use type hints instead of :type and :rtype

This commit is contained in:
Anthony Sottile 2022-01-05 14:07:13 -05:00
parent e1d737906c
commit 741ff11bfb
16 changed files with 77 additions and 184 deletions

View file

@ -19,7 +19,7 @@ import flake8
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = "1.3"
needs_sphinx = "2.1"
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
@ -306,3 +306,5 @@ extlinks = {
"issue": ("https://github.com/pycqa/flake8/issues/%s", "#"),
"pull": ("https://github.com/pycqa/flake8/pull/%s", "#"),
}
autodoc_typehints = "description"

View file

@ -34,23 +34,21 @@ accepts as well as what it returns.
.. code-block:: python
# src/flake8/main/git.py
def hook(lazy=False, strict=False):
def hook(lazy: bool = False, strict: bool = False) -> int:
"""Execute Flake8 on the files in git's index.
Determine which files are about to be committed and run Flake8 over them
to check for violations.
:param bool lazy:
:param lazy:
Find files not added to the index prior to committing. This is useful
if you frequently use ``git commit -a`` for example. This defaults to
False since it will otherwise include files not in the index.
:param bool strict:
:param strict:
If True, return the total number of errors/violations found by Flake8.
This will cause the hook to fail.
:returns:
Total number of errors found during the run.
:rtype:
int
"""
# NOTE(sigmavirus24): Delay import of application until we need it.
from flake8.main import application
@ -66,39 +64,9 @@ accepts as well as what it returns.
return app.result_count
return 0
Note that because the parameters ``hook`` and ``strict`` are simply boolean
parameters, we inline the type declaration for those parameters, e.g.,
.. code-block:: restructuredtext
:param bool lazy:
Also note that we begin the description of the parameter on a new-line and
Note that we begin the description of the parameter on a new-line and
indented 4 spaces.
On the other hand, we also separate the parameter type declaration in some
places where the name is a little longer, e.g.,
.. code-block:: python
# src/flake8/formatting/base.py
def format(self, error):
"""Format an error reported by Flake8.
This method **must** be implemented by subclasses.
:param error:
This will be an instance of :class:`~flake8.style_guide.Error`.
:type error:
flake8.style_guide.Error
:returns:
The formatted error string.
:rtype:
str
"""
Here we've separated ``:param error:`` and ``:type error:``.
Following the above examples and guidelines should help you write doc-strings
that are stylistically correct for |Flake8|.

View file

@ -48,9 +48,9 @@ def configure_logging(
) -> None:
"""Configure logging for flake8.
:param int verbosity:
:param verbosity:
How verbose to be in logging information.
:param str filename:
:param filename:
Name of the file to append log information to.
If ``None`` this will log to ``sys.stderr``.
If the name is "stdout" or "stderr" this will log to the appropriate

View file

@ -60,8 +60,6 @@ class Report:
List of occurrences of a violation formatted as:
{Count} {Error Code} {Message}, e.g.,
``8 E531 Some error message about the error``
:rtype:
list
"""
return [
f"{s.count} {s.error_code} {s.message}"
@ -110,12 +108,10 @@ class StyleGuide:
This will check the files passed in and return a :class:`Report`
instance.
:param list paths:
:param paths:
List of filenames (or paths) to check.
:returns:
Object that mimic's Flake8 2.0's Reporter class.
:rtype:
flake8.api.legacy.Report
"""
assert self._application.options is not None
self._application.options.filenames = paths
@ -126,14 +122,12 @@ class StyleGuide:
def excluded(self, filename: str, parent: Optional[str] = None) -> bool:
"""Determine if a file is excluded.
:param str filename:
:param filename:
Path to the file to check if it is excluded.
:param str parent:
:param parent:
Name of the parent directory containing the file.
:returns:
True if the filename is excluded, False otherwise.
:rtype:
bool
"""
def excluded(path: str) -> bool:
@ -186,18 +180,16 @@ class StyleGuide:
This will check the file passed in and return a :class:`Report`
instance.
:param str filename:
:param filename:
The path to the file to check.
:param list lines:
:param lines:
Ignored since Flake8 3.0.
:param expected:
Ignored since Flake8 3.0.
:param int line_offset:
:param line_offset:
Ignored since Flake8 3.0.
:returns:
Object that mimic's Flake8 2.0's Reporter class.
:rtype:
flake8.api.legacy.Report
"""
return self.check_files([filename])
@ -209,8 +201,6 @@ def get_style_guide(**kwargs: Any) -> StyleGuide:
Keyword arguments that provide some options for the StyleGuide.
:returns:
An initialized StyleGuide
:rtype:
:class:`StyleGuide`
"""
application = app.Application()
prelim_opts, remaining_args = application.parse_preliminary_options([])

View file

@ -182,8 +182,6 @@ class Manager:
:returns:
A tuple of the total results found and the results reported.
:rtype:
tuple(int, int)
"""
results_reported = results_found = 0
for checker in self._all_checkers:
@ -260,7 +258,7 @@ class Manager:
def start(self, paths: Optional[List[str]] = None) -> None:
"""Start checking files.
:param list paths:
:param paths:
Path names to check. This is passed directly to
:meth:`~Manager.make_checkers`.
"""

View file

@ -17,9 +17,9 @@ def _filenames_from(
) -> Generator[str, None, None]:
"""Generate filenames from an argument.
:param str arg:
:param arg:
Parameter from the command-line.
:param callable predicate:
:param predicate:
Predicate to use to filter out filenames. If the predicate
returns ``True`` we will exclude the filename, otherwise we
will yield it. By default, we include every filename

View file

@ -43,8 +43,6 @@ class BaseFormatter:
:param options:
User specified configuration parsed from both configuration files
and the command-line interface.
:type options:
:class:`argparse.Namespace`
"""
self.options = options
self.filename = options.output_file
@ -63,7 +61,7 @@ class BaseFormatter:
def beginning(self, filename: str) -> None:
"""Notify the formatter that we're starting to process a file.
:param str filename:
:param filename:
The name of the file that Flake8 is beginning to report results
from.
"""
@ -71,7 +69,7 @@ class BaseFormatter:
def finished(self, filename: str) -> None:
"""Notify the formatter that we've finished processing a file.
:param str filename:
:param filename:
The name of the file that Flake8 has finished reporting results
from.
"""
@ -96,8 +94,6 @@ class BaseFormatter:
:param error:
This will be an instance of
:class:`~flake8.violation.Violation`.
:type error:
flake8.violation.Violation
"""
line = self.format(error)
source = self.show_source(error)
@ -111,12 +107,8 @@ class BaseFormatter:
:param error:
This will be an instance of
:class:`~flake8.violation.Violation`.
:type error:
flake8.violation.Violation
:returns:
The formatted error string.
:rtype:
str
"""
raise NotImplementedError(
"Subclass of BaseFormatter did not implement" " format."
@ -161,14 +153,10 @@ class BaseFormatter:
:param error:
This will be an instance of
:class:`~flake8.violation.Violation`.
:type error:
flake8.violation.Violation
:returns:
The formatted error string if the user wants to show the source.
If the user does not want to show the source, this will return
``None``.
:rtype:
str
"""
if not self.options.show_source or error.physical_line is None:
return ""
@ -197,9 +185,9 @@ class BaseFormatter:
out for subclasses. Override this if you want behaviour that differs
from the default.
:param str line:
:param line:
The formatted string to print or write.
:param str source:
:param source:
The source code that has been formatted and associated with the
line of output.
"""

View file

@ -35,13 +35,7 @@ class Application:
"""Abstract our application into a class."""
def __init__(self) -> None:
"""Initialize our application.
:param str program:
The name of the program/application that we're executing.
:param str version:
The version of the program/application we're executing.
"""
"""Initialize our application."""
#: The timestamp when the Application instance was instantiated.
self.start_time = time.time()
#: The timestamp when the Application finished reported errors.
@ -91,12 +85,10 @@ class Application:
options; we ignore those for now, they'll be parsed later when we do
real option parsing.
:param list argv:
:param argv:
Command-line arguments passed in directly.
:returns:
Populated namespace and list of remaining argument strings.
:rtype:
(argparse.Namespace, list)
"""
args, rest = self.prelim_arg_parser.parse_known_args(argv)
# XXX (ericvw): Special case "forwarding" the output file option so

View file

@ -12,7 +12,7 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
This handles the creation of an instance of :class:`Application`, runs it,
and then exits the application.
:param list argv:
:param argv:
The arguments to be passed to the application for parsing.
"""
if argv is None:

View file

@ -77,8 +77,7 @@ class JobsArgument:
def __init__(self, arg: str) -> None:
"""Parse and validate the --jobs argument.
:param str arg:
The argument passed by argparse for validation
:param arg: The argument passed by argparse for validation
"""
self.is_auto = False
self.n_jobs = -1

View file

@ -125,10 +125,10 @@ class Option:
The following are all passed directly through to argparse.
:param str short_option_name:
:param short_option_name:
The short name of the option (e.g., ``-x``). This will be the
first argument passed to ``ArgumentParser.add_argument``
:param str long_option_name:
:param long_option_name:
The long name of the option (e.g., ``--xtra-long-option``). This
will be the second argument passed to
``ArgumentParser.add_argument``
@ -141,13 +141,13 @@ class Option:
:param const:
Constant value to store on a common destination. Usually used in
conjunction with ``action="store_const"``.
:param iterable choices:
:param choices:
Possible values for the option.
:param str help:
:param help:
Help text displayed in the usage information.
:param str metavar:
:param metavar:
Name to use instead of the long option name for help text.
:param bool required:
:param required:
Whether this option is required or not.
The following options may be passed directly through to :mod:`argparse`
@ -157,28 +157,28 @@ class Option:
A callable to normalize the type (as is the case in
:mod:`argparse`). Deprecated: you can also pass through type
strings such as ``'int'`` which are handled by :mod:`optparse`.
:param str action:
:param action:
Any action allowed by :mod:`argparse`. Deprecated: this also
understands the ``action='callback'`` action from :mod:`optparse`.
:param callable callback:
:param callback:
Callback used if the action is ``"callback"``. Deprecated: please
use ``action=`` instead.
:param iterable callback_args:
:param callback_args:
Additional positional arguments to the callback callable.
Deprecated: please use ``action=`` instead (probably with
``functools.partial``).
:param dictionary callback_kwargs:
:param callback_kwargs:
Keyword arguments to the callback callable. Deprecated: please
use ``action=`` instead (probably with ``functools.partial``).
The following parameters are for Flake8's option handling alone.
:param bool parse_from_config:
:param parse_from_config:
Whether or not this option should be parsed out of config files.
:param bool comma_separated_list:
:param comma_separated_list:
Whether the option is a comma separated list when parsing from a
config file.
:param bool normalize_paths:
:param normalize_paths:
Whether the option is expecting a path or list of paths and should
attempt to normalize the paths to absolute paths.
"""
@ -325,13 +325,13 @@ class OptionManager:
) -> None:
"""Initialize an instance of an OptionManager.
:param str prog:
:param prog:
Name of the actual program (e.g., flake8).
:param str version:
:param version:
Version string for the program.
:param str usage:
:param usage:
Basic usage string used by the OptionParser.
:param argparse.ArgumentParser parents:
:param parents:
A list of ArgumentParser objects whose arguments should also be
included.
"""
@ -410,7 +410,7 @@ class OptionManager:
def remove_from_default_ignore(self, error_codes: Sequence[str]) -> None:
"""Remove specified error codes from the default ignore list.
:param list error_codes:
:param error_codes:
List of strings that are the error/warning codes to attempt to
remove from the extended default ignore list.
"""
@ -428,7 +428,7 @@ class OptionManager:
def extend_default_ignore(self, error_codes: Sequence[str]) -> None:
"""Extend the default ignore list with the error codes provided.
:param list error_codes:
:param error_codes:
List of strings that are the error/warning codes with which to
extend the default ignore list.
"""
@ -438,7 +438,7 @@ class OptionManager:
def extend_default_select(self, error_codes: Sequence[str]) -> None:
"""Extend the default select list with the error codes provided.
:param list error_codes:
:param error_codes:
List of strings that are the error/warning codes with which
to extend the default select list.
"""

View file

@ -67,8 +67,7 @@ class FileProcessor:
) -> None:
"""Initialice our file processor.
:param str filename:
Name of the file to process
:param filename: Name of the file to process
"""
self.options = options
self.filename = filename
@ -355,8 +354,6 @@ class FileProcessor:
:returns:
True if a line matches :attr:`defaults.NOQA_FILE`,
otherwise False
:rtype:
bool
"""
if not self.options.disable_noqa and any(
defaults.NOQA_FILE.match(line) for line in self.lines

View file

@ -20,8 +20,6 @@ class Statistics:
:returns:
Sorted list of error codes.
:rtype:
list(str)
"""
return sorted({key.code for key in self._store})
@ -31,8 +29,6 @@ class Statistics:
:param error:
The Violation instance containing the information about the
violation.
:type error:
flake8.violation.Violation
"""
key = Key.create_from(error)
if key not in self._store:
@ -57,9 +53,9 @@ class Statistics:
>>> stats.statistics_for('W')
<generator ...>
:param str prefix:
:param prefix:
The error class or specific error code to find statistics for.
:param str filename:
:param filename:
(Optional) The filename to further filter results by.
:returns:
Generator of instances of :class:`Statistic`
@ -90,16 +86,14 @@ class Key(NamedTuple):
def matches(self, prefix: str, filename: Optional[str]) -> bool:
"""Determine if this key matches some constraints.
:param str prefix:
:param prefix:
The error code prefix that this key's error code should start with.
:param str filename:
:param filename:
The filename that we potentially want to match on. This can be
None to only match on error prefix.
:returns:
True if the Key's code starts with the prefix and either filename
is None, or the Key's filename matches the value passed in.
:rtype:
bool
"""
return self.code.startswith(prefix) and (
filename is None or self.filename == filename

View file

@ -89,8 +89,7 @@ class DecisionEngine:
def was_selected(self, code: str) -> Union[Selected, Ignored]:
"""Determine if the code has been selected by the user.
:param str code:
The code for the check that has been run.
:param code: The code for the check that has been run.
:returns:
Selected.Implicitly if the selected list is empty,
Selected.Explicitly if the selected list is not empty and a match
@ -112,7 +111,7 @@ class DecisionEngine:
def was_ignored(self, code: str) -> Union[Selected, Ignored]:
"""Determine if the code has been ignored by the user.
:param str code:
:param code:
The code for the check that has been run.
:returns:
Selected.Implicitly if the ignored list is empty,
@ -211,8 +210,7 @@ class DecisionEngine:
This method does not look at whether the specific line is being
ignored in the file itself.
:param str code:
The code for the check that has been run.
:param code: The code for the check that has been run.
"""
decision = self.cache.get(code)
if decision is None:
@ -257,12 +255,8 @@ class StyleGuideManager:
:param options:
The original options parsed from the CLI and config file.
:type options:
:class:`~argparse.Namespace`
:returns:
A copy of the default style guide with overridden values.
:rtype:
:class:`~flake8.style_guide.StyleGuide`
"""
per_file = utils.parse_files_to_codes_mapping(options.per_file_ignores)
for filename, violations in per_file:
@ -301,25 +295,23 @@ class StyleGuideManager:
) -> int:
"""Handle an error reported by a check.
:param str code:
:param code:
The error code found, e.g., E123.
:param str filename:
:param filename:
The file in which the error was found.
:param int line_number:
:param line_number:
The line number (where counting starts at 1) at which the error
occurs.
:param int column_number:
:param column_number:
The column number (where counting starts at 1) at which the error
occurs.
:param str text:
:param text:
The text of the error message.
:param str physical_line:
:param physical_line:
The actual physical line causing the error.
:returns:
1 if the error was reported. 0 if it was ignored. This is to allow
for counting of the number of errors found that were not ignored.
:rtype:
int
"""
guide = self.style_guide_for(filename)
return guide.handle_error(
@ -332,7 +324,7 @@ class StyleGuideManager:
This provides information to the underlying StyleGuides so that only
the errors in the line number ranges are reported.
:param dict diffinfo:
:param diffinfo:
Dictionary mapping filenames to sets of line number ranges.
"""
for guide in self.style_guides:
@ -392,13 +384,11 @@ class StyleGuide:
def applies_to(self, filename: str) -> bool:
"""Check if this StyleGuide applies to the file.
:param str filename:
:param filename:
The name of the file with violations that we're potentially
applying this StyleGuide to.
:returns:
True if this applies, False otherwise
:rtype:
bool
"""
if self.filename is None:
return True
@ -418,7 +408,7 @@ class StyleGuide:
This method does not look at whether the specific line is being
ignored in the file itself.
:param str code:
:param code:
The code for the check that has been run.
"""
return self.decider.decision_for(code)
@ -434,25 +424,23 @@ class StyleGuide:
) -> int:
"""Handle an error reported by a check.
:param str code:
:param code:
The error code found, e.g., E123.
:param str filename:
:param filename:
The file in which the error was found.
:param int line_number:
:param line_number:
The line number (where counting starts at 1) at which the error
occurs.
:param int column_number:
:param column_number:
The column number (where counting starts at 1) at which the error
occurs.
:param str text:
:param text:
The text of the error message.
:param str physical_line:
:param physical_line:
The actual physical line causing the error.
:returns:
1 if the error was reported. 0 if it was ignored. This is to allow
for counting of the number of errors found that were not ignored.
:rtype:
int
"""
disable_noqa = self.options.disable_noqa
# NOTE(sigmavirus24): Apparently we're provided with 0-indexed column
@ -485,7 +473,7 @@ class StyleGuide:
This provides information to the StyleGuide so that only the errors
in the line number ranges are reported.
:param dict diffinfo:
:param diffinfo:
Dictionary mapping filenames to sets of line number ranges.
"""
self._parsed_diff = diffinfo

View file

@ -37,12 +37,8 @@ def parse_comma_separated_list(
:param regexp:
Compiled regular expression used to split the value when it is a
string.
:type regexp:
_sre.SRE_Pattern
:returns:
List of values with whitespace stripped.
:rtype:
list
"""
assert isinstance(value, str), value
@ -94,7 +90,6 @@ def parse_files_to_codes_mapping( # noqa: C901
either comma or whitespace tokens.
:param value: String to be parsed and normalized.
:type value: str
"""
if not isinstance(value_, str):
value = "\n".join(value_)
@ -166,8 +161,6 @@ def normalize_paths(
:returns:
The normalized paths.
:rtype:
[str]
"""
assert isinstance(paths, list), paths
return [normalize_path(p, parent) for p in paths]
@ -178,8 +171,6 @@ def normalize_path(path: str, parent: str = os.curdir) -> str:
:returns:
The normalized path.
:rtype:
str
"""
# NOTE(sigmavirus24): Using os.path.sep and os.path.altsep allow for
# Windows compatibility with both Windows-style paths (c:\foo\bar) and
@ -219,8 +210,6 @@ def parse_unified_diff(diff: Optional[str] = None) -> Dict[str, Set[int]]:
:returns:
dictionary mapping file names to sets of line numbers
:rtype:
dict
"""
# Allow us to not have to patch out stdin_get_value
if diff is None:
@ -284,12 +273,10 @@ def parse_unified_diff(diff: Optional[str] = None) -> Dict[str, Set[int]]:
def is_using_stdin(paths: List[str]) -> bool:
"""Determine if we're going to read from stdin.
:param list paths:
:param paths:
The paths that we're going to check.
:returns:
True if stdin (-) is in the path, otherwise False
:rtype:
bool
"""
return "-" in paths
@ -297,11 +284,11 @@ def is_using_stdin(paths: List[str]) -> bool:
def fnmatch(filename: str, patterns: Sequence[str]) -> bool:
"""Wrap :func:`fnmatch.fnmatch` to add some functionality.
:param str filename:
:param filename:
Name of the file we're trying to match.
:param list patterns:
:param patterns:
Patterns we're using to try to match the filename.
:param bool default:
:param default:
The default value if patterns is empty
:returns:
True if a pattern matches the filename, False if it doesn't.
@ -320,18 +307,14 @@ def matches_filename(
) -> bool:
"""Use fnmatch to discern if a path exists in patterns.
:param str path:
:param path:
The path to the file under question
:param patterns:
The patterns to match the path against.
:type patterns:
list[str]
:param str log_message:
:param log_message:
The message used for logging purposes.
:returns:
True if path matches patterns, False otherwise
:rtype:
bool
"""
if not patterns:
return False
@ -354,8 +337,6 @@ def get_python_version() -> str:
:returns:
Implementation name, version, and platform as a string.
:rtype:
str
"""
return "{} {} on {}".format(
platform.python_implementation(),

View file

@ -33,12 +33,10 @@ class Violation(NamedTuple):
def is_inline_ignored(self, disable_noqa: bool) -> bool:
"""Determine if a comment has been added to ignore this line.
:param bool disable_noqa:
:param disable_noqa:
Whether or not users have provided ``--disable-noqa``.
:returns:
True if error is ignored in-line, False otherwise.
:rtype:
bool
"""
physical_line = self.physical_line
# TODO(sigmavirus24): Determine how to handle stdin with linecache
@ -88,8 +86,6 @@ class Violation(NamedTuple):
True if there is no diff or if the error is in the diff's line
number ranges. False if the error's line number falls outside
the diff's line number ranges.
:rtype:
bool
"""
if not diff:
return True