Skip to content

Commit cb36e20

Browse files
committedMar 31, 2021
com2ann
1 parent 64a610e commit cb36e20

19 files changed

+361
-389
lines changed
 

‎src/flake8/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def configure_logging(verbosity, filename=None, logformat=LOG_FORMAT):
6262

6363
if not filename or filename in ("stderr", "stdout"):
6464
fileobj = getattr(sys, filename or "stderr")
65-
handler_cls = logging.StreamHandler # type: Type[logging.Handler]
65+
handler_cls: Type[logging.Handler] = logging.StreamHandler
6666
else:
6767
fileobj = filename
6868
handler_cls = logging.FileHandler

‎src/flake8/api/legacy.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def __init__(self, application):
8181
self._file_checker_manager = application.file_checker_manager
8282

8383
@property
84-
def options(self): # type: () -> argparse.Namespace
84+
def options(self) -> argparse.Namespace:
8585
"""Return application's options.
8686
8787
An instance of :class:`argparse.Namespace` containing parsed options.

‎src/flake8/checker.py

+32-31
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,8 @@ def __init__(self, style_guide, arguments, checker_plugins):
8585
self.options = style_guide.options
8686
self.checks = checker_plugins
8787
self.jobs = self._job_count()
88-
self._all_checkers = [] # type: List[FileChecker]
89-
self.checkers = [] # type: List[FileChecker]
88+
self._all_checkers: List[FileChecker] = []
89+
self.checkers: List[FileChecker] = []
9090
self.statistics = {
9191
"files": 0,
9292
"logical lines": 0,
@@ -103,8 +103,7 @@ def _process_statistics(self):
103103
self.statistics[statistic] += checker.statistics[statistic]
104104
self.statistics["files"] += len(self.checkers)
105105

106-
def _job_count(self):
107-
# type: () -> int
106+
def _job_count(self) -> int:
108107
# First we walk through all of our error cases:
109108
# - multiprocessing library is not present
110109
# - we're running on windows in which case we know we have significant
@@ -165,8 +164,7 @@ def _handle_results(self, filename, results):
165164
)
166165
return reported_results_count
167166

168-
def is_path_excluded(self, path):
169-
# type: (str) -> bool
167+
def is_path_excluded(self, path: str) -> bool:
170168
"""Check if a path is excluded.
171169
172170
:param str path:
@@ -189,8 +187,7 @@ def is_path_excluded(self, path):
189187
logger=LOG,
190188
)
191189

192-
def make_checkers(self, paths=None):
193-
# type: (Optional[List[str]]) -> None
190+
def make_checkers(self, paths: Optional[List[str]] = None) -> None:
194191
"""Create checkers for each file."""
195192
if paths is None:
196193
paths = self.arguments
@@ -235,8 +232,7 @@ def should_create_file_checker(filename, argument):
235232
self.checkers = [c for c in self._all_checkers if c.should_process]
236233
LOG.info("Checking %d files", len(self.checkers))
237234

238-
def report(self):
239-
# type: () -> Tuple[int, int]
235+
def report(self) -> Tuple[int, int]:
240236
"""Report all of the errors found in the managed file checkers.
241237
242238
This iterates over each of the checkers and reports the errors sorted
@@ -258,11 +254,11 @@ def report(self):
258254
results_found += len(results)
259255
return (results_found, results_reported)
260256

261-
def run_parallel(self): # type: () -> None
257+
def run_parallel(self) -> None:
262258
"""Run the checkers in parallel."""
263259
# fmt: off
264-
final_results = collections.defaultdict(list) # type: Dict[str, List[Tuple[str, int, int, str, Optional[str]]]] # noqa: E501
265-
final_statistics = collections.defaultdict(dict) # type: Dict[str, Dict[str, int]] # noqa: E501
260+
final_results: Dict[str, List[Tuple[str, int, int, str, Optional[str]]]] = collections.defaultdict(list) # noqa: E501
261+
final_statistics: Dict[str, Dict[str, int]] = collections.defaultdict(dict) # noqa: E501
266262
# fmt: on
267263

268264
pool = _try_initialize_processpool(self.jobs)
@@ -297,12 +293,12 @@ def run_parallel(self): # type: () -> None
297293
checker.results = final_results[filename]
298294
checker.statistics = final_statistics[filename]
299295

300-
def run_serial(self): # type: () -> None
296+
def run_serial(self) -> None:
301297
"""Run the checkers in serial."""
302298
for checker in self.checkers:
303299
checker.run_checks()
304300

305-
def run(self): # type: () -> None
301+
def run(self) -> None:
306302
"""Run all the checkers.
307303
308304
This will intelligently decide whether to run the checks in parallel
@@ -356,9 +352,7 @@ def __init__(self, filename, checks, options):
356352
self.options = options
357353
self.filename = filename
358354
self.checks = checks
359-
# fmt: off
360-
self.results = [] # type: List[Tuple[str, int, int, str, Optional[str]]] # noqa: E501
361-
# fmt: on
355+
self.results: List[Tuple[str, int, int, str, Optional[str]]] = []
362356
self.statistics = {
363357
"tokens": 0,
364358
"logical lines": 0,
@@ -372,12 +366,11 @@ def __init__(self, filename, checks, options):
372366
self.should_process = not self.processor.should_ignore_file()
373367
self.statistics["physical lines"] = len(self.processor.lines)
374368

375-
def __repr__(self): # type: () -> str
369+
def __repr__(self) -> str:
376370
"""Provide helpful debugging representation."""
377371
return f"FileChecker for {self.filename}"
378372

379-
def _make_processor(self):
380-
# type: () -> Optional[processor.FileProcessor]
373+
def _make_processor(self) -> Optional[processor.FileProcessor]:
381374
try:
382375
return processor.FileProcessor(self.filename, self.options)
383376
except OSError as e:
@@ -391,8 +384,13 @@ def _make_processor(self):
391384
self.report("E902", 0, 0, message)
392385
return None
393386

394-
def report(self, error_code, line_number, column, text):
395-
# type: (Optional[str], int, int, str) -> str
387+
def report(
388+
self,
389+
error_code: Optional[str],
390+
line_number: int,
391+
column: int,
392+
text: str,
393+
) -> str:
396394
"""Report an error by storing it in the results list."""
397395
if error_code is None:
398396
error_code, text = text.split(" ", 1)
@@ -468,7 +466,7 @@ def _extract_syntax_information(exception):
468466
column -= column_offset
469467
return row, column
470468

471-
def run_ast_checks(self): # type: () -> None
469+
def run_ast_checks(self) -> None:
472470
"""Run all checks expecting an abstract syntax tree."""
473471
try:
474472
ast = self.processor.build_ast()
@@ -610,8 +608,9 @@ def handle_newline(self, token_type):
610608
else:
611609
self.run_logical_checks()
612610

613-
def check_physical_eol(self, token, prev_physical):
614-
# type: (processor._Token, str) -> None
611+
def check_physical_eol(
612+
self, token: processor._Token, prev_physical: str
613+
) -> None:
615614
"""Run physical checks if and only if it is at the end of the line."""
616615
# a newline token ends a single physical line.
617616
if processor.is_eol_token(token):
@@ -640,13 +639,14 @@ def check_physical_eol(self, token, prev_physical):
640639
self.run_physical_checks(line + "\n")
641640

642641

643-
def _pool_init(): # type: () -> None
642+
def _pool_init() -> None:
644643
"""Ensure correct signaling of ^C using multiprocessing.Pool."""
645644
signal.signal(signal.SIGINT, signal.SIG_IGN)
646645

647646

648-
def _try_initialize_processpool(job_count):
649-
# type: (int) -> Optional[multiprocessing.pool.Pool]
647+
def _try_initialize_processpool(
648+
job_count: int,
649+
) -> Optional[multiprocessing.pool.Pool]:
650650
"""Return a new process pool instance if we are able to create one."""
651651
try:
652652
return multiprocessing.Pool(job_count, _pool_init)
@@ -675,8 +675,9 @@ def _run_checks(checker):
675675
return checker.run_checks()
676676

677677

678-
def find_offset(offset, mapping):
679-
# type: (int, processor._LogicalMapping) -> Tuple[int, int]
678+
def find_offset(
679+
offset: int, mapping: processor._LogicalMapping
680+
) -> Tuple[int, int]:
680681
"""Find the offset tuple for a single offset."""
681682
if isinstance(offset, tuple):
682683
return offset

‎src/flake8/exceptions.py

+8-11
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,13 @@ class FailedToLoadPlugin(Flake8Exception):
1919

2020
FORMAT = 'Flake8 failed to load plugin "%(name)s" due to %(exc)s.'
2121

22-
def __init__(self, plugin_name, exception):
23-
# type: (str, Exception) -> None
22+
def __init__(self, plugin_name: str, exception: Exception) -> None:
2423
"""Initialize our FailedToLoadPlugin exception."""
2524
self.plugin_name = plugin_name
2625
self.original_exception = exception
2726
super().__init__(plugin_name, exception)
2827

29-
def __str__(self): # type: () -> str
28+
def __str__(self) -> str:
3029
"""Format our exception message."""
3130
return self.FORMAT % {
3231
"name": self.plugin_name,
@@ -37,7 +36,7 @@ def __str__(self): # type: () -> str
3736
class InvalidSyntax(Flake8Exception):
3837
"""Exception raised when tokenizing a file fails."""
3938

40-
def __init__(self, exception): # type: (Exception) -> None
39+
def __init__(self, exception: Exception) -> None:
4140
"""Initialize our InvalidSyntax exception."""
4241
self.original_exception = exception
4342
self.error_message = "{}: {}".format(
@@ -48,7 +47,7 @@ def __init__(self, exception): # type: (Exception) -> None
4847
self.column_number = 0
4948
super().__init__(exception)
5049

51-
def __str__(self): # type: () -> str
50+
def __str__(self) -> str:
5251
"""Format our exception message."""
5352
return self.error_message
5453

@@ -58,14 +57,13 @@ class PluginRequestedUnknownParameters(Flake8Exception):
5857

5958
FORMAT = '"%(name)s" requested unknown parameters causing %(exc)s'
6059

61-
def __init__(self, plugin, exception):
62-
# type: (Dict[str, str], Exception) -> None
60+
def __init__(self, plugin: Dict[str, str], exception: Exception) -> None:
6361
"""Pop certain keyword arguments for initialization."""
6462
self.plugin = plugin
6563
self.original_exception = exception
6664
super().__init__(plugin, exception)
6765

68-
def __str__(self): # type: () -> str
66+
def __str__(self) -> str:
6967
"""Format our exception message."""
7068
return self.FORMAT % {
7169
"name": self.plugin["plugin_name"],
@@ -78,14 +76,13 @@ class PluginExecutionFailed(Flake8Exception):
7876

7977
FORMAT = '"%(name)s" failed during execution due to "%(exc)s"'
8078

81-
def __init__(self, plugin, exception):
82-
# type: (Dict[str, str], Exception) -> None
79+
def __init__(self, plugin: Dict[str, str], exception: Exception) -> None:
8380
"""Utilize keyword arguments for message generation."""
8481
self.plugin = plugin
8582
self.original_exception = exception
8683
super().__init__(plugin, exception)
8784

88-
def __str__(self): # type: () -> str
85+
def __str__(self) -> str:
8986
"""Format our exception message."""
9087
return self.FORMAT % {
9188
"name": self.plugin["plugin_name"],

‎src/flake8/formatting/base.py

+14-17
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,7 @@ class BaseFormatter:
3333
output filename has been specified.
3434
"""
3535

36-
def __init__(self, options):
37-
# type: (argparse.Namespace) -> None
36+
def __init__(self, options: argparse.Namespace) -> None:
3837
"""Initialize with the options parsed from config and cli.
3938
4039
This also calls a hook, :meth:`after_init`, so subclasses do not need
@@ -48,38 +47,38 @@ def __init__(self, options):
4847
"""
4948
self.options = options
5049
self.filename = options.output_file
51-
self.output_fd = None # type: Optional[IO[str]]
50+
self.output_fd: Optional[IO[str]] = None
5251
self.newline = "\n"
5352
self.after_init()
5453

55-
def after_init(self): # type: () -> None
54+
def after_init(self) -> None:
5655
"""Initialize the formatter further."""
5756

58-
def beginning(self, filename): # type: (str) -> None
57+
def beginning(self, filename: str) -> None:
5958
"""Notify the formatter that we're starting to process a file.
6059
6160
:param str filename:
6261
The name of the file that Flake8 is beginning to report results
6362
from.
6463
"""
6564

66-
def finished(self, filename): # type: (str) -> None
65+
def finished(self, filename: str) -> None:
6766
"""Notify the formatter that we've finished processing a file.
6867
6968
:param str filename:
7069
The name of the file that Flake8 has finished reporting results
7170
from.
7271
"""
7372

74-
def start(self): # type: () -> None
73+
def start(self) -> None:
7574
"""Prepare the formatter to receive input.
7675
7776
This defaults to initializing :attr:`output_fd` if :attr:`filename`
7877
"""
7978
if self.filename:
8079
self.output_fd = open(self.filename, "a")
8180

82-
def handle(self, error): # type: (Violation) -> None
81+
def handle(self, error: "Violation") -> None:
8382
"""Handle an error reported by Flake8.
8483
8584
This defaults to calling :meth:`format`, :meth:`show_source`, and
@@ -96,7 +95,7 @@ def handle(self, error): # type: (Violation) -> None
9695
source = self.show_source(error)
9796
self.write(line, source)
9897

99-
def format(self, error): # type: (Violation) -> Optional[str]
98+
def format(self, error: "Violation") -> Optional[str]:
10099
"""Format an error reported by Flake8.
101100
102101
This method **must** be implemented by subclasses.
@@ -115,7 +114,7 @@ def format(self, error): # type: (Violation) -> Optional[str]
115114
"Subclass of BaseFormatter did not implement" " format."
116115
)
117116

118-
def show_statistics(self, statistics): # type: (Statistics) -> None
117+
def show_statistics(self, statistics: "Statistics") -> None:
119118
"""Format and print the statistics."""
120119
for error_code in statistics.error_codes():
121120
stats_for_error_code = statistics.statistics_for(error_code)
@@ -130,8 +129,7 @@ def show_statistics(self, statistics): # type: (Statistics) -> None
130129
)
131130
)
132131

133-
def show_benchmarks(self, benchmarks):
134-
# type: (List[Tuple[str, float]]) -> None
132+
def show_benchmarks(self, benchmarks: List[Tuple[str, float]]) -> None:
135133
"""Format and print the benchmarks."""
136134
# NOTE(sigmavirus24): The format strings are a little confusing, even
137135
# to me, so here's a quick explanation:
@@ -152,7 +150,7 @@ def show_benchmarks(self, benchmarks):
152150
benchmark = float_format(statistic=statistic, value=value)
153151
self._write(benchmark)
154152

155-
def show_source(self, error): # type: (Violation) -> Optional[str]
153+
def show_source(self, error: "Violation") -> Optional[str]:
156154
"""Show the physical line generating the error.
157155
158156
This also adds an indicator for the particular part of the line that
@@ -183,15 +181,14 @@ def show_source(self, error): # type: (Violation) -> Optional[str]
183181
# one
184182
return f"{error.physical_line}{indent}^"
185183

186-
def _write(self, output): # type: (str) -> None
184+
def _write(self, output: str) -> None:
187185
"""Handle logic of whether to use an output file or print()."""
188186
if self.output_fd is not None:
189187
self.output_fd.write(output + self.newline)
190188
if self.output_fd is None or self.options.tee:
191189
print(output, end=self.newline)
192190

193-
def write(self, line, source):
194-
# type: (Optional[str], Optional[str]) -> None
191+
def write(self, line: Optional[str], source: Optional[str]) -> None:
195192
"""Write the line either to the output file or stdout.
196193
197194
This handles deciding whether to write to a file or print to standard
@@ -209,7 +206,7 @@ def write(self, line, source):
209206
if source:
210207
self._write(source)
211208

212-
def stop(self): # type: () -> None
209+
def stop(self) -> None:
213210
"""Clean up after reporting is finished."""
214211
if self.output_fd is not None:
215212
self.output_fd.close()

0 commit comments

Comments
 (0)
Please sign in to comment.