PK!uh$wemake_python_styleguide/__init__.py# -*- coding: utf-8 -*- PK!a#wemake_python_styleguide/checker.py# -*- coding: utf-8 -*- """ Entry point to the app. Represents a :term:`checker` business entity. There's only a single checker instance that runs a lot of :term:`visitors `. .. mermaid:: :caption: Checker relation with visitors. graph TD C1[Checker] --> V1[Visitor 1] C1[Checker] --> V2[Visitor 2] C1[Checker] --> VN[Visitor N] That's how all ``flake8`` plugins work: .. mermaid:: :caption: ``flake8`` API calls order. graph LR F1[flake8] --> F2[add_options] F2 --> F3[parse_options] F3 --> F4[__init__] F4 --> F5[run] .. _checker: Checker API ----------- .. autoclass:: Checker :no-undoc-members: :exclude-members: name, version, visitors, _run_checks :special-members: __init__ """ import ast import tokenize from typing import ClassVar, Iterator, Sequence, Type from flake8.options.manager import OptionManager from wemake_python_styleguide import constants, types from wemake_python_styleguide import version as pkg_version from wemake_python_styleguide.options.config import Configuration from wemake_python_styleguide.presets import complexity, general, tokens from wemake_python_styleguide.transformations.ast_tree import transform from wemake_python_styleguide.visitors import base VisitorClass = Type[base.BaseVisitor] @types.final class Checker(object): """ Implementation of :term:`checker`. See also: http://flake8.pycqa.org/en/latest/plugin-development/index.html Attributes: name: required by the ``flake8`` API, should match the package name. version: required by the ``flake8`` API, defined in the packaging file. config: custom configuration object used to provide and parse options: :class:`wemake_python_styleguide.options.config.Configuration`. options: option structure passed by ``flake8``: :class:`wemake_python_styleguide.types.ConfigurationOptions`. visitors: :term:`preset` of visitors that are run by this checker. """ name: ClassVar[str] = pkg_version.pkg_name version: ClassVar[str] = pkg_version.pkg_version config = Configuration() options: types.ConfigurationOptions visitors: ClassVar[Sequence[VisitorClass]] = ( *general.GENERAL_PRESET, *complexity.COMPLEXITY_PRESET, *tokens.TOKENS_PRESET, ) def __init__( self, tree: ast.AST, file_tokens: Sequence[tokenize.TokenInfo], filename: str = constants.STDIN, ) -> None: """ Creates new checker instance. These parameter names should not be changed. ``flake8`` has special API that passes concrete parameters to the plugins that ask for them. ``flake8`` also decides how to execute this plugin based on its parameters. This one is executed once per module. Parameters: tree: ``ast`` parsed by ``flake8``. Differs from ``ast.parse`` since it is mutated by multiple ``flake8`` plugins. Why mutated? Since it is really expensive to copy all ``ast`` information in terms of memory. file_tokens: ``tokenize.tokenize`` parsed file tokens. filename: module file name, might be empty if piping is used. """ self.tree = transform(tree) self.filename = filename self.file_tokens = file_tokens @classmethod def add_options(cls, parser: OptionManager) -> None: """ ``flake8`` api method to register new plugin options. See :class:`wemake_python_styleguide.options.config.Configuration` docs for detailed options reference. Arguments: parser: ``flake8`` option parser instance. """ cls.config.register_options(parser) @classmethod def parse_options(cls, options: types.ConfigurationOptions) -> None: """Parses registered options for providing them to each visitor.""" cls.options = options def _run_checks( self, visitors: Sequence[VisitorClass], ) -> Iterator[types.CheckResult]: """Runs all passed visitors one by one.""" for visitor_class in visitors: visitor = visitor_class.from_checker(self) visitor.run() for error in visitor.violations: yield (*error.node_items(), type(self)) def run(self) -> Iterator[types.CheckResult]: """ Runs the checker. This method is used by ``flake8`` API. It is executed after all configuration is parsed. Yields: Violations that were found by the passed visitors. """ yield from self._run_checks(self.visitors) PK!ٮ0V%wemake_python_styleguide/constants.py# -*- coding: utf-8 -*- """ This module contains list of white- and black-listed ``python`` members. It contains lists of keywords and built-in functions we discourage to use. It also contains some exceptions that we allow to use in our codebase. """ import re from wemake_python_styleguide.types import Final #: List of functions we forbid to use. FUNCTIONS_BLACKLIST: Final = frozenset(( # Code generation: 'eval', 'exec', 'compile', # Termination: 'exit', 'quit', # Magic: 'globals', 'locals', 'vars', 'dir', # IO: 'input', # print is handled via `flake8-print` # Attribute access: 'hasattr', 'delattr', # Gratis: 'copyright', 'help', 'credits', # Dynamic imports: '__import__', # OOP: 'staticmethod', )) #: List of module metadata we forbid to use. MODULE_METADATA_VARIABLES_BLACKLIST: Final = frozenset(( '__author__', '__all__', '__version__', '__about__', )) #: List of variable names we forbid to use. VARIABLE_NAMES_BLACKLIST: Final = frozenset(( # Meaningless words: 'data', 'result', 'results', 'item', 'items', 'value', 'values', 'val', 'vals', 'var', 'vars', 'variable', 'content', 'contents', 'info', 'handle', 'handler', 'file', 'obj', 'objects', 'objs', 'some', 'do', 'params', 'parameters', # Confuseables: 'no', 'true', 'false', # Names from examples: 'foo', 'bar', 'baz', )) #: List of special names that are used only as first argument in methods. SPECIAL_ARGUMENT_NAMES_WHITELIST: Final = frozenset(( 'self', 'cls', 'mcs', )) #: List of magic methods that are forbidden to use. MAGIC_METHODS_BLACKLIST: Final = frozenset(( # Since we don't use `del`: '__del__', '__delitem__', '__delete__', '__dir__', # since we don't use `dir()` '__delattr__', # since we don't use `delattr()` )) #: List of nested classes' names we allow to use. NESTED_CLASSES_WHITELIST: Final = frozenset(( 'Meta', # django forms, models, drf, etc 'Params', # factoryboy specific )) #: List of nested functions' names we allow to use. NESTED_FUNCTIONS_WHITELIST: Final = frozenset(( 'decorator', 'factory', )) #: List of allowed ``__future__`` imports. FUTURE_IMPORTS_WHITELIST: Final = frozenset(( 'annotations', 'generator_stop', )) #: List of blacklisted module names. MODULE_NAMES_BLACKLIST: Final = frozenset(( 'util', 'utils', 'utilities', 'helpers', )) #: List of allowed module magic names. MAGIC_MODULE_NAMES_WHITELIST: Final = frozenset(( '__init__', '__main__', )) #: Regex pattern to name modules. MODULE_NAME_PATTERN: Final = re.compile(r'^_?_?[a-z][a-z\d_]+[a-z\d](__)?$') #: Common numbers that are allowed to be used without being called "magic". MAGIC_NUMBERS_WHITELIST: Final = frozenset(( 0.5, 100, 1000, 1024, # bytes 24, # hours 60, # seconds, minutes )) #: Maximum amount of ``# noqa`` comments per module. MAX_NOQA_COMMENTS: Final = 10 # Internal variables # They are not publicly documented since they are not used by the end user. # Used as a default filename, when it is not passed by flake8: STDIN: Final = 'stdin' # Used as a special name for unused variables: UNUSED_VARIABLE: Final = '_' # Used to specify as a placeholder for `__init__`: INIT: Final = '__init__' # Allowed magic number modulo: NON_MAGIC_MODULO: Final = 10 # Used to specify a pattern which checks variables and modules for underscored # numbers in their names: UNDERSCORED_NUMBER_PATTERN: Final = re.compile(r'.+\D\_\d+(\D|$)') PK!uh+wemake_python_styleguide/logics/__init__.py# -*- coding: utf-8 -*- PK!sx33.wemake_python_styleguide/logics/collections.py# -*- coding: utf-8 -*- import ast from typing import List, Sequence def normalize_dict_elements(node: ast.Dict) -> Sequence[ast.AST]: """ Normalizes ``dict`` elements and enforces consistent order. We had a problem that some ``dict`` objects might not have some keys. Example:: some_dict = {**one, **two} This ``dict`` contains two values and zero keys. This function will normalize this structure to use values instead of missing keys. See also: https://github.com/wemake-services/wemake-python-styleguide/issues/450 """ elements: List[ast.AST] = [] for dict_key, dict_value in zip(node.keys, node.values): if dict_key is None: elements.append(dict_value) else: elements.append(dict_key) return elements PK!,wemake_python_styleguide/logics/filenames.py# -*- coding: utf-8 -*- from pathlib import PurePath def get_stem(file_path: str) -> str: """ Returns the last element of path without extension. >>> get_stem('/some/module.py') 'module' >>> get_stem('C:/User/package/__init__.py') '__init__' >>> get_stem('c:/package/abc.py') 'abc' >>> get_stem('episode2.py') 'episode2' """ return PurePath(file_path).stem PK!/ X%<<,wemake_python_styleguide/logics/functions.py# -*- coding: utf-8 -*- from ast import Call, arg from typing import Container, List, Optional import astor from wemake_python_styleguide.types import AnyFunctionDefAndLambda def given_function_called(node: Call, to_check: Container[str]) -> str: """ Returns function name if it is called and contained in the container. >>> import ast >>> module = ast.parse('print(123, 456)') >>> given_function_called(module.body[0].value, ['print']) 'print' >>> given_function_called(module.body[0].value, ['adjust']) '' """ function_name = astor.to_source(node.func).strip() if function_name in to_check: return function_name return '' def is_method(function_type: Optional[str]) -> bool: """ Returns whether a given function type belongs to a class. >>> is_method('function') False >>> is_method(None) False >>> is_method('method') True >>> is_method('classmethod') True >>> is_method('staticmethod') True >>> is_method('') False """ return function_type in {'method', 'classmethod', 'staticmethod'} def get_all_arguments(node: AnyFunctionDefAndLambda) -> List[arg]: """ Returns list of all arguments that exist in a function. Respects the correct parameters order. Positional args, *args, keyword-only, **kwargs. """ names = [ *node.args.args, *node.args.kwonlyargs, ] if node.args.vararg: names.insert(len(node.args.args), node.args.vararg) if node.args.kwarg: names.append(node.args.kwarg) return names def is_first_argument(node: AnyFunctionDefAndLambda, name: str) -> bool: """Tells whether an argument name is the logically first in function.""" if not node.args.args: return False return name == node.args.args[0].arg PK!7*wemake_python_styleguide/logics/imports.py# -*- coding: utf-8 -*- from typing import List from wemake_python_styleguide.types import AnyImport def get_import_parts(node: AnyImport) -> List[str]: """Returns list of import modules.""" module_path = getattr(node, 'module', '') or '' return module_path.split('.') PK!uh2wemake_python_styleguide/logics/naming/__init__.py# -*- coding: utf-8 -*- PK!>]Z''0wemake_python_styleguide/logics/naming/access.py# -*- coding: utf-8 -*- from wemake_python_styleguide.constants import UNUSED_VARIABLE def is_magic(name: str) -> bool: """ Checks whether the given ``name`` is magic. >>> is_magic('__init__') True >>> is_magic('some') False >>> is_magic('cli') False >>> is_magic('_') False >>> is_magic('__version__') True >>> is_magic('__main__') True """ return name.startswith('__') and name.endswith('__') def is_private(name: str) -> bool: """ Checks if name has private name pattern. >>> is_private('regular') False >>> is_private('__private') True >>> is_private('_protected') False >>> is_private('__magic__') False >>> is_private('_') False """ return name.startswith('__') and not is_magic(name) def is_protected(name: str) -> bool: """ Checks if name has protected name pattern. >>> is_protected('_protected') True >>> is_protected('__private') False >>> is_protected('__magic__') False >>> is_protected('common_variable') False >>> is_protected('_') False """ if not name.startswith('_'): return False if name == UNUSED_VARIABLE: return False return not is_private(name) and not is_magic(name) PK!L"x[[2wemake_python_styleguide/logics/naming/builtins.py# -*- coding: utf-8 -*- import keyword from flake8_builtins import BUILTINS from wemake_python_styleguide.constants import UNUSED_VARIABLE from wemake_python_styleguide.logics.naming.access import is_magic ALL_BUILTINS = frozenset(( *keyword.kwlist, *BUILTINS, # Special case. # Some python version have them, some do not have them: 'async', 'await', )) def is_wrong_alias(variable_name: str) -> bool: """ Tells whether a variable is wrong builtins alias or not. >>> is_wrong_alias('regular_name_') True >>> is_wrong_alias('_') False >>> is_wrong_alias('_async') False >>> is_wrong_alias('_await') False >>> is_wrong_alias('regular_name') False >>> is_wrong_alias('class_') False >>> is_wrong_alias('list_') False >>> is_wrong_alias('list') False >>> is_wrong_alias('__spec__') False """ if is_magic(variable_name): return False if variable_name == UNUSED_VARIABLE or not variable_name.endswith('_'): return False return variable_name[:-1] not in ALL_BUILTINS PK!< 21wemake_python_styleguide/logics/naming/logical.py# -*- coding: utf-8 -*- from typing import Iterable from wemake_python_styleguide import constants from wemake_python_styleguide.logics.naming import access from wemake_python_styleguide.options import defaults def is_wrong_name(name: str, to_check: Iterable[str]) -> bool: """ Checks that name is not prohibited by explicitly listing it's name. >>> is_wrong_name('wrong', ['wrong']) True >>> is_wrong_name('correct', ['wrong']) False >>> is_wrong_name('_wrong', ['wrong']) True >>> is_wrong_name('wrong_', ['wrong']) True >>> is_wrong_name('wrong__', ['wrong']) False >>> is_wrong_name('__wrong', ['wrong']) False """ for name_to_check in to_check: choices_to_check = { name_to_check, '_{0}'.format(name_to_check), '{0}_'.format(name_to_check), } if name in choices_to_check: return True return False def is_upper_case_name(name: str) -> bool: """ Checks that attribute name has no upper-case letters. >>> is_upper_case_name('camelCase') True >>> is_upper_case_name('UPPER_CASE') True >>> is_upper_case_name('camel_Case') True >>> is_upper_case_name('snake_case') False >>> is_upper_case_name('snake') False >>> is_upper_case_name('snake111') False >>> is_upper_case_name('__variable_v2') False """ return any(character.isupper() for character in name) def is_too_short_name( name: str, min_length: int = defaults.MIN_NAME_LENGTH, ) -> bool: """ Checks for too short names. >>> is_too_short_name('test') False >>> is_too_short_name('o') True >>> is_too_short_name('_') False >>> is_too_short_name('z1') False >>> is_too_short_name('z', min_length=1) False """ return name != constants.UNUSED_VARIABLE and len(name) < min_length def is_too_long_name( name: str, max_length: int = defaults.MAX_NAME_LENGTH, ) -> bool: """ Checks for too long names. >>> is_too_long_name('test') False >>> is_too_long_name('this_is_twentynine_characters') False >>> is_too_long_name('this_should_fail', max_length=10) True >>> is_too_long_name('this_is_thirty_characters_long', max_length=30) False >>> is_too_long_name('this_is_thirty_characters_long', max_length=29) True """ return len(name) > max_length def does_contain_underscored_number(name: str) -> bool: """ Checks for names with underscored number. >>> does_contain_underscored_number('star_wars_episode2') False >>> does_contain_underscored_number('come2_me') False >>> does_contain_underscored_number('_') False >>> does_contain_underscored_number('z1') False >>> does_contain_underscored_number('iso123_456') False >>> does_contain_underscored_number('star_wars_episode_2') True >>> does_contain_underscored_number('come_2_me') True >>> does_contain_underscored_number('come_44_me') True >>> does_contain_underscored_number('iso_123_456') True """ return constants.UNDERSCORED_NUMBER_PATTERN.match(name) is not None def does_contain_consecutive_underscores(name: str) -> bool: """ Checks if name contains consecutive underscores in middle of name. >>> does_contain_consecutive_underscores('name') False >>> does_contain_consecutive_underscores('__magic__') False >>> does_contain_consecutive_underscores('__private') False >>> does_contain_consecutive_underscores('name') False >>> does_contain_consecutive_underscores('some__value') True >>> does_contain_consecutive_underscores('__some__value__') True >>> does_contain_consecutive_underscores('__private__value') True >>> does_contain_consecutive_underscores('some_value__') True """ if access.is_magic(name) or access.is_private(name): return '__' in name.strip('_') return '__' in name def does_contain_unicode(name: str) -> bool: """ Check if name contains unicode characters. >>> does_contain_unicode('hello_world1') False >>> does_contain_unicode('') False >>> does_contain_unicode('привет_мир1') True >>> does_contain_unicode('russian_техт') True """ try: name.encode('ascii') except UnicodeEncodeError: return True else: return False PK!^=S  4wemake_python_styleguide/logics/naming/name_nodes.py# -*- coding: utf-8 -*- import ast from typing import Optional def is_same_variable(left: ast.AST, right: ast.AST) -> bool: """Ensures that nodes are the same variable.""" if isinstance(left, ast.Name) and isinstance(right, ast.Name): return left.id == right.id return False def get_assigned_name(node: ast.AST) -> Optional[str]: """ Returns variable names for node that is just assigned. Returns ``None`` for nodes that are used in a different manner. """ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store): return node.id if isinstance(node, ast.Attribute) and isinstance(node.ctx, ast.Store): return node.attr if isinstance(node, ast.ExceptHandler): return getattr(node, 'name', None) return None PK!]̈(wemake_python_styleguide/logics/nodes.py# -*- coding: utf-8 -*- import ast from typing import Optional, Union from wemake_python_styleguide.types import AnyNodes def is_literal(node: ast.AST) -> bool: """ Checks for nodes that contains only constants. If the node contains only literals it will be evaluated. When node relies on some other names, it won't be evaluated. """ try: ast.literal_eval(node) except ValueError: return False else: return True def is_contained(node: ast.AST, to_check: Union[AnyNodes, type]) -> bool: """Checks whether node does contain given subnode types.""" for child in ast.walk(node): if isinstance(child, to_check): return True return False def is_doc_string(node: ast.stmt) -> bool: """ Tells whether or not the given node is a docstring. We call docstrings any string nodes that are placed right after function, class, or module definition. """ if not isinstance(node, ast.Expr): return False return isinstance(node.value, ast.Str) def get_parent(node: ast.AST) -> Optional[ast.AST]: """Returns the parent node or ``None`` if node has no parent.""" return getattr(node, 'wps_parent', None) PK!Ai,wemake_python_styleguide/logics/operators.py# -*- coding: utf-8 -*- import ast from typing import Optional from wemake_python_styleguide.logics.nodes import get_parent def unwrap_unary_node(node: ast.AST) -> ast.AST: """ Returns a real unwrapped node from the unary wrapper. It recursively unwraps any level of unary operators. Returns the node itself if it is not wrapped in unary operator. """ if not isinstance(node, ast.UnaryOp): return node return unwrap_unary_node(node.operand) def get_parent_ignoring_unary(node: ast.AST) -> Optional[ast.AST]: """ Returns real parent ignoring proxy unary parent level. What can go wrong? 1. Number can be negative: ``x = -1``, so ``1`` has ``UnaryOp`` as parent, but should return ``Assign`` 2. Some values can be negated: ``x = --some``, so ``some`` has ``UnaryOp`` as parent, but should return ``Assign`` """ parent = get_parent(node) if parent is None or not isinstance(parent, ast.UnaryOp): return parent return get_parent_ignoring_unary(parent) PK!ܖ)wemake_python_styleguide/logics/tokens.py# -*- coding: utf-8 -*- import tokenize from typing import Container, Iterable, Tuple def split_prefixes(token: tokenize.TokenInfo) -> Tuple[str, str]: """Splits string token by prefixes and the quoted content.""" split = token.string.split(token.string[-1]) return split[0], token.string.replace(split[0], '', 1) def has_triple_string_quotes(string_contents: str) -> bool: """Tells whether string token is written as inside triple quotes.""" if string_contents.startswith('"""') and string_contents.endswith('"""'): return True elif string_contents.startswith("'''") and string_contents.endswith("'''"): return True return False def only_contains( tokens: Iterable[tokenize.TokenInfo], container: Container[int], ) -> bool: """Determins that only tokens from the given list are contained.""" for token in tokens: if token.exact_type not in container: return False return True PK!uh,wemake_python_styleguide/options/__init__.py# -*- coding: utf-8 -*- PK!A??*wemake_python_styleguide/options/config.py# -*- coding: utf-8 -*- from typing import ClassVar, Mapping, Optional, Sequence, Union import attr from flake8.options.manager import OptionManager from wemake_python_styleguide.options import defaults from wemake_python_styleguide.types import final #: Immutable config values passed from `flake8`. ConfigValues = Mapping[str, Union[str, int, bool]] @final @attr.attrs(frozen=True, auto_attribs=True, slots=True) class _Option(object): """Represents ``flake8`` option object.""" long_option_name: str default: int # noqa: E704 help: str type: Optional[str] = 'int' # noqa: A003 parse_from_config: bool = True action: str = 'store' def __attrs_post_init__(self): """Is called after regular init is done.""" object.__setattr__(self, 'help', self.help + ' Defaults to: %default') @final class Configuration(object): """ Provides configuration options for our plugin. We do not like our linter to be configurable. Since people may take the wrong path or make wrong decisions. We try to make all defaults as reasonable as possible. However, you can currently adjust some complexity options. Why? Because we are not quite sure about the ideal values yet. We are still researching them, and providing a way for developers to help us out is a good thing at the moment. Options for general checks: - ``min-name-length`` - minimum number of chars to define a valid variable and module name, defaults to :str:`wemake_python_styleguide.options.defaults.MIN_NAME_LENGTH` - ``max-name-length`` - maximum number of chars to define a valid variable and module name, defaults to :str:`wemake_python_styleguide.options.defaults.MAX_NAME_LENGTH` - ``i-control-code`` - whether you control ones who use your code, more rules are enforced when you do control it, defaults to :str:`wemake_python_styleguide.options.defaults.I_CONTROL_CODE` Options for complexity related checks: - ``max-returns`` - maximum allowed number of ``return`` statements in one function, defaults to :str:`wemake_python_styleguide.options.defaults.MAX_RETURNS` - ``max-local-variables`` - maximum allowed number of local variables in one function, defaults to :str:`wemake_python_styleguide.options.defaults.MAX_LOCAL_VARIABLES` - ``max-expressions`` - maximum allowed number of expressions in one function, defaults to :str:`wemake_python_styleguide.options.defaults.MAX_EXPRESSIONS` - ``max-arguments`` - maximum allowed number of arguments in one function, defaults to :str:`wemake_python_styleguide.options.defaults.MAX_ARGUMENTS` - ``max-module-members`` - maximum number of classes and functions in a single module, defaults to :str:`wemake_python_styleguide.options.defaults.MAX_MODULE_MEMBERS` - ``max-methods`` - maximum number of methods in a single class, defaults to :str:`wemake_python_styleguide.options.defaults.MAX_METHODS` - ``max-line-complexity`` - maximum line complexity measured in number of ``ast`` nodes per line, defaults to :str:`wemake_python_styleguide.options.defaults.MAX_LINE_COMPLEXITY` - ``max-jones-score`` - maximum Jones score for a module, which is equal to the median of all lines complexity sum, defaults to :str:`wemake_python_styleguide.options.defaults.MAX_JONES_SCORE` - ``max-imports`` - maximum number of imports in a single module, defaults to :str:`wemake_python_styleguide.options.defaults.MAX_IMPORTS` - ``max-base-classes`` - maximum number of parent classes inside a class definition, defaults to :str:`wemake_python_styleguide.options.defaults.MAX_BASE_CLASSES` - ``max-decorators`` - maximum number of decorators for single function or class definition, defaults to :str:`wemake_python_styleguide.options.defaults.MAX_DECORATORS` All options are configurable via ``flake8`` CLI. Example:: flake8 --max-returns=2 --max-arguments=4 Or you can provide options in ``tox.ini`` or ``setup.cfg``. Example:: [flake8] max-returns = 2 max-arguments = 4 We use ``setup.cfg`` as a default way to provide configuration. """ options: ClassVar[Sequence[_Option]] = [ # Complexity: _Option( '--max-returns', defaults.MAX_RETURNS, 'Maximum allowed number of return statements in one function.', ), _Option( '--max-local-variables', defaults.MAX_LOCAL_VARIABLES, 'Maximum allowed number of local variables in one function.', ), _Option( '--max-expressions', defaults.MAX_EXPRESSIONS, 'Maximum allowed number of expressions in one function.', ), _Option( '--max-arguments', defaults.MAX_ARGUMENTS, 'Maximum allowed number of arguments in one function.', ), _Option( '--max-module-members', defaults.MAX_MODULE_MEMBERS, 'Maximum number of classes and functions in a single module.', ), _Option( '--max-methods', defaults.MAX_METHODS, 'Maximum number of methods in a single class.', ), _Option( '--max-line-complexity', defaults.MAX_LINE_COMPLEXITY, 'Maximum line complexity, measured in `ast` nodes.', ), _Option( '--max-jones-score', defaults.MAX_JONES_SCORE, 'Maximum median module complexity, based on sum of lines.', ), _Option( '--max-imports', defaults.MAX_IMPORTS, 'Maximum number of imports in a single module.', ), _Option( '--max-base-classes', defaults.MAX_BASE_CLASSES, 'Maximum number of base classes.', ), _Option( '--max-decorators', defaults.MAX_DECORATORS, 'Maximum number of decorators.', ), # General: _Option( '--min-name-length', defaults.MIN_NAME_LENGTH, 'Minimum required length of variable and module names.', ), _Option( '--max-name-length', defaults.MAX_NAME_LENGTH, 'Maximum possible length of the variable and module names.', ), _Option( '--i-control-code', defaults.I_CONTROL_CODE, 'Whether you control ones who use your code.', action='store_true', type=None, ), ] def register_options(self, parser: OptionManager) -> None: """Registers options for our plugin.""" for option in self.options: parser.add_option(**attr.asdict(option)) PK!,wemake_python_styleguide/options/defaults.py# -*- coding: utf-8 -*- """ Constants with default values for plugin's configuration. We try to stick to "the magical 7 ± 2 number". https://en.wikipedia.org/wiki/The_Magical_Number_Seven,_Plus_or_Minus_Two What does it mean? It means that we choose these values based on our mind capacity. And it is really hard to keep in mind more that 9 objects at the same time. These values can be changed in the ``setup.cfg`` file on a per-project bases, if you find them too strict or too permissive. """ from wemake_python_styleguide.types import Final # General: #: Minimum variable's name length. MIN_NAME_LENGTH: Final = 2 #: Maximum variable and module name length: MAX_NAME_LENGTH: Final = 45 #: Whether you control ones who use your code. I_CONTROL_CODE: Final = True # Complexity: #: Maximum number of `return` statements allowed in a single function. MAX_RETURNS: Final = 5 #: Maximum number of local variables in a function. MAX_LOCAL_VARIABLES: Final = 5 #: Maximum number of expressions in a single function. MAX_EXPRESSIONS: Final = 9 #: Maximum number of arguments for functions or methods. MAX_ARGUMENTS: Final = 5 #: Maximum number of classes and functions in a single module. MAX_MODULE_MEMBERS: Final = 7 #: Maximum number of methods in a single class. MAX_METHODS: Final = 7 #: Maximum line complexity. MAX_LINE_COMPLEXITY: Final = 14 # 7 * 2, also almost guessed #: Maximum median module Jones complexity. MAX_JONES_SCORE: Final = 12 # this value was "guessed" #: Maximum number of imports in a single module. MAX_IMPORTS: Final = 12 #: Maximum number of base classes. MAX_BASE_CLASSES: Final = 3 #: Maximum number of decorators. MAX_DECORATORS: Final = 5 PK!}{??,wemake_python_styleguide/presets/__init__.py# -*- coding: utf-8 -*- """See :term:`preset` in the docs.""" PK!ڷ tt.wemake_python_styleguide/presets/complexity.py# -*- coding: utf-8 -*- from wemake_python_styleguide.visitors.ast.complexity import ( classes, counts, function, jones, nested, offset, ) #: Used to store all complexity related visitors to be later passed to checker: COMPLEXITY_PRESET = ( function.FunctionComplexityVisitor, jones.JonesComplexityVisitor, nested.NestedComplexityVisitor, offset.OffsetVisitor, counts.ImportMembersVisitor, counts.ModuleMembersVisitor, counts.MethodMembersVisitor, counts.ConditionsVisitor, counts.ElifVisitor, counts.TryExceptVisitor, classes.ClassComplexityVisitor, ) PK!(X+wemake_python_styleguide/presets/general.py# -*- coding: utf-8 -*- from wemake_python_styleguide.visitors.ast import ( annotations, attributes, builtins, classes, comparisons, conditions, functions, keywords, loops, naming, statements, ) from wemake_python_styleguide.visitors.ast.imports import WrongImportVisitor from wemake_python_styleguide.visitors.ast.modules import ( EmptyModuleContentsVisitor, ) from wemake_python_styleguide.visitors.filenames.module import ( WrongModuleNameVisitor, ) #: Used to store all general visitors to be later passed to checker: GENERAL_PRESET = ( # General: statements.StatementsWithBodiesVisitor, statements.WrongParametersIndentationVisitor, keywords.WrongRaiseVisitor, keywords.WrongKeywordVisitor, keywords.WrongTryExceptVisitor, keywords.WrongContextManagerVisitor, keywords.ConsistentReturningVisitor, loops.WrongComprehensionVisitor, loops.WrongLoopVisitor, attributes.WrongAttributeVisitor, annotations.WrongAnnotationVisitor, functions.WrongFunctionCallVisitor, functions.FunctionDefinitionVisitor, WrongImportVisitor, naming.WrongNameVisitor, naming.WrongModuleMetadataVisitor, naming.WrongVariableAssignmentVisitor, builtins.MagicNumberVisitor, builtins.WrongStringVisitor, builtins.WrongAssignmentVisitor, builtins.WrongCollectionVisitor, comparisons.WrongConditionalVisitor, comparisons.ComparisonSanityVisitor, comparisons.WrongComparisionOrderVisitor, conditions.IfStatementVisitor, # Classes: classes.WrongClassVisitor, classes.WrongMethodVisitor, classes.WrongSlotsVisitor, # Modules: WrongModuleNameVisitor, EmptyModuleContentsVisitor, ) PK!R22*wemake_python_styleguide/presets/tokens.py# -*- coding: utf-8 -*- from wemake_python_styleguide.visitors.tokenize import ( comments, keywords, primitives, statements, ) #: Used to store all token related visitors to be later passed to checker: TOKENS_PRESET = ( comments.WrongCommentVisitor, comments.FileMagicCommentsVisitor, keywords.WrongKeywordTokenVisitor, primitives.WrongNumberTokenVisitor, primitives.WrongStringTokenVisitor, primitives.WrongStringConcatenationVisitor, statements.ExtraIndentationVisitor, statements.BracketLocationVisitor, ) PK!uh4wemake_python_styleguide/transformations/__init__.py# -*- coding: utf-8 -*- PK!uh8wemake_python_styleguide/transformations/ast/__init__.py# -*- coding: utf-8 -*- PK!ISi8wemake_python_styleguide/transformations/ast/bugfixes.py# -*- coding: utf-8 -*- import ast from wemake_python_styleguide.logics.nodes import get_parent def fix_async_offset(tree: ast.AST) -> ast.AST: """ Fixes ``col_offest`` values for async nodes. This is a temporary check for async-based expressions, because offset for them isn't calculated properly. We can calculate right version of offset with subscripting ``6`` (length of "async " part). Affected ``python`` versions: - all versions below ``python3.6.7`` Read more: https://bugs.python.org/issue29205 https://github.com/wemake-services/wemake-python-styleguide/issues/282 """ nodes_to_fix = ( ast.AsyncFor, ast.AsyncWith, ast.AsyncFunctionDef, ) for node in ast.walk(tree): if isinstance(node, nodes_to_fix): error = 6 if node.col_offset % 4 != 0 else 0 node.col_offset = node.col_offset - error return tree def fix_line_number(tree: ast.AST) -> ast.AST: """ Adjusts line number for some nodes. They are set incorrectly for some collections. It might be either a bug or a feature. We do several checks here, to be sure that we won't get an incorrect line number. But, we basically check if there's a parent, so we can compare and adjust. Example:: print(( # should start from here 1, 2, 3, # actually starts from here )) """ affected = (ast.Tuple,) for node in ast.walk(tree): if isinstance(node, affected): parent_lineno = getattr(get_parent(node), 'lineno', None) if parent_lineno and parent_lineno < node.lineno: node.lineno = node.lineno - 1 return tree PK!LPP<wemake_python_styleguide/transformations/ast/enhancements.py# -*- coding: utf-8 -*- import ast def set_if_chain(tree: ast.AST) -> ast.AST: """ Used to create ``if`` chains. We have a problem, because we can not tell which situation is happening: .. code:: python if some_value: if other_value: ... .. code:: python if some_value: ... elif other_value: ... Since they are very similar it very hard to make a different when actually working with nodes. So, we need a simple way to separate them. """ for statement in ast.walk(tree): for child in ast.iter_child_nodes(statement): if isinstance(statement, ast.If) and isinstance(child, ast.If): if child in statement.orelse: setattr(statement, 'wps_chained', True) # noqa: Z425 setattr(child, 'wps_chain', statement) return tree def set_node_context(tree: ast.AST) -> ast.AST: """ Used to set proper context to all nodes. What we call "a context"? Context is where exactly this node belongs on a global level. Example:: if some_value > 2: test = 'passed' Despite the fact ``test`` variable has ``Assign`` as it parent it will have ``Module`` as a context. What contexts do we respect? - :py:class:`ast.Module` - :py:class:`ast.ClassDef` - :py:class:`ast.FunctionDef` and :py:class:`ast.AsyncFunctionDef` """ contexts = ( ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef, ) current_context = None for statement in ast.walk(tree): if isinstance(statement, contexts): current_context = statement for child in ast.iter_child_nodes(statement): setattr(child, 'wps_context', current_context) return tree PK!U4wemake_python_styleguide/transformations/ast_tree.py# -*- coding: utf-8 -*- import ast from pep8ext_naming import NamingChecker from wemake_python_styleguide.transformations.ast.bugfixes import ( fix_async_offset, fix_line_number, ) from wemake_python_styleguide.transformations.ast.enhancements import ( set_if_chain, set_node_context, ) class _ClassVisitor(ast.NodeVisitor): """Used to set method types inside classes.""" def __init__(self, transformer: NamingChecker) -> None: super().__init__() self.transformer = transformer def visit_ClassDef(self, node: ast.ClassDef) -> None: # noqa: N802 self.transformer.tag_class_functions(node) self.generic_visit(node) def _set_parent(tree: ast.AST) -> ast.AST: """ Sets parents for all nodes that do not have this prop. This step is required due to how `flake8` works. It does not set the same properties as `ast` module. This function was the cause of `issue-112`. Twice. Since the ``0.6.1`` we use ``'wps_parent'`` with a prefix. This should fix the issue with conflicting plugins. .. versionchanged:: 0.0.11 .. versionchanged:: 0.6.1 """ for statement in ast.walk(tree): for child in ast.iter_child_nodes(statement): setattr(child, 'wps_parent', statement) return tree def _set_function_type(tree: ast.AST) -> ast.AST: """ Sets the function type for methods. Can set: `method`, `classmethod`, `staticmethod`. .. versionchanged:: 0.3.0 """ transformer = _ClassVisitor(NamingChecker(tree, 'stdin')) transformer.visit(tree) return tree def transform(tree: ast.AST) -> ast.AST: """ Mutates the given ``ast`` tree. Applies all possible tranformations. Ordering: - initial ones - bugfixes - enhancements """ pipeline = ( # Initial, should be the first ones, ordering inside is important: _set_parent, _set_function_type, # Bugfixes, order is not important: fix_async_offset, fix_line_number, # Enhancements, order is not important: set_node_context, set_if_chain, ) for tranformation in pipeline: tree = tranformation(tree) return tree PK!d..̺ !wemake_python_styleguide/types.py# -*- coding: utf-8 -*- """ This module contains knowledge about the most important types that we use. There are also different :term:`visitor` specific types that are defined and use exclusively in that file. Policy ~~~~~~ If any of the following statements is true, move the type to this file: - if type is used in multiple files - if type is complex enough it has to be documented - if type is very important for the public API final ~~~~~ As you can see in the source code almost everything is marked as ``@final`` or ``Final``. It means that this value can not be subclassed or reassigned. This it only a ``mypy`` feature, it does not affect ``python`` runtime. We do this, because we value composition over inheritance. And this ``@final`` decorators help you to define readable and clear APIs for cases when inheritance is used. See also: My guide about ``@final`` type in ``python``: https://sobolevn.me/2018/07/real-python-contants Reference ~~~~~~~~~ """ import ast from typing import Tuple, Type, Union from typing_extensions import Final, Protocol, final # noqa: F401 #: In cases we need to work with both import types. AnyImport = Union[ast.Import, ast.ImportFrom] #: In cases we need to work with both function definitions. AnyFunctionDef = Union[ast.FunctionDef, ast.AsyncFunctionDef] #: In cases we need to work with all function definitions (including lambdas). AnyFunctionDefAndLambda = Union[AnyFunctionDef, ast.Lambda] #: In cases we need to work with both forms of if functions AnyIf = Union[ast.If, ast.IfExp] #: Flake8 API format to return error messages: CheckResult = Tuple[int, int, str, type] #: Tuple of AST node types for declarative syntax. AnyNodes = Tuple[Type[ast.AST], ...] class ConfigurationOptions(Protocol): """ Provides structure for the options we use in our checker and visitors. Then this protocol is passed to each individual visitor. It uses structural sub-typing, and does not represent any kind of a real class or structure. See also: https://mypy.readthedocs.io/en/latest/protocols.html """ # General: min_name_length: int i_control_code: bool max_name_length: int # Complexity: max_arguments: int max_local_variables: int max_returns: int max_expressions: int max_module_members: int max_methods: int max_line_complexity: int max_jones_score: int max_imports: int max_base_classes: int max_decorators: int PK!lU#wemake_python_styleguide/version.py# -*- coding: utf-8 -*- import pkg_resources def _get_version(dist_name: str) -> str: # pragma: no cover """Fetches distribution name. Contains a fix for Sphinx.""" try: return pkg_resources.get_distribution(dist_name).version except pkg_resources.DistributionNotFound: return '' # readthedocs can not install `poetry` projects pkg_name = 'wemake-python-styleguide' #: We store the version number inside the `pyproject.toml`: pkg_version = _get_version(pkg_name) PK!\/wemake_python_styleguide/violations/__init__.py# -*- coding: utf-8 -*- # TODO(@sobolevn): ensure that documentation is also sorted # TODO(@sobolevn): write tests for testing violation sorting order? PK!YFF+wemake_python_styleguide/violations/base.py# -*- coding: utf-8 -*- """ Contains detailed technical information about :term:`violation` internals. .. _violations: Violations API -------------- .. currentmodule:: wemake_python_styleguide.violations.base .. autoclasstree:: wemake_python_styleguide.violations.base .. autosummary:: :nosignatures: ASTViolation MaybeASTViolation TokenizeViolation SimpleViolation Violation can not have more than one base class. See :ref:`tutorial` for more information about choosing a correct base class. Conventions ~~~~~~~~~~~ - Each violation class name should end with "Violation" - Each violation must have a long docstring with full description - Each violation must have "Reasoning" and "Solution" sections - Each violation must have "versionadded" policy - Each violation should have an example with correct and wrong usages - If violation error template should have a parameter it should be the last part of the text: ``: {0}`` Reference ~~~~~~~~~ """ import ast import tokenize from typing import ClassVar, Optional, Tuple, Union from wemake_python_styleguide.types import final #: General type for all possible nodes where error happens. ErrorNode = Union[ ast.AST, tokenize.TokenInfo, None, ] class BaseViolation(object): """ Abstract base class for all style violations. It basically just defines how to create any error and how to format this error later on. Each subclass must define ``error_template`` and ``code`` fields. Attributes: error_template: message that will be shown to user after formatting. code: violation unique number. Used to identify the violation. """ error_template: ClassVar[str] code: ClassVar[int] def __init__(self, node: ErrorNode, text: str = None) -> None: """ Creates new instance of abstract violation. Parameters: node: violation was raised by this node. If applied. text: extra text to format the final message. If applied. """ self._node = node self._text = text @final def _full_code(self) -> str: """ Returns fully formatted code. Adds violation letter to the numbers. Also ensures that codes like ``3`` will be represented as ``Z003``. """ return 'Z' + str(self.code).zfill(3) def _location(self) -> Tuple[int, int]: """ Return violation location inside the file. Default location is in the so-called "file beginning". """ return 0, 0 @final def message(self) -> str: """ Returns error's formatted message with code and reason. Conditionally formats the ``error_template`` if it is required. """ return '{0} {1}'.format( self._full_code(), self.error_template.format(self._text), ) @final def node_items(self) -> Tuple[int, int, str]: """Returns tuple to match ``flake8`` API format.""" return (*self._location(), self.message()) class _BaseASTViolation(BaseViolation): """Used as a based type for all ``ast`` violations.""" _node: Optional[ast.AST] @final def _location(self) -> Tuple[int, int]: line_number = getattr(self._node, 'lineno', 0) column_offset = getattr(self._node, 'col_offset', 0) return line_number, column_offset class ASTViolation(_BaseASTViolation): """Violation for ``ast`` based style visitors.""" _node: ast.AST class MaybeASTViolation(_BaseASTViolation): """ Violation for ``ast`` and modules visitors. Is used for violations that share the same rule for nodes and module names. Is wildly used for naming rules. """ def __init__(self, node=None, text: str = None) -> None: """Creates new instance of module violation without explicit node.""" super().__init__(node, text=text) class TokenizeViolation(BaseViolation): """Violation for ``tokenize`` based visitors.""" _node: tokenize.TokenInfo @final def _location(self) -> Tuple[int, int]: return self._node.start class SimpleViolation(BaseViolation): """Violation for cases where there's no associated nodes.""" _node: None def __init__(self, node=None, text: str = None) -> None: """Creates new instance of simple style violation.""" super().__init__(node, text=text) PK!R5wemake_python_styleguide/violations/best_practices.py# -*- coding: utf-8 -*- """ These checks ensure that you follow the best practices. The source for these best practices is hidden inside countless hours we have spent debugging software or reviewing it. How do we find inspiration for new rules? We find some ugly code during code reviews and audits. Then we forbid to use this bad code forever. So, this error will never return to our codebase. .. currentmodule:: wemake_python_styleguide.violations.best_practices Summary ------- .. autosummary:: :nosignatures: WrongMagicCommentViolation WrongDocCommentViolation OveruseOfNoqaCommentViolation WrongModuleMetadataViolation EmptyModuleViolation InitModuleHasLogicViolation WrongKeywordViolation WrongFunctionCallViolation FutureImportViolation RaiseNotImplementedViolation BaseExceptionViolation BooleanPositionalArgumentViolation NestedFunctionViolation NestedClassViolation MagicNumberViolation StaticMethodViolation BadMagicMethodViolation NestedImportViolation RedundantLoopElseViolation RedundantFinallyViolation ReassigningVariableToItselfViolation YieldInsideInitViolation ProtectedModuleViolation ProtectedAttributeViolation LambdaInsideLoopViolation UnreachableCodeViolation StatementHasNoEffectViolation MultipleAssignmentsViolation IncorrectUnpackingViolation DuplicateExceptionViolation YieldInComprehensionViolation NonUniqueItemsInSetViolation BaseExceptionSubclassViolation SimplifiableIfViolation IncorrectClassBodyContentViolation MethodWithoutArgumentsViolation IncorrectBaseClassViolation IncorrectSlotsViolation IncorrectSuperCallViolation RedundantReturningElseViolation TryExceptMultipleReturnPathViolation Comments -------- .. autoclass:: WrongMagicCommentViolation .. autoclass:: WrongDocCommentViolation .. autoclass:: OveruseOfNoqaCommentViolation Modules ------- .. autoclass:: WrongModuleMetadataViolation .. autoclass:: EmptyModuleViolation .. autoclass:: InitModuleHasLogicViolation Builtins -------- .. autoclass:: WrongKeywordViolation .. autoclass:: WrongFunctionCallViolation .. autoclass:: FutureImportViolation .. autoclass:: RaiseNotImplementedViolation .. autoclass:: BaseExceptionViolation .. autoclass:: BooleanPositionalArgumentViolation Design ------ .. autoclass:: NestedFunctionViolation .. autoclass:: NestedClassViolation .. autoclass:: MagicNumberViolation .. autoclass:: StaticMethodViolation .. autoclass:: BadMagicMethodViolation .. autoclass:: NestedImportViolation .. autoclass:: RedundantLoopElseViolation .. autoclass:: RedundantFinallyViolation .. autoclass:: ReassigningVariableToItselfViolation .. autoclass:: YieldInsideInitViolation .. autoclass:: ProtectedModuleViolation .. autoclass:: ProtectedAttributeViolation .. autoclass:: LambdaInsideLoopViolation .. autoclass:: UnreachableCodeViolation .. autoclass:: StatementHasNoEffectViolation .. autoclass:: MultipleAssignmentsViolation .. autoclass:: IncorrectUnpackingViolation .. autoclass:: DuplicateExceptionViolation .. autoclass:: YieldInComprehensionViolation .. autoclass:: NonUniqueItemsInSetViolation .. autoclass:: BaseExceptionSubclassViolation .. autoclass:: SimplifiableIfViolation .. autoclass:: IncorrectClassBodyContentViolation .. autoclass:: MethodWithoutArgumentsViolation .. autoclass:: IncorrectBaseClassViolation .. autoclass:: IncorrectSlotsViolation .. autoclass:: IncorrectSuperCallViolation .. autoclass:: RedundantReturningElseViolation .. autoclass:: TryExceptMultipleReturnPathViolation """ from wemake_python_styleguide.types import final from wemake_python_styleguide.violations.base import ( ASTViolation, SimpleViolation, TokenizeViolation, ) @final class WrongMagicCommentViolation(SimpleViolation): """ Restricts to use several control (or magic) comments. We do not allow to use: 1. ``# noqa`` comment without specified violations 2. ``# type: some_type`` comments to specify a type for ``typed_ast`` Reasoning: We cover several different use-cases in a single rule. ``# noqa`` comment is restricted because it can hide other violations. ``# type: some_type`` comment is restricted because we can already use type annotations instead. Solution: Use ``# noqa`` comments with specified error types. Use type annotations to specify types. We still allow to use ``# type: ignore`` comment. Since sometimes it is totally required. Example:: # Correct: type = MyClass.get_type() # noqa: A001 coordinate: int = 10 some.int_field = 'text' # type: ignore number: int for number in some_untyped_iterable(): ... # Wrong: type = MyClass.get_type() # noqa coordinate = 10 # type: int .. versionadded:: 0.1.0 """ code = 400 error_template = 'Found wrong magic comment: {0}' @final class WrongDocCommentViolation(TokenizeViolation): """ Forbids to use empty doc comments (``#:``). Reasoning: Doc comments are used to provide a documentation. But supplying empty doc comments breaks this use-case. It is unclear why they can be used with no contents. Solution: Add some documentation to this comment. Or remove it. Empty doc comments are not caught by the default ``pycodestyle`` checks. Example:: # Correct: #: List of allowed names: NAMES_WHITELIST = ['feature', 'bug', 'research'] # Wrong: #: NAMES_WHITELIST = ['feature', 'bug', 'research'] .. versionadded:: 0.1.0 """ code = 401 error_template = 'Found wrong doc comment' @final class OveruseOfNoqaCommentViolation(SimpleViolation): """ Forbids to use too many ``# noqa`` comments. We check this count on a per-module basis. We use :str:`wemake_python_styleguide.constants.MAX_NOQA_COMMENTS` as a default value. Reasoning: Having too many ``# noqa`` comments with make your code less readable and clearly indicates that there's something wrong with it. Solution: Refactor your code to much the style. Or use a config file to switch off some checks. .. versionadded:: 0.7.0 """ error_template = 'Found `noqa` comments overuse: {0}' code = 402 # Modules: @final class WrongModuleMetadataViolation(ASTViolation): """ Forbids to have some module level variables. Reasoning: We discourage using module variables like ``__author__``, because code should not contain any metadata. Solution: Place all the metadata in ``setup.py``, ``setup.cfg``, or ``pyproject.toml``. Use proper docstrings and packaging classifiers. Use ``pkg_resources`` if you need to import this data into your app. See :py:data:`~wemake_python_styleguide.constants.MODULE_METADATA_VARIABLES_BLACKLIST` for full list of bad names. Example:: # Wrong: __author__ = 'Nikita Sobolev' __version__ = 0.1.2 .. versionadded:: 0.1.0 """ error_template = 'Found wrong metadata variable: {0}' code = 410 @final class EmptyModuleViolation(SimpleViolation): """ Forbids to have empty modules. Reasoning: Why is it even there? Do not pollute your project with empty files. Solution: If you have an empty module there are two ways to handle that: 1. delete it 2. drop some documentation in it, so you will explain why it is there .. versionadded:: 0.1.0 """ error_template = 'Found empty module' code = 411 @final class InitModuleHasLogicViolation(SimpleViolation): """ Forbids to have logic inside ``__init__`` module. Reasoning: If you have logic inside the ``__init__`` module it means several things: 1. you are keeping some outdated stuff there, you need to refactor 2. you are placing this logic into the wrong file, just create another one 3. you are doing some dark magic, and you should not do that Solution: Put your code in other modules. However, we allow to have some contents inside the ``__init__`` module: 1. comments, since they are dropped before AST comes in play 2. docs string, because sometimes it is required to state something It is also fine when you have different users that use your code. And you do not want to break everything for them. In this case this rule can be configured. Configuration: This rule is configurable with ``--i-control-code``. Default: :str:`wemake_python_styleguide.options.defaults.I_CONTROL_CODE` .. versionadded:: 0.1.0 """ error_template = 'Found `__init__.py` module with logic' code = 412 # Modules: @final class WrongKeywordViolation(ASTViolation): """ Forbids to use some keywords from ``python``. Reasoning: We believe that some keywords are anti-patterns. They promote bad-practices like ``global`` and ``pass``, or just not user-friendly like ``del``. Solution: Solutions differ from keyword to keyword. ``pass`` should be replaced with docstring or ``contextlib.suppress``. ``del`` should be replaced with specialized methods like ``.pop()``. ``global`` and ``nonlocal`` usages should be refactored. Example:: # Wrong: pass del nonlocal global .. versionadded:: 0.1.0 """ error_template = 'Found wrong keyword: {0}' code = 420 @final class WrongFunctionCallViolation(ASTViolation): """ Forbids to call some built-in functions. Reasoning: Some functions are only suitable for very specific use cases, we forbid to use them in a free manner. See :py:data:`~wemake_python_styleguide.constants.FUNCTIONS_BLACKLIST` for the full list of blacklisted functions. See also: https://www.youtube.com/watch?v=YjHsOrOOSuI .. versionadded:: 0.1.0 """ error_template = 'Found wrong function call: {0}' code = 421 @final class FutureImportViolation(ASTViolation): """ Forbids to use ``__future__`` imports. Reasoning: Almost all ``__future__`` imports are legacy ``python2`` compatibility tools that are no longer required. Solution: Remove them. Drop ``python2`` support. Except, there are some new ones for ``python4`` support. See :py:data:`~wemake_python_styleguide.constants.FUTURE_IMPORTS_WHITELIST` for the full list of allowed future imports. Example:: # Correct: from __future__ import annotations # Wrong: from __future__ import print_function .. versionadded:: 0.1.0 """ error_template = 'Found future import: {0}' code = 422 @final class RaiseNotImplementedViolation(ASTViolation): """ Forbids to use ``NotImplemented`` error. Reasoning: These two violations look so similar. But, these violations have different use cases. Use cases of ``NotImplemented`` is too limited to be generally available. Solution: Use ``NotImplementedError``. Example:: # Correct: raise NotImplementedError('To be done') # Wrong: raise NotImplemented .. versionadded:: 0.1.0 See Also: https://stackoverflow.com/a/44575926/4842742 """ error_template = 'Found raise NotImplemented' code = 423 @final class BaseExceptionViolation(ASTViolation): """ Forbids to use ``BaseException`` exception. Reasoning: We can silence system exit and keyboard interrupt with this exception handler. It is almost the same as raw ``except:`` block. Solution: Handle ``Exception``, ``KeyboardInterrupt``, ``GeneratorExit``, and ``SystemExit`` separately. Do not use the plain ``except:`` keyword. Example:: # Correct: except Exception as ex: ... # Wrong: except BaseException as ex: ... .. versionadded:: 0.3.0 See Also: https://docs.python.org/3/library/exceptions.html#exception-hierarchy https://help.semmle.com/wiki/pages/viewpage.action?pageId=1608527 """ error_template = 'Found except `BaseException`' code = 424 @final class BooleanPositionalArgumentViolation(ASTViolation): """ Forbids to pass booleans as non-keyword parameters. Reasoning: Passing boolean as regular positional parameters is very non-descriptive. It is almost impossible to tell, what does this parameter means. And you almost always have to look up the implementation to tell what is going on. Solution: Pass booleans as keywords only. This will help you to save extra context on what's going on. Example:: # Correct: UsersRepository.update(cache=True) # Wrong: UsersRepository.update(True) .. versionadded:: 0.6.0 """ error_template = 'Found boolean non-keyword argument: {0}' code = 425 # Design: @final class NestedFunctionViolation(ASTViolation): """ Forbids to have nested functions. Reasoning: Nesting functions is a bad practice. It is hard to test them, it is hard then to separate them. People tend to overuse closures, so it's hard to manage the dataflow. Solution: Just write flat functions, there's no need to nest them. Pass parameters as normal arguments, do not use closures. Until you need them for decorators or factories. We also disallow to nest ``lambda`` and ``async`` functions. See :py:data:`~wemake_python_styleguide.constants.NESTED_FUNCTIONS_WHITELIST` for the whole list of whitelisted names. Example:: # Correct: def do_some(): ... def other(): ... # Wrong: def do_some(): def inner(): ... .. versionadded:: 0.1.0 """ error_template = 'Found nested function: {0}' code = 430 @final class NestedClassViolation(ASTViolation): """ Forbids to use nested classes. Reasoning: Nested classes are really hard to manage. You can not even create an instance of this class in many cases. Testing them is also really hard. Solution: Just write flat classes, there's no need nest them. If you are nesting classes inside a function for parametrization, then you will probably need to use different design (or metaclasses). See :py:data:`~wemake_python_styleguide.constants.NESTED_CLASSES_WHITELIST` for the full list of whitelisted names. Example:: # Correct: class Some(object): ... class Other(object): ... # Wrong: class Some(object): class Inner(object): ... .. versionadded:: 0.1.0 """ error_template = 'Found nested class: {0}' code = 431 @final class MagicNumberViolation(ASTViolation): """ Forbids to use magic numbers in your code. What we call a "magic number"? Well, it is actually any number that appears in your code out of nowhere. Like ``42``. Or ``0.32``. Reasoning: It is very hard to remember what these numbers actually mean. Why were they used? Should they ever be changed? Or are they eternal like ``3.14``? Solution: Give these numbers a name! Move them to a separate variable, giving more context to the reader. And by moving things into new variables you will trigger other complexity checks. Example:: # Correct: price_in_euro = 3.33 # could be changed later total = get_items_from_cart() * price_in_euro # Wrong: total = get_items_from_cart() * 3.33 What are numbers that we exclude from this check? Any numbers that are assigned to a variable, array, dictionary, or keyword arguments inside a function. ``int`` numbers that are in range ``[-10, 10]`` and some other common numbers, that are defined in :py:data:`~wemake_python_styleguide.constants.MAGIC_NUMBERS_WHITELIST` .. versionadded:: 0.1.0 See also: https://en.wikipedia.org/wiki/Magic_number_(programming) """ code = 432 error_template = 'Found magic number: {0}' @final class StaticMethodViolation(ASTViolation): """ Forbids to use ``@staticmethod`` decorator. Reasoning: Static methods are not required to be inside the class. Because they even do not have access to the current instance. Solution: Use instance methods, ``@classmethod``, or functions instead. .. versionadded:: 0.1.0 """ error_template = 'Found using `@staticmethod`' code = 433 @final class BadMagicMethodViolation(ASTViolation): """ Forbids to use some magic methods. Reasoning: We forbid to use magic methods related to the forbidden language parts. Likewise, we forbid to use ``del`` keyword, so we forbid to use all magic methods related to it. Solution: Refactor your code to use custom methods instead. It will give more context to your app. See :py:data:`~wemake_python_styleguide.constants.MAGIC_METHODS_BLACKLIST` for the full blacklist of the magic methods. .. versionadded:: 0.1.0 See also: https://www.youtube.com/watch?v=F6u5rhUQ6dU """ error_template = 'Found using restricted magic method: {0}' code = 434 @final class NestedImportViolation(ASTViolation): """ Forbids to have nested imports in functions. Reasoning: Usually, nested imports are used to fix the import cycle. So, nested imports show that there's an issue with your design. Solution: You don't need nested imports, you need to refactor your code. Introduce a new module or find another way to do what you want to do. Rethink how your layered architecture should look like. Example:: # Correct: from my_module import some_function def some(): ... # Wrong: def some(): from my_module import some_function .. versionadded:: 0.1.0 See also: https://github.com/seddonym/layer_linter """ error_template = 'Found nested import' code = 435 @final class RedundantLoopElseViolation(ASTViolation): """ Forbids to use ``else`` without ``break`` in a loop. We use the same logic for ``for`` and ``while`` loops. Reasoning: When there's no ``break`` keyword in loop's body it means that ``else`` will always be called. This rule will reduce complexity, improve readability, and protect from possible errors. Solution: Refactor your ``else`` case logic to be inside the loop's body. Or right after it. Example:: # Correct: for letter in 'abc': if letter == 'b': break else: print('"b" is not found') for letter in 'abc': print(letter) print('always called') # Wrong: for letter in 'abc': print(letter) else: print('always called') .. versionadded:: 0.3.0 """ error_template = 'Found `else` in a loop without `break`' code = 436 @final class RedundantFinallyViolation(ASTViolation): """ Forbids to use ``finally`` in ``try`` block without ``except`` block. Reasoning: This rule will reduce complexity and improve readability. Solution: Refactor your ``try`` logic. Replace the ``try-finally`` statement with a ``with`` statement. Example:: # Correct: with open("filename") as f: f.write(...) # Wrong: try: f = open("filename") f.write(...) finally: f.close() .. versionadded:: 0.3.0 """ error_template = 'Found `finally` in `try` block without `except`' code = 437 @final class ReassigningVariableToItselfViolation(ASTViolation): """ Forbids to assign variable to itself. Reasoning: There is no need to do that. Generally, it is an indication of some errors or just dead code. Example:: # Correct: some = some + 1 x_coord, y_coord = y_coord, x_coord # Wrong: some = some x_coord, y_coord = x_coord, y_coord .. versionadded:: 0.3.0 """ error_template = 'Found reassigning variable to itself' code = 438 @final class YieldInsideInitViolation(ASTViolation): """ Forbids to use ``yield`` inside of ``__init__`` method. Reasoning: ``__init__`` should be used to initialize new objects. It shouldn't ``yield`` anything because it should return ``None`` by the convention. Example:: # Correct: class Example(object): def __init__(self): self._public_items_count = 0 # Wrong: class Example(object): def __init__(self): yield 10 .. versionadded:: 0.3.0 """ error_template = 'Found `yield` inside `__init__` method' code = 439 @final class ProtectedModuleViolation(ASTViolation): """ Forbids to import protected modules. Reasoning: When importing protected modules we break a contract that authors of this module enforce. This way we are not respecting encapsulation and it may break our code at any moment. Solution: Do not import anything from protected modules. Respect the encapsulation. Example:: # Correct: from some.public.module import FooClass # Wrong: import _compat from some._protected.module import BarClass from some.module import _protected .. versionadded:: 0.3.0 """ error_template = 'Found protected module import' code = 440 @final class ProtectedAttributeViolation(ASTViolation): """ Forbids to use protected attributes and methods. Reasoning: When using protected attributes and method we break a contract that authors of this class enforce. This way we are not respecting encapsulation and it may break our code at any moment. Solution: Do not use protected attributes and methods. Respect the encapsulation. Example:: # Correct: self._protected = 1 cls._hidden_method() some.public() # Wrong: print(some._protected) instance._hidden() self.container._internal = 10 Note, that it is possible to use protected attributes with ``self`` and ``cls`` as base names. We allow this so you can create and use protected attributes and methods inside the class context. This is how protected attributes should be used. .. versionadded:: 0.3.0 """ error_template = 'Found protected attribute usage: {0}' code = 441 @final class LambdaInsideLoopViolation(ASTViolation): """ Forbids to use ``lambda`` inside loops. Reasoning: It is error-prone to use ``lambda`` inside ``for`` and ``while`` loops due to the famous late-binding. Solution: Use regular functions, factory functions, or ``partial`` functions. Save yourself from possible confusion. Example:: # Correct: for index in range(10): some.append(partial_function(index)) # Wrong: for index in range(10): some.append(lambda index=index: index * 10)) other.append(lambda: index * 10)) .. versionadded:: 0.5.0 See also: https://docs.python-guide.org/writing/gotchas/#late-binding-closures """ error_template = "Found `lambda` in loop's body" code = 442 @final class UnreachableCodeViolation(ASTViolation): """ Forbids to have unreachable code. What is unreachable code? It is some lines of code that cannot be executed by python's interpreter. This is probably caused by ``return`` or ``raise`` statements. However, we can not cover 100% of truly unreachable code by this rule. This happens due to the dynamic nature of python. For example, detecting that ``1 / some_value`` would sometimes raise an exception is too complicated and is out of the scope of this rule. Reasoning: Having dead code in your project is an indicator that you do not care about your code base at all. It dramatically reduces code quality and readability. It also demotivates team members. Solution: Delete any unreachable code you have. Or refactor it, if this happens by your mistake. Example:: # Correct: def some_function(): print('This line is reachable, all good') return 5 # Wrong: def some_function(): return 5 print('This line is unreachable') .. versionadded:: 0.5.0 """ error_template = 'Found unreachable code' code = 443 @final class StatementHasNoEffectViolation(ASTViolation): """ Forbids to have statements that do nothing. Reasoning: Statements that just access the value or expressions used as statements indicate that your code contains deadlines. They just pollute your codebase and do nothing. Solution: Refactor your code in case it was a typo or error. Or just delete this code. Example:: # Correct: def some_function(): price = 8 + 2 return price # Wrong: def some_function(): 8 + 2 print .. versionadded:: 0.5.0 """ error_template = 'Found statement that has no effect' code = 444 @final class MultipleAssignmentsViolation(ASTViolation): """ Forbids to have statements that do nothing. Reasoning: Multiple assignments on the same line might not do what you think they do. They can also grown pretty long. And you will not notice the rising complexity of your code. Solution: Use separate lines for each assignment. Example:: # Correct: a = 1 b = 1 # Wrong: a = b = 1 .. versionadded:: 0.6.0 """ error_template = 'Found multiple assign targets' code = 445 @final class IncorrectUnpackingViolation(ASTViolation): """ Forbids to have statements that do nothing. Reasoning: Having unpacking with side-effects is very dirty. You might get in serious and very hard-to-debug troubles because of this technique. So, do not use it. Solution: Use unpacking with only variables, not any other entities. Example:: # Correct: first, second = some() # Wrong: first, some_dict['alias'] = some() .. versionadded:: 0.6.0 """ error_template = 'Found incorrect unpacking target' code = 446 @final class DuplicateExceptionViolation(ASTViolation): """ Forbids to have the same exception class in multiple ``except`` blocks. Reasoning: Having the same exception name in different blocks means that something is not right: since only one branch will work. Other one will always be ignored. So, that is clearly an error. Solution: Use unique exception handling rules. Example:: # Correct: try: ... except ValueError: ... # Wrong: try: ... except ValueError: ... except ValueError: ... .. versionadded:: 0.6.0 """ error_template = 'Found duplicate exception: {0}' code = 447 @final class YieldInComprehensionViolation(ASTViolation): """ Forbids to have ``yield`` keyword inside comprehensions. Reasoning: Having the ``yield`` keyword inside comprehensions is error-prone. You can shoot yourself in a foot by an inaccurate usage of this feature. Solution: Use regular ``for`` loops with ``yield`` keywords. Or create a separate generator function. Example:: # Wrong: >>> list((yield letter) for letter in 'ab') ['a', None, 'b', None] >>> list([(yield letter) for letter in 'ab']) ['a', 'b'] See also: https://github.com/satwikkansal/wtfPython#-yielding-none .. versionadded:: 0.7.0 """ error_template = 'Found `yield` inside comprehension' code = 448 @final class NonUniqueItemsInSetViolation(ASTViolation): """ Forbids to have duplicate items in ``set`` literals. Reasoning: When you explicitly put duplicate items in ``set`` literals it just does not make any sense. Since ``set`` can not contain duplicate items and they will be removed anyway. Solution: Remove the duplicate items. Example:: # Correct: some_set = {'a', variable1} some_set = {make_call(), make_call()} # Wrong: some_set = {'a', 'a', variable1, variable1} Things that we consider duplicates: builtins and variables. These nodes are not checked because they may return different results: - function and method calls - comprehensions - attributes - subscribe operations - containers: lists, dicts, tuples, sets .. versionadded:: 0.7.0 """ error_template = 'Found non-unique item in `set` literal: {0}' code = 449 @final class BaseExceptionSubclassViolation(ASTViolation): """ Forbids to have duplicate items in ``set`` literals. Reasoning: ``BaseException`` is a special case: it is not designed to be extended by users. A lot of your ``except Exception`` cases won't work. That's incorrect and dangerous. Solution: Change the base class to ``Exception``. Example:: # Correct: class MyException(Exception): ... # Wrong: class MyException(BaseException): ... See also: https://docs.python.org/3/library/exceptions.html#exception-hierarchy .. versionadded:: 0.7.0 """ error_template = 'Found exception inherited from `BaseException`' code = 450 @final class SimplifiableIfViolation(ASTViolation): """ Forbids to have simplifiable ``if`` conditions. Reasoning: This complex construction can cause frustration among other developers. It is longer, more verbose, and more complex. Solution: Use ``bool()`` to convert test values to boolean values. Or just leave it as it is in case when your test already returns a boolean value. Use can also use ``not`` keyword to switch boolean values. Example:: # Correct: my_bool = bool(some_call()) other_value = 8 if some_call() else None # Wrong: my_bool = True if some_call() else False We only check ``if`` nodes where ``True`` and ``False`` values are used. We check both ``if`` nodes and ``if`` expressions. .. versionadded:: 0.7.0 """ error_template = 'Found simplifiable `if` condition' code = 451 @final class IncorrectClassBodyContentViolation(ASTViolation): """ Forbids to use incorrect nodes inside ``class`` definitions. Reasoning: Python allows us to have conditions, context managers, and even infinite loops inside ``class`` definitions. On the other hand, only methods, attributes, and docstrings make sense. So, we discourage using anything except these nodes in class bodies. Solution: If you have complex logic inside your class definition, most likely that you do something wrong. There are different options to refactor this mess. You can try metaclasses, decorators, builders, and other patterns. Example:: # Wrong: class Test(object): for _ in range(10): print('What?!') We also allow some nested classes, check out :class:`NestedClassViolation` for more information. .. versionadded:: 0.7.0 """ error_template = 'Found incorrect node inside `class` body' code = 452 @final class MethodWithoutArgumentsViolation(ASTViolation): """ Forbids to have methods without any arguments. Reasoning: Methods withour arguments are allowed to be defined, but almost impossible to use. Furthermore, they don't have an access to ``self``, so can not access the inner state of the object. It might be an intentional design or just a typo. Solution: Move any methods with arguments to raw functions. Or just add an argument if it is actually required. Example:: # Correct: class Test(object): def method(self): ... # Wrong: class Test(object): def method(): ... .. versionadded:: 0.7.0 """ error_template = 'Found method without arguments: {0}' code = 453 @final class IncorrectBaseClassViolation(ASTViolation): """ Forbids to have methods without any arguments. Reasoning: In Python you can specify anything in the base classes slot. In runtime this expression will be evaluated and executed. We need to prevent dirty hacks in this field. Solution: Use only attributes, names, and types to be your base classes. Example:: # Correct: class Test(module.ObjectName, MixinName, keyword=True): ... class GenericClass(Generic[ValueType]): ... # Wrong: class Test((lambda: object)()): ... .. versionadded:: 0.7.0 .. versionchanged:: 0.7.1 """ error_template = 'Found incorrect base class' code = 454 @final class IncorrectSlotsViolation(ASTViolation): """ Forbids to have incorrect ``__slots__`` definition. Reasoning: ``__slots__`` is a very special attribute. It completely changes your class. So, we need to be careful with it. We should not allow anything rather than tuples to define slots, we also need to check that fields defined in ``__slots__`` are unique. Solution: Use tuples with unique elements to define ``__slots__`` attribute. Example:: # Correct: class Test(object): __slots__ = ('field1', 'field2') class Other(Test): __slots__ = Test.__slots__ + ('child',) # Wrong: class Test(object): __slots__ = ['field1', 'field2', 'field2'] Note, that we do ignore all complex expressions for this field. So, we only check raw literals. .. versionadded:: 0.7.0 """ error_template = 'Found incorrect `__slots__` syntax' code = 455 @final class IncorrectSuperCallViolation(ASTViolation): """ Forbids to use ``super()`` with parameters or outside of methods. Reasoning: ``super()`` is a very special function. It implicitly relies on the context where it is used and parameters passed to it. So, we should be very careful with parameters and context. Solution: Use ``super()`` without arguments and only inside methods. Example:: # Correct: super().__init__() # Wrong: super(ClassName, self).__init__() .. versionadded:: 0.7.0 """ error_template = 'Found incorrect `super()` call: {0}' code = 456 @final class RedundantReturningElseViolation(ASTViolation): """ Forbids to use redundant ``else`` cases in returning functions. We check single ``if`` statements that all contain ``return`` or ``raise`` or ``break`` statements with this rule. We do not check ``if`` statements with ``elif`` cases. Reasoning: Using extra ``else`` creates a situation when the whole node could and should be dropped without any changes in logic. So, we prefer to have less code than more code. Solution: Remove redundant ``else`` case. Example:: # Correct: def some_function(): if some_call(): return 'yeap' return 'nope' # Wrong: def some_function(): if some_call(): raise ValueError('yeap') else: raise ValueError('nope') .. versionadded:: 0.7.0 """ error_template = 'Found redundant returning `else` statement' code = 457 @final class TryExceptMultipleReturnPathViolation(ASTViolation): """ Forbids to use multiple ``return`` path with ``try`` / ``except`` case. Reasoning: The problem with ``return`` in ``else`` and ``finally`` is that it is impossible to say what value is going to be actually returned without looking up the implementation details. Why? Because ``return`` does not expect that some other code will be executed after it. But, ``finally`` is always executed, even after ``return``. And ``else`` will not be executed when there are no exceptions in ``try`` case and a ``return`` statement. Solution: Remove ``return`` from one of the cases. Example:: # Wrong: try: return 1 # this line will never return except Exception: ... finally: return 2 # this line will actually return try: return 1 # this line will actually return except ZeroDivisionError: ... else: return 0 # this line will never return .. versionadded:: 0.7.0 """ error_template = 'Found `try`/`else`/`finally` with multiple return paths' code = 458 PK!9CC1wemake_python_styleguide/violations/complexity.py# -*- coding: utf-8 -*- """ These checks find flaws in your application design. We try to stick to "the magical 7 ± 2 number" when counting things. https://en.wikipedia.org/wiki/The_Magical_Number_Seven,_Plus_or_Minus_Two That's how many objects we can keep in our memory at a time. We try hard not to exceed the memory capacity limit. You can also find interesting reading about "Cognitive complexity": https://www.sonarsource.com/docs/CognitiveComplexity.pdf Note: Simple is better than complex. Complex is better than complicated. .. currentmodule:: wemake_python_styleguide.violations.complexity Summary ------- .. autosummary:: :nosignatures: JonesScoreViolation TooManyImportsViolation TooManyModuleMembersViolation TooManyLocalsViolation TooManyArgumentsViolation TooManyReturnsViolation TooManyExpressionsViolation TooManyMethodsViolation TooManyBaseClassesViolation TooManyDecoratorsViolation TooDeepNestingViolation LineComplexityViolation TooManyConditionsViolation TooManyElifsViolation TooManyForsInComprehensionViolation TooManyExceptCasesViolation Module complexity ----------------- .. autoclass:: JonesScoreViolation .. autoclass:: TooManyImportsViolation .. autoclass:: TooManyModuleMembersViolation Function and class complexity ----------------------------- .. autoclass:: TooManyLocalsViolation .. autoclass:: TooManyArgumentsViolation .. autoclass:: TooManyReturnsViolation .. autoclass:: TooManyExpressionsViolation .. autoclass:: TooManyMethodsViolation .. autoclass:: TooManyBaseClassesViolation .. autoclass:: TooManyDecoratorsViolation Structures complexity --------------------- .. autoclass:: TooDeepNestingViolation .. autoclass:: LineComplexityViolation .. autoclass:: TooManyConditionsViolation .. autoclass:: TooManyElifsViolation .. autoclass:: TooManyForsInComprehensionViolation .. autoclass:: TooManyExceptCasesViolation """ from wemake_python_styleguide.types import final from wemake_python_styleguide.violations.base import ( ASTViolation, SimpleViolation, ) @final class JonesScoreViolation(SimpleViolation): """ Forbids to have modules with complex lines. We are using Jones Complexity algorithm to count module's score. See :py:class:`~.LineComplexityViolation` for details of per-line-complexity. How it is done: we count complexity per line, then measuring the median complexity across the lines in the whole module. Reasoning: Having complex modules will decrease your code maintainability. Solution: Refactor the module contents. Configuration: This rule is configurable with ``--max-jones-score``. Default: :str:`wemake_python_styleguide.options.defaults.MAX_JONES_SCORE` .. versionadded:: 0.1.0 See also: https://github.com/Miserlou/JonesComplexity """ error_template = 'Found module with high Jones Complexity score: {0}' code = 200 @final class TooManyImportsViolation(SimpleViolation): """ Forbids to have modules with too many imports. Namespaces are one honking great idea -- let's do more of those! Reasoning: Having too many imports without prefixes is quite expensive. You have to memorize all the source locations of the imports. And sometimes it is hard to remember what kind of functions and classes are already injected into your context. It is also a questionable design if a single module has a lot of imports. Why a single module has so many dependencies? So, it becomes too coupled. Solution: Refactor the imports to import a common namespace. Something like ``from package import module`` and then use it like ``module.function()``. Or refactor your code and split the complex module into several ones. We do not make any differences between ``import`` and ``from ... import ...``. Configuration: This rule is configurable with ``--max-imports``. Default: :str:`wemake_python_styleguide.options.defaults.MAX_IMPORTS` .. versionadded:: 0.1.0 """ error_template = 'Found module with too many imports: {0}' code = 201 @final class TooManyModuleMembersViolation(SimpleViolation): """ Forbids to have many classes and functions in a single module. Reasoning: Having many classes and functions in a single module is a bad thing. Soon it will be hard to read through this code and understand it. Solution: It is better to split this module into several modules or a package. We do not make any differences between classes and functions in this check. They are treated as the same unit of logic. We also do not care about functions and classes being public or not. However, methods are counted separately on a per-class basis. Configuration: This rule is configurable with ``--max-module-members``. Default: :str:`wemake_python_styleguide.options.defaults.MAX_MODULE_MEMBERS` .. versionadded:: 0.1.0 """ error_template = 'Found too many module members: {0}' code = 202 # Functions and classes: @final class TooManyLocalsViolation(ASTViolation): """ Forbids to have too many local variables in the unit of code. Reasoning: Having too many variables in a single function is a bad thing. Soon, you will find troubles to understand what this variable means. It will also become hard to name new variables. Solution: If you have too many variables in a function, you have to refactor it. What counts as a local variable? We only count variable as local in the following case: it is assigned inside the function body. We do not count variables defined inside comprehensions as local variables, since it is impossible to use them outside of the comprehension. Example:: def first_function(param): first_var = 1 def second_function(argument): second_var = 1 argument = int(argument) third_var, _ = some_call() In this example we will count as locals only several variables: 1. ``first_var``, because it is assigned inside the function's body 2. ``second_var``, because it is assigned inside the function's body 3. ``argument``, because it is reassigned inside the function's body 4. ``third_var``, because it is assigned inside the function's body Please, note that ``_`` is a special case. It is not counted as a local variable. Since by design it means: do not count me as a real variable. Configuration: This rule is configurable with ``--max-local-variables``. Default: :str:`wemake_python_styleguide.options.defaults.MAX_LOCAL_VARIABLES` .. versionadded:: 0.1.0 """ error_template = 'Found too many local variables: {0}' code = 210 @final class TooManyArgumentsViolation(ASTViolation): """ Forbids to have too many arguments for a function or method. Reasoning: This is an indicator of a bad design. When a function requires many arguments it shows that it is required to refactor this piece of code. It also indicates that function does too many things at once. Solution: Split function into several functions. Then it will be easier to use them. Configuration: This rule is configurable with ``--max-arguments``. Default: :str:`wemake_python_styleguide.options.defaults.MAX_ARGUMENTS` .. versionadded:: 0.1.0 """ error_template = 'Found too many arguments: {0}' code = 211 @final class TooManyReturnsViolation(ASTViolation): """ Forbids placing too many ``return`` statements into the function. Reasoning: When there are too many ``return`` keywords, functions are hard to test. They are also hard to read and hard to change and keep everything inside your head at once. Solution: Change your design. Configuration: This rule is configurable with ``--max-returns``. Default: :str:`wemake_python_styleguide.options.defaults.MAX_RETURNS` .. versionadded:: 0.1.0 """ error_template = 'Found too many return statements: {0}' code = 212 @final class TooManyExpressionsViolation(ASTViolation): """ Forbids putting too many expressions in a unit of code. Reasoning: When there are too many expressions it means that this specific function does too many things at once. It has too much logic. Solution: Split function into several functions, refactor your API. Configuration: This rule is configurable with ``--max-expressions``. Default: :str:`wemake_python_styleguide.options.defaults.MAX_EXPRESSIONS` .. versionadded:: 0.1.0 """ error_template = 'Found too many expressions: {0}' code = 213 @final class TooManyMethodsViolation(ASTViolation): """ Forbids to have many methods in a single class. Reasoning: Having too many methods might lead to the "God object". This kind of objects can handle everything. So, in the end, your code becomes too hard to maintain and test. Solution: What to do if you have too many methods in a single class? Split this class into several classes. Then use composition or inheritance to refactor your code. This will protect you from "God object" anti-pattern. We do not make any difference between instance and class methods. We also do not care about functions and classes being public or not. We also do not count inherited methods from parents. This rule does not count the attributes of a class. Configuration: This rule is configurable with ``--max-methods``. Default: :str:`wemake_python_styleguide.options.defaults.MAX_METHODS` .. versionadded:: 0.1.0 See also: https://en.wikipedia.org/wiki/God_object """ error_template = 'Found too many methods: {0}' code = 214 class TooManyBaseClassesViolation(ASTViolation): """ Restrict the maximum number of base classes. Reasoning: It is almost never possible to navigate to the desired method of a parent class when you need it with multiple mixins. It is hard to understand ``mro`` and ``super`` calls. Do not overuse this technique. Solution: Reduce the number of base classes. Use composition over inheritance. Example:: # Correct: class SomeClassName(First, Second, Mixin): ... # Wrong: class SomeClassName( FirstParentClass, SecondParentClass, ThirdParentClass, CustomClass, AddedClass, ): ... Configuration: This rule is configurable with ``--max-base-classes``. Default: :str:`wemake_python_styleguide.options.defaults.MAX_BASE_CLASSES` .. versionadded:: 0.3.0 .. versionchanged:: 0.5.0 See also: https://en.wikipedia.org/wiki/Composition_over_inheritance """ error_template = 'Too many base classes: {0}' code = 215 class TooManyDecoratorsViolation(ASTViolation): """ Restrict the maximum number of decorators. Reasoning: When you are using too many decorators it means that you try to overuse the magic. You have to ask yourself: do I really know what happens inside this decorator tree? Typically, the answer will be "no". Solution: Using too many decorators typically means that you try to configure the behavior from outside of the class. Do not do that too much. Split functions or classes into multiple ones. Use higher order decorators. Configuration: This rule is configurable with ``--max-decorators``. Default: :str:`wemake_python_styleguide.options.defaults.MAX_DECORATORS` This rule checks: functions, methods, and classes. .. versionadded:: 0.5.0 """ error_template = 'Too many decorators: {0}' code = 216 # Structures: @final class TooDeepNestingViolation(ASTViolation): """ Forbids nesting blocks too deep. Reasoning: If nesting is too deep that indicates usage of complex logic and language constructions. This means that our design is not suited to handle such construction. Solution: We need to refactor our complex construction into simpler ones. We can use new functions or different constructions. .. versionadded:: 0.1.0 .. versionchanged:: 0.5.0 """ error_template = 'Found too deep nesting: {0}' code = 220 @final class LineComplexityViolation(ASTViolation): """ Forbids to have complex lines. We are using Jones Complexity algorithm to count complexity. What is Jones Complexity? It is a simple yet powerful method to count the number of ``ast`` nodes per line. If the complexity of a single line is higher than a threshold, then an error is raised. What nodes do we count? All except the following: 1. modules 2. function and classes, since they are checked differently 3. type annotations, since they do not increase the complexity Reasoning: Having a complex line indicates that you somehow managed to put too much logic inside a single line. At some point in time, you will no longer be able to understand what this line means and what it does. Solution: Split a single line into several lines: by creating new variables, statements or functions. Note, this might trigger new complexity issues. With this technique, a single new node in a line might trigger a complex refactoring process including several modules. Configuration: This rule is configurable with ``--max-line-complexity``. Default: :str:`wemake_python_styleguide.options.defaults.MAX_LINE_COMPLEXITY` .. versionadded:: 0.1.0 See also: https://github.com/Miserlou/JonesComplexity """ error_template = 'Found line with high Jones Complexity: {0}' code = 221 @final class TooManyConditionsViolation(ASTViolation): """ Forbids to have conditions with too many logical operators. Reasoning: When reading through the complex conditions you will fail to understand all the possible branches. And you will end up putting debug breakpoint on this line just to figure out how it works. Solution: We can reduce the complexity of a single ``if`` by doing two things: creating new variables or creating nested ``if`` statements. Both of these actions will trigger other complexity checks. We count ``and`` and ``or`` keywords as conditions. .. versionadded:: 0.1.0 .. versionchanged:: 0.5.0 """ error_template = 'Found a condition with too much logic: {0}' code = 222 @final class TooManyElifsViolation(ASTViolation): """ Forbids to use many ``elif`` branches. Reasoning: This rule is specifically important because of many ``elif`` branches indicate a complex flow in your design: you are reimplementing ``switch`` in python. Solution: There are different design patterns to use instead. For example, you can use some interface that just call a specific method without ``if``. Or separate your ``if`` into multiple functions. .. versionadded:: 0.1.0 .. versionchanged:: 0.5.0 """ error_template = 'Found too many `elif` branches: {0}' code = 223 @final class TooManyForsInComprehensionViolation(ASTViolation): """ Forbids to have too many ``for`` statement within a comprehension. Reasoning: When reading through the complex comprehension you will fail to understand it. Solution: We can reduce the complexity of comprehension by reducing the amount of ``for`` statements. Refactor your code to use several ``for`` loops, comprehensions, or different functions. Example:: # Wrong: ast_nodes = [ target for assignment in top_level_assigns for target in assignment.targets for _ in range(10) ] .. versionadded:: 0.3.0 """ error_template = 'Found a comprehension with too many `for` statements' code = 224 @final class TooManyExceptCasesViolation(ASTViolation): """ Forbids to have too many ``except`` cases in a single ``try`` clause. Reasoning: Handling too many exceptions in a single place is a good indicator of a bad design. Since this way, one controlling structure will become too complex. And you will need to test a lot of paths your application might go. Solution: We can reduce the complexity of this case by splitting it into multiple ``try`` cases, functions or using a decorator to handle different exceptions. .. versionadded:: 0.7.0 """ error_template = 'Found too many `except` cases' code = 225 PK!B"ff2wemake_python_styleguide/violations/consistency.py# -*- coding: utf-8 -*- """ These checks limit the Python's inconsistency. We can do the same things differently in Python. For example, there are three ways to format a string. There are several ways to write the same number. We like our code to be consistent. It is easier to bare with your code base if you follow these rules. So, we choose a single way to do things. It does not mean that we choose the best way to do it. But, we value consistency more than being 100% right. And we are ready to suffer all trade-offs that might come. Once again, these rules are highly subjective. But, we love them. .. currentmodule:: wemake_python_styleguide.violations.consistency Summary ------- .. autosummary:: :nosignatures: LocalFolderImportViolation DottedRawImportViolation UnicodeStringViolation UnderscoredNumberViolation PartialFloatViolation FormattedStringViolation RequiredBaseClassViolation MultipleIfsInComprehensionViolation ConstantComparisonViolation ComparisonOrderViolation BadNumberSuffixViolation MultipleInComparisonViolation RedundantComparisonViolation MissingSpaceBetweenKeywordAndParenViolation WrongConditionalViolation ObjectInBaseClassesListViolation MultipleContextManagerAssignmentsViolation ParametersIndentationViolation ExtraIndentationViolation WrongBracketPositionViolation MultilineFunctionAnnotationViolation UppercaseStringModifierViolation IncorrectMultilineStringViolation EmptyLineAfterCodingViolation InconsistentReturnViolation InconsistentYieldViolation ImplicitStringConcatenationViolation UselessContinueViolation UselessNodeViolation UselessExceptCaseViolation Consistency checks ------------------ .. autoclass:: LocalFolderImportViolation .. autoclass:: DottedRawImportViolation .. autoclass:: UnicodeStringViolation .. autoclass:: UnderscoredNumberViolation .. autoclass:: PartialFloatViolation .. autoclass:: FormattedStringViolation .. autoclass:: RequiredBaseClassViolation .. autoclass:: MultipleIfsInComprehensionViolation .. autoclass:: ConstantComparisonViolation .. autoclass:: ComparisonOrderViolation .. autoclass:: BadNumberSuffixViolation .. autoclass:: MultipleInComparisonViolation .. autoclass:: RedundantComparisonViolation .. autoclass:: MissingSpaceBetweenKeywordAndParenViolation .. autoclass:: WrongConditionalViolation .. autoclass:: ObjectInBaseClassesListViolation .. autoclass:: MultipleContextManagerAssignmentsViolation .. autoclass:: ParametersIndentationViolation .. autoclass:: ExtraIndentationViolation .. autoclass:: WrongBracketPositionViolation .. autoclass:: MultilineFunctionAnnotationViolation .. autoclass:: UppercaseStringModifierViolation .. autoclass:: IncorrectMultilineStringViolation .. autoclass:: EmptyLineAfterCodingViolation .. autoclass:: InconsistentReturnViolation .. autoclass:: InconsistentYieldViolation .. autoclass:: ImplicitStringConcatenationViolation .. autoclass:: UselessContinueViolation .. autoclass:: UselessNodeViolation .. autoclass:: UselessExceptCaseViolation """ from wemake_python_styleguide.types import final from wemake_python_styleguide.violations.base import ( ASTViolation, TokenizeViolation, ) @final class LocalFolderImportViolation(ASTViolation): """ Forbids to have imports relative to the current folder. Reasoning: We should pick one style and stick to it. We have decided to use the explicit one. Solution: Refactor your imports to use the absolute path. Example:: # Correct: from my_package.version import get_version # Wrong: from .version import get_version from ..drivers import MySQLDriver .. versionadded:: 0.1.0 """ error_template = 'Found local folder import' code = 300 @final class DottedRawImportViolation(ASTViolation): """ Forbids to use imports like ``import os.path``. Reasoning: There too many different ways to import something. We should pick one style and stick to it. We have decided to use the readable one. Solution: Refactor your import statement. Example:: # Correct: from os import path # Wrong: import os.path .. versionadded:: 0.1.0 """ error_template = 'Found dotted raw import: {0}' code = 301 @final class UnicodeStringViolation(TokenizeViolation): """ Forbids to use ``u`` string prefix. Reasoning: We do not need this prefix since ``python2``. But, it is still possible to find it inside the codebase. Solution: Remove this prefix. Example:: # Correct: nickname = 'sobolevn' file_contents = b'aabbcc' # Wrong: nickname = u'sobolevn' .. versionadded:: 0.1.0 """ code = 302 error_template = 'Found unicode string prefix: {0}' @final class UnderscoredNumberViolation(TokenizeViolation): """ Forbids to use underscores (``_``) in numbers. Reasoning: It is possible to write ``1000`` in three different ways: ``1_000``, ``10_00``, and ``100_0``. And it would be still the same number. Count how many ways there are to write bigger numbers. Currently, it all depends on the cultural habits of the author. We enforce a single way to write numbers: without the underscore. Solution: Numbers should be written as numbers: ``1000``. If you have a very big number with a lot of zeros, use multiplication. Example:: # Correct: phone = 88313443 million = 1000000 # Wrong: phone = 8_83_134_43 million = 100_00_00 .. versionadded:: 0.1.0 """ code = 303 error_template = 'Found underscored number: {0}' @final class PartialFloatViolation(TokenizeViolation): """ Forbids to use partial floats like ``.05`` or ``23.``. Reasoning: Partial numbers are hard to read and they can be confused with other numbers. For example, it is really easy to confuse ``0.5`` and ``.05`` when reading through the source code. Solution: Use full versions with leading and starting zeros. Example:: # Correct: half = 0.5 ten_float = 10.0 # Wrong: half = .5 ten_float = 10. .. versionadded:: 0.1.0 """ code = 304 error_template = 'Found partial float: {0}' @final class FormattedStringViolation(ASTViolation): """ Forbids to use ``f`` strings. Reasoning: ``f`` strings loses context too often and they are hard to lint. Imagine that you have a string that breaks when you move it two lines above. That's not how a string should behave. Also, they promote a bad practice: putting your logic inside the template. Solution: Use ``.format()`` with indexed params instead. See also: https://github.com/xZise/flake8-string-format Example:: # Wrong: f'Result is: {2 + 2}' # Correct: 'Result is: {0}'.format(2 + 2) 'Hey {user}! How are you?'.format(user='sobolevn') .. versionadded:: 0.1.0 """ error_template = 'Found `f` string' code = 305 @final class RequiredBaseClassViolation(ASTViolation): """ Forbids to write classes without base classes. Reasoning: We just need to decide how to do it. We need a single and unified rule about base classes. We have decided to stick to the explicit base class notation. Solution: Add a base class. Example:: # Correct: class Some(object): ... # Wrong: class Some: ... .. versionadded:: 0.1.0 """ error_template = 'Found class without a base class: {0}' code = 306 @final class MultipleIfsInComprehensionViolation(ASTViolation): """ Forbids to have multiple ``if`` statements inside list comprehensions. Reasoning: It is very hard to read multiple ``if`` statements inside a list comprehension. Since it is even hard to tell all of them should pass or fail. Solution: Use a single ``if`` statement inside list comprehensions. Use ``filter()`` if you have complicated logic. Example:: # Wrong: nodes = [node for node in html if node != 'b' if node != 'i'] # Correct: nodes = [node for node in html if node not in ('b', 'i')] .. versionadded:: 0.1.0 """ error_template = 'Found list comprehension with multiple `if`s' code = 307 @final class ConstantComparisonViolation(ASTViolation): """ Forbids to have comparisons between two literals. Reasoning: When two constants are compared it is typically an indication of a mistake, since the Boolean value of the comparison, will always be the same. Solution: Remove the constant comparison and any associated dead code. Example:: # Wrong: if 60 * 60 < 1000: do_something() else: do_something_else() # Correct: do_something_else() .. versionadded:: 0.3.0 """ error_template = 'Found constant comparison' code = 308 @final class ComparisonOrderViolation(ASTViolation): """ Forbids comparision where argument doesn't come first. Reasoning: It is hard to read the code when you have to shuffle ordering of the arguments all the time. Bring consistency to the comparison! Solution: Refactor your comparison expression, place the argument first. Example:: # Correct: if some_x > 3: if 3 < some_x < 10: # Wrong: if 3 < some_x: .. versionadded:: 0.3.0 """ error_template = 'Found reversed comparison order' code = 309 @final class BadNumberSuffixViolation(TokenizeViolation): """ Forbids to use capital ``X``, ``O``, ``B``, and ``E`` in numbers. Reasoning: Octal, hex, binary and scientific notation suffixes could be written in two possible notations: lowercase and uppercase. Which brings confusion and decreases code consistency and readability. We enforce a single way to write numbers with suffixes: suffix with lowercase chars. Solution: Octal, hex, binary and scientific notation suffixes in numbers should be written lowercase. Example:: # Correct: hex_number = 0xFF octal_number = 0o11 binary_number = 0b1001 number_with_scientific_notation = 1.5e+10 # Wrong: hex_number = 0XFF octal_number = 0O11 binary_number = 0B1001 number_with_scientific_notation = 1.5E+10 .. versionadded:: 0.3.0 """ error_template = 'Found bad number suffix: {0}' code = 310 @final class MultipleInComparisonViolation(ASTViolation): """ Forbids comparision where multiple ``in`` checks. Reasoning: Using multiple ``in`` is unreadable. Solution: Refactor your comparison expression to use several ``and`` conditions or separate ``if`` statements in case it is appropriate. Example:: # Correct: if item in bucket and bucket in master_list_of_buckets: if x_coord in line and line in square: # Wrong: if item in bucket in master_list_of_buckets: if x_cord in line in square: .. versionadded:: 0.3.0 """ error_template = 'Found multiple `in` comparisons' code = 311 @final class RedundantComparisonViolation(ASTViolation): """ Forbids to have comparisons between the same variable. Reasoning: When the same variables are compared it is typically an indication of a mistake, since the Boolean value of the comparison will always be the same. Solution: Remove the same variable comparison and any associated dead code. Example:: # Wrong: a = 1 if a < a: do_something() else: do_something_else() # Correct: do_something() .. versionadded:: 0.3.0 """ error_template = 'Found comparison between same variable' code = 312 @final class MissingSpaceBetweenKeywordAndParenViolation(TokenizeViolation): """ Enforces to separate parenthesis from the keywords with spaces. Reasoning: Some people use ``return`` and ``yield`` keywords as functions. The same happened to good old ``print`` in Python2. Solution: Insert space symbol between keyword and open paren. Example:: # Wrong: def func(): a = 1 b = 2 del(a, b) yield(1, 2, 3) # Correct: def func(): a = 1 del (a, b) yield (1, 2, 3) .. versionadded:: 0.3.0 """ error_template = 'Found parens right after a keyword' code = 313 class WrongConditionalViolation(ASTViolation): """ Forbids using ``if`` statements that use invalid conditionals. Reasoning: When invalid conditional arguments are used it is typically an indication of a mistake, since the value of the conditional result will always be the same. Solution: Remove the conditional and any associated dead code. Example:: # Correct: if value is True: ... # Wrong: if True: ... .. versionadded:: 0.3.0 """ error_template = 'Conditional always evaluates to same result' code = 314 class ObjectInBaseClassesListViolation(ASTViolation): """ Forbids extra ``object`` in parent classes list. Reasoning: We should allow object only when we explicitly use it as a single parent class. When there is another class or there are multiple parents - we should not allow it for the consistency reasons. Solution: Remove extra ``object`` parent class from the list. Example:: # Correct: class SomeClassName(object): ... class SomeClassName(FirstParentClass, SecondParentClass): ... # Wrong: class SomeClassName(FirstParentClass, SecondParentClass, object): ... .. versionadded:: 0.3.0 """ error_template = 'Founded extra `object` in parent classes list' code = 315 @final class MultipleContextManagerAssignmentsViolation(ASTViolation): """ Forbids multiple assignment targets for context managers. Reasoning: It is hard to distinguish whether ``as`` should unpack into tuple or we are just using two context managers. Solution: Use several context managers. Or explicit brackets. Example:: # Correct: with open('') as first: with second: ... with some_context as (first, second): ... # Wrong: with open('') as first, second: ... .. versionadded:: 0.6.0 """ error_template = 'Found context manager with too many assignments' code = 316 @final class ParametersIndentationViolation(ASTViolation): """ Forbids to use incorrect parameters indentation. Reasoning: It is really easy to spoil your perfect, readable code with incorrect multi-line parameters indentation. Since it is really easy to style them in any of 100 possible ways. We enforce a strict rule about how it is possible to write these multi-line parameters. Solution: Use consistent multi-line parameters indentation. Example:: # Correct: def my_function(arg1, arg2, arg3) -> None: return None print(1, 2, 3, 4, 5, 6) def my_function( arg1, arg2, arg3, ) -> None: return None print( 1, 2, 3, 4, 5, 6, ) def my_function( arg1, arg2, arg3, ) -> None: return None print( first_variable, 2, third_value, 4, 5, last_item, ) # Special case: print('some text', 'description', [ first_variable, second_variable, third_variable, last_item, ], end='') Everything else is considered a violation. This rule checks: lists, sets, tuples, dicts, calls, functions, methods, and classes. .. versionadded:: 0.6.0 """ error_template = 'Found incorrect multi-line parameters' code = 317 @final class ExtraIndentationViolation(TokenizeViolation): """ Forbids to use extra indentation. Reasoning: You can use extra indentation for lines of code. Python allows you to do that in case you will keep the indentation level equal for this specific node. But, that's insane! Solution: We should stick to 4 spaces for an indentation block. Each next block should be indented by just 4 extra spaces. Example:: # Correct: def test(): print('test') # Wrong: def test(): print('test') .. versionadded:: 0.6.0 """ error_template = 'Found extra indentation' code = 318 @final class WrongBracketPositionViolation(TokenizeViolation): """ Forbids to use extra indentation. Reasoning: You can use extra indentation for lines of code. Python allows you to do that in case you will keep the indentation level equal for this specific node. But, that's insane! Solution: Place bracket on the same line, when a single line expression. Or place the bracket on a new line when a multi-line expression. Example:: # Correct: print([ 1, 2, 3, ]) print( 1, 2, ) def _annotate_brackets( tokens: List[tokenize.TokenInfo], ) -> TokenLines: ... # Wrong: print([ 1, 2, 3], ) print( 1, 2) def _annotate_brackets( tokens: List[tokenize.TokenInfo]) -> TokenLines: ... We check round, square, and curly brackets. .. versionadded:: 0.6.0 """ error_template = 'Found bracket in wrong position' code = 319 @final class MultilineFunctionAnnotationViolation(ASTViolation): """ Forbids to use multi-line function type annotations. Reasoning: Functions with multi-line type annotations are unreadable. Solution: Use type annotations that fit into a single line to annotate functions. If your annotation is too long, then use type aliases. Example:: # Correct: def create_list(length: int) -> List[int]: ... # Wrong: def create_list(length: int) -> List[ int, ]: ... This rule checks argument and return type annotations. .. versionadded:: 0.6.0 """ error_template = 'Found multi-line function type annotation' code = 320 @final class UppercaseStringModifierViolation(TokenizeViolation): """ Forbids to use uppercase string modifiers. Reasoning: String modifiers should be consistent. Solution: Use lowercase modifiers should be written in lowercase. Example:: # Correct: some_string = r'/regex/' some_bytes = b'123' # Wrong: some_string = R'/regex/' some_bytes = B'123' .. versionadded:: 0.6.0 """ error_template = 'Found uppercase string modifier: {0}' code = 321 @final class IncorrectMultilineStringViolation(TokenizeViolation): ''' Forbids to use triple quotes for singleline strings. Reasoning: String quotes should be consistent. Solution: Use single quotes for single-line strings. Triple quotes are only allowed for real multiline strings. Example:: # Correct: single_line = 'abc' multiline = """ one two """ # Wrong: some_string = """abc""" some_bytes = b"""123""" Docstrings are ignored from this rule. You must use triple quotes strings for docstrings. .. versionadded:: 0.7.0 ''' error_template = 'Found incorrect multi-line string' code = 322 @final class EmptyLineAfterCodingViolation(TokenizeViolation): """ Enforces to have an extra empty line after the ``coding`` comment. Reasoning: This is done for pure consistency. Solution: Add an empty line between ``coding`` magic comment and your code. Example:: # Correct: # coding: utf-8 SOME_VAR = 1 # Wrong: # coding: utf-8 SOME_VAR = 1 .. versionadded:: 0.7.0 """ error_template = ( 'Found missing empty line between `coding` magic comment and code' ) code = 323 @final class InconsistentReturnViolation(ASTViolation): """ Enforces to have consistent ``return`` statements. Rules are: 1. if any ``return`` has a value, all ``return`` nodes should have a value 2. do not place ``return`` without value at the end of a function This rule respects ``mypy`` style of placing ``return`` statements. There should be no conflict with these two checks. Reasoning: This is done for pure consistency and readability of your code. Eventually, this rule may also find some bugs in your code. Solution: Add or remove values from the ``return`` statements to make them consistent. Remove ``return`` statement from the function end. Example:: # Correct: def function(): if some: return 2 return 1 # Wrong: def function(): if some: return return 1 def function(): if some: print(some) return .. versionadded:: 0.7.0 """ error_template = 'Found inconsistent `return` statement' code = 324 @final class InconsistentYieldViolation(ASTViolation): """ Enforces to have consistent ``yield`` statements. Rules are: 1. if any ``yield`` has a value, all ``yield`` nodes should have a value This rule respects ``mypy`` style of placing ``yield`` statements. There should be no conflict with these two checks. Reasoning: This is done for pure consistency and readability of your code. Eventually, this rule may also find some bugs in your code. Solution: Add or remove values from the ``yield`` statements to make them consistent. Example:: # Correct: def function(): if some: yield 2 yield 1 # Wrong: def function(): if some: yield yield 1 .. versionadded:: 0.7.0 """ error_template = 'Found inconsistent `yield` statement' code = 325 @final class ImplicitStringConcatenationViolation(TokenizeViolation): """ Forbids to use implicit string contacatenation. Reasoning: This is error-prone, since you can possible miss a comma in a collection of string and get an implicit concatenation. And because there are different and safe ways to do the same thing it is better to use them instead. Solution: Use ``+`` or ``.format()`` to join strings. Example:: # Correct: text = 'first' + 'second' # Wrong: text = 'first' 'second' .. versionadded:: 0.7.0 """ error_template = 'Found implicit string concatenation' code = 326 @final class UselessContinueViolation(ASTViolation): """ Forbids to use meaningless ``continue`` node in loops. Reasoning: Placing this keyword in the end of any loop won't make any difference to your code. And we prefer not to have meaningless constructs in our code. Solution: Remove useless ``continue`` node from the loop. Example:: # Correct: for number in [1, 2, 3]: if number < 2: continue print(number) # Wrong: for number in [1, 2, 3]: print(number) continue .. versionadded:: 0.7.0 """ error_template = 'Found useless `continue` at the end of the loop' code = 327 @final class UselessNodeViolation(ASTViolation): """ Forbids to use meaningless nodes. Reasoning: Some nodes might be completely useless. They will literally do nothing. Sometimes they are hard to find, because this situation can be caused by a recent refactoring or just by acedent. This might be also an overuse of syntax. Solution: Remove node or make sure it makes any sense. Example:: # Wrong: for number in [1, 2, 3]: break .. versionadded:: 0.7.0 """ error_template = 'Found useless node: {0}' code = 328 class UselessExceptCaseViolation(ASTViolation): """ Forbids to use meaningless ``except`` cases. Reasoning: Using ``except`` cases that just reraise the same exception is error-prone. You can increase your stacktrace, silence some potential exceptions, and screw things up. It also does not make any sense to do so. Solution: Remove ``except`` case or make sure it makes any sense. Example:: # Correct: try: ... except IndexError: sentry.log() raise ValueError() # Wrong: try: ... except TypeError: raise .. versionadded:: 0.7.0 """ error_template = 'Found useless `except` case' code = 329 PK!cߺ ??-wemake_python_styleguide/violations/naming.py# -*- coding: utf-8 -*- """ Naming is hard! It is, in fact, one of the two hardest problems. These checks are required to make your application easier to read and understand by multiple people over the long period of time. Naming convention ----------------- Our naming convention tries to cover all possible cases. It is partially automated with this linter, but: - Some rules are still WIP - Some rules will never be automated, code reviews to the rescue! General ~~~~~~~ - Use only ``ASCII`` chars for names - Do not use transliteration from any other languages, translate names instead - Use clear names, do not use words that do not mean anything like ``obj`` - Use names of an appropriate length: not too short, not too long - Protected members should use underscore as the first char - Private names with two leading underscores are not allowed - If you need to explicitly state that the variable is unused, prefix it with ``_`` or just use ``_`` as a name - Do not use variables that are stated to be unused, rename them when actually using them - Whenever you want to name your variable similar to a keyword or builtin, use trailing ``_`` - Do not use consecutive underscores - When writing abbreviations in ``UpperCase`` capitalize all letters: ``HTTPAddress`` - When writing abbreviations in ``snake_case`` use lowercase: ``http_address`` - When writing numbers in ``snake_case`` do not use extra ``_`` before numbers as in ``http2_protocol`` Packages ~~~~~~~~ - Packages must use ``snake_case`` - One word for a package is the most preferable name Modules ~~~~~~~ - Modules must use ``snake_case`` - Module names must not overuse magic names - Module names must be valid Python identifiers Classes ~~~~~~~ - Classes must use ``UpperCase`` - Python's built-in classes, however, are typically lowercase words - Exception classes must end with ``Error`` Instance attributes ~~~~~~~~~~~~~~~~~~~ - Instance attributes must use ``snake_case`` with no exceptions Class attributes ~~~~~~~~~~~~~~~~ - Class attributes must use ``snake_case`` with no exceptions Functions and methods ~~~~~~~~~~~~~~~~~~~~~ - Functions and methods must use ``snake_case`` with no exceptions Method and function arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Instance methods must have their first argument named ``self`` - Class methods must have their first argument named ``cls`` - Metaclass methods must have their first argument named ``mcs`` - Python's ``*args`` and ``**kwargs`` should be default names when just passing these values to some other method/function, unless you want to use these values in place, then name them explicitly - Keyword-only arguments must be separated from other arguments with ``*`` Global (module level) variables ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Global variables must use ``CONSTANT_CASE`` - Unless other is required by the API, example: ``urlpatterns`` in Django Variables ~~~~~~~~~ - Variables must use ``snake_case`` with no exceptions - When a variable is unused it must be prefixed with an underscore: ``_user`` Type aliases ~~~~~~~~~~~~ - Must use ``UpperCase`` as real classes - Must not contain word ``type`` in its name - Generic types should be called ``TT`` or ``KT`` or ``VT`` - Covariant and contravariant types should be marked with ``Cov`` and ``Contra`` suffixes, in this case, one letter can be dropped: ``TCov`` and ``KContra`` .. currentmodule:: wemake_python_styleguide.violations.naming Summary ------- .. autosummary:: :nosignatures: WrongModuleNameViolation WrongModuleMagicNameViolation WrongModuleNamePatternViolation WrongVariableNameViolation TooShortNameViolation PrivateNameViolation SameAliasImportViolation UnderscoredNumberNameViolation UpperCaseAttributeViolation ConsecutiveUnderscoresInNameViolation ReservedArgumentNameViolation TooLongNameViolation UnicodeNameViolation TrailingUnderscoreViolation UnusedVariableIsUsedViolation Module names ------------ .. autoclass:: WrongModuleNameViolation .. autoclass:: WrongModuleMagicNameViolation .. autoclass:: WrongModuleNamePatternViolation General names ------------- .. autoclass:: WrongVariableNameViolation .. autoclass:: TooShortNameViolation .. autoclass:: PrivateNameViolation .. autoclass:: SameAliasImportViolation .. autoclass:: UnderscoredNumberNameViolation .. autoclass:: UpperCaseAttributeViolation .. autoclass:: ConsecutiveUnderscoresInNameViolation .. autoclass:: ReservedArgumentNameViolation .. autoclass:: TooLongNameViolation .. autoclass:: UnicodeNameViolation .. autoclass:: TrailingUnderscoreViolation .. autoclass:: UnusedVariableIsUsedViolation """ from wemake_python_styleguide.types import final from wemake_python_styleguide.violations.base import ( ASTViolation, MaybeASTViolation, SimpleViolation, ) @final class WrongModuleNameViolation(SimpleViolation): """ Forbids to use blacklisted module names. Reasoning: Some module names are not expressive enough. It is hard to tell what you can find inside the ``utils.py`` module. Solution: Rename your module, reorganize the contents. See :py:data:`~wemake_python_styleguide.constants.MODULE_NAMES_BLACKLIST` for the full list of bad module names. Example:: # Correct: github.py views.py # Wrong: utils.py helpers.py .. versionadded:: 0.1.0 """ error_template = 'Found wrong module name' code = 100 @final class WrongModuleMagicNameViolation(SimpleViolation): """ Forbids to use any magic names except whitelisted ones. Reasoning: Do not fall in love with magic. There's no good reason to use magic names when you can use regular names. See :py:data:`~wemake_python_styleguide.constants.MAGIC_MODULE_NAMES_WHITELIST` for the full list of allowed magic module names. Example:: # Correct: __init__.py __main__.py # Wrong: __version__.py .. versionadded:: 0.1.0 """ error_template = 'Found wrong module magic name' code = 101 @final class WrongModuleNamePatternViolation(SimpleViolation): """ Forbids to use module names that do not match our pattern. Reasoning: Module names must be valid python identifiers. And just like the variable names - module names should be consistent. Ideally, they should follow the same rules. For ``python`` world it is common to use ``snake_case`` notation. We use :py:data:`~wemake_python_styleguide.constants.MODULE_NAME_PATTERN` to validate the module names. Example:: # Correct: __init__.py some_module_name.py test12.py # Wrong: _some.py MyModule.py 0001_migration.py .. versionadded:: 0.1.0 """ error_template = 'Found incorrect module name pattern' code = 102 # General names: @final class WrongVariableNameViolation(ASTViolation): """ Forbids to have blacklisted variable names. Reasoning: We have found some names that are not expressive enough. However, they appear in the code more than often. All names that we forbid to use could be improved. Solution: Try to use a more specific name instead. If you really want to use any of the names from the list, add a prefix or suffix to it. It will serve you well. See :py:data:`~wemake_python_styleguide.constants.VARIABLE_NAMES_BLACKLIST` for the full list of blacklisted variable names. Example:: # Correct: html_node_item = None # Wrong: item = None .. versionadded:: 0.1.0 """ error_template = 'Found wrong variable name: {0}' code = 110 @final class TooShortNameViolation(MaybeASTViolation): """ Forbids to have too short variable or module names. Reasoning: It is hard to understand what the variable means and why it is used, if its name is too short. Solution: Think of another name. Give more context to it. This rule checks: modules, variables, attributes, functions, methods, and classes. Example:: # Correct: x_coordinate = 1 abscissa = 2 # Wrong: x = 1 y = 2 Configuration: This rule is configurable with ``--min-name-length``. Default: :str:`wemake_python_styleguide.options.defaults.MIN_NAME_LENGTH` .. versionadded:: 0.1.0 .. versionchanged:: 0.4.0 """ error_template = 'Found too short name: {0}' code = 111 @final class PrivateNameViolation(MaybeASTViolation): """ Forbids to have private name pattern. Reasoning: Private is not private in ``python``. So, why should we pretend it is? This might lead to some serious design flaws. Solution: Rename your variable or method to be protected. Think about your design, why do you want to make it private? Are there any other ways to achieve what you want? This rule checks: modules, variables, attributes, functions, and methods. Example:: # Correct: def _collect_coverage(self): ... # Wrong: def __collect_coverage(self): ... .. versionadded:: 0.1.0 .. versionchanged:: 0.4.0 """ error_template = 'Found private name pattern: {0}' code = 112 @final class SameAliasImportViolation(ASTViolation): """ Forbids to use the same alias as the original name in imports. Reasoning: Why would you even do this in the first place? Example:: # Correct: from os import path # Wrong: from os import path as path .. versionadded:: 0.1.0 """ error_template = 'Found same alias import: {0}' code = 113 @final class UnderscoredNumberNameViolation(MaybeASTViolation): """ Forbids to have names with underscored numbers pattern. Reasoning: This is done for consistency in naming. Solution: Do not put an underscore between text and numbers, that is confusing. Rename your variable or modules do not include underscored numbers. This rule checks: modules, variables, attributes, functions, method, and classes. Please, note that putting an underscore that replaces ``-`` in some names between numbers are fine, example: ``ISO-123-456`` would become ``iso123_456``. Example:: # Correct: star_wars_episode2 = 'awesome!' iso123_456 = 'some data' # Wrong: star_wars_episode_2 = 'not so awesome' iso_123_456 = 'some data' .. versionadded:: 0.3.0 .. versionchanged:: 0.4.0 """ error_template = 'Found underscored name pattern: {0}' code = 114 @final class UpperCaseAttributeViolation(ASTViolation): """ Forbids to use anything but ``snake_case`` for naming class attributes. Reasoning: Constants with upper-case names belong on a module level. Solution: Move your constants to the module level. Rename your variables so that they conform to ``snake_case`` convention. Example:: # Correct: MY_MODULE_CONSTANT = 1 class A(object): my_attribute = 42 # Wrong: class A(object): MY_CONSTANT = 42 .. versionadded:: 0.3.0 """ error_template = 'Found upper-case constant in a class: {0}' code = 115 @final class ConsecutiveUnderscoresInNameViolation(MaybeASTViolation): """ Forbids to use more than one consecutive underscore in variable names. Reasoning: This is done to gain extra readability. This naming rule already exists for module names. Example:: # Correct: some_value = 5 __magic__ = 5 # Wrong: some__value = 5 This rule checks: modules, variables, attributes, functions, and methods. .. versionadded:: 0.3.0 .. versionchanged:: 0.4.0 """ error_template = 'Found consecutive underscores name: {0}' code = 116 @final class ReservedArgumentNameViolation(ASTViolation): """ Forbids to name your variables as ``self``, ``cls``, and ``mcs``. Reasoning: These names are special, they should only be used as first arguments inside methods. Example:: # Correct: class Test(object): def __init__(self): ... # Wrong: cls = 5 lambda self: self + 12 This rule checks: functions and methods. Having any reserved names in ``lambda`` functions is not allowed. .. versionadded:: 0.5.0 """ error_template = 'Found name reserved for first argument: {0}' code = 117 @final class TooLongNameViolation(MaybeASTViolation): """ Forbids to have long short variable or module names. Reasoning: Too long names are unreadable. It is better to use a shorter alternative. Long names also indicate that this variable is too complex, maybe it may require some documentation. Solution: Think of another name. Give less context to it. This rule checks: modules, variables, attributes, functions, methods, and classes. Example:: # Correct: total_price = 25 average_age = 45 # Wrong: final_price_after_fifteen_percent_sales_tax_and_gratuity = 30 total_age_of_all_participants_in_the_survey_divided_by_twelve = 2 Configuration: This rule is configurable with ``--max-name-length``. Default: :str:`wemake_python_styleguide.options.defaults.MAX_NAME_LENGTH` .. versionadded:: 0.5.0 """ error_template = 'Found too long name: {0}' code = 118 @final class UnicodeNameViolation(MaybeASTViolation): """ Forbids to use unicode names. Reasoning: This should be forbidden for sanity, readability, and writability. Solution: Rename your entities so that they contain only ASCII symbols. This rule checks: modules, variables, attributes, functions, methods, and classes. Example:: # Correct: some_variable = 'Text with russian: русский язык' # Wrong: переменная = 42 some_變量 = '' .. versionadded:: 0.5.0 """ error_template = 'Found unicode name: {0}' code = 119 @final class TrailingUnderscoreViolation(ASTViolation): """ Forbids to use trailing ``_`` for names that do not need it. Reasoning: We use trailing underscore for a reason: to indicate that this name shadows a built-in or keyword. So, when overusing this feature for general names: it just harms readability of your program. Solution: Rename your variable not to contain trailing underscores. This rule checks: variables, attributes, functions, methods, and classes. Example:: # Correct: class_ = SomeClass list_ = [] # Wrong: some_variable_ = 1 .. versionadded:: 0.7.0 """ error_template = 'Found regular name with trailing underscore: {0}' code = 120 @final class UnusedVariableIsUsedViolation(ASTViolation): """ Forbids to have use variables that are marked as unused. Reasoning: Sometimes you start to use new logic in your functions, and you start to use variables that once were marked as unused. But, you have not renamed them for some reason. And now you have a lot of confusion: the variable is marked as unused, but you are using it. Why? What's going on? Solution: Rename your variable to be a regular variable without a leading underscore. Example:: # Correct: def function(): first = 15 return first + 10 # Wrong: def function(): _first = 15 return _first + 10 This rule checks: functions, methods, and ``lambda`` functions. .. versionadded:: 0.7.0 """ error_template = 'Found usage of a variable marked as unused: {0}' code = 121 PK!uh-wemake_python_styleguide/visitors/__init__.py# -*- coding: utf-8 -*- PK!uh1wemake_python_styleguide/visitors/ast/__init__.py# -*- coding: utf-8 -*- PK!14wemake_python_styleguide/visitors/ast/annotations.py# -*- coding: utf-8 -*- import ast from wemake_python_styleguide.types import AnyFunctionDef, final from wemake_python_styleguide.violations.consistency import ( MultilineFunctionAnnotationViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor from wemake_python_styleguide.visitors.decorators import alias @final @alias('visit_any_function', ( 'visit_FunctionDef', 'visit_AsyncFunctionDef', )) class WrongAnnotationVisitor(BaseNodeVisitor): """Ensures that annotations are used correctly.""" def _check_arg_annotation(self, node: ast.arg) -> None: for sub_node in ast.walk(node): lineno = getattr(sub_node, 'lineno', None) if lineno and lineno != node.lineno: self.add_violation(MultilineFunctionAnnotationViolation(node)) return def _check_return_annotation(self, node: AnyFunctionDef) -> None: if not node.returns: return for sub_node in ast.walk(node.returns): lineno = getattr(sub_node, 'lineno', None) if lineno and lineno != node.returns.lineno: self.add_violation(MultilineFunctionAnnotationViolation(node)) return def visit_any_function(self, node: AnyFunctionDef) -> None: """ Checks return type annotations. Raises: MultilineFunctionAnnotationViolation """ self._check_return_annotation(node) self.generic_visit(node) def visit_arg(self, node: ast.arg) -> None: """ Checks arguments annotations. Raises: MultilineFunctionAnnotationViolation """ self._check_arg_annotation(node) self.generic_visit(node) PK!j 3wemake_python_styleguide/visitors/ast/attributes.py# -*- coding: utf-8 -*- import ast from typing import ClassVar, FrozenSet from wemake_python_styleguide.logics.naming import access from wemake_python_styleguide.types import final from wemake_python_styleguide.violations.best_practices import ( ProtectedAttributeViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor @final class WrongAttributeVisitor(BaseNodeVisitor): """Ensures that attributes are used correctly.""" _allowed_to_use_protected: ClassVar[FrozenSet[str]] = frozenset(( 'self', 'cls', 'mcs', )) def _is_super_called(self, node: ast.Call) -> bool: if isinstance(node.func, ast.Name): if node.func.id == 'super': return True return False def _check_protected_attribute(self, node: ast.Attribute) -> None: if access.is_protected(node.attr): if isinstance(node.value, ast.Name): if node.value.id in self._allowed_to_use_protected: return if isinstance(node.value, ast.Call): if self._is_super_called(node.value): return self.add_violation( ProtectedAttributeViolation(node, text=node.attr), ) def visit_Attribute(self, node: ast.Attribute) -> None: """ Checks the `Attribute` node. Raises: ProtectedAttributeViolation """ self._check_protected_attribute(node) self.generic_visit(node) PK!OEE1wemake_python_styleguide/visitors/ast/builtins.py# -*- coding: utf-8 -*- import ast from collections import Counter from typing import ClassVar, Iterable, List import astor from wemake_python_styleguide import constants from wemake_python_styleguide.logics.operators import ( get_parent_ignoring_unary, unwrap_unary_node, ) from wemake_python_styleguide.types import AnyNodes, final from wemake_python_styleguide.violations.best_practices import ( IncorrectUnpackingViolation, MagicNumberViolation, MultipleAssignmentsViolation, NonUniqueItemsInSetViolation, ) from wemake_python_styleguide.violations.consistency import ( FormattedStringViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor @final class WrongStringVisitor(BaseNodeVisitor): """Restricts to use ``f`` strings.""" def visit_JoinedStr(self, node: ast.JoinedStr) -> None: """ Restricts to use ``f`` strings. Raises: FormattedStringViolation """ self.add_violation(FormattedStringViolation(node)) self.generic_visit(node) @final class MagicNumberVisitor(BaseNodeVisitor): """Checks magic numbers used in the code.""" _allowed_parents: ClassVar[AnyNodes] = ( ast.Assign, # Constructor usages: ast.FunctionDef, ast.AsyncFunctionDef, ast.arguments, # Primitives: ast.List, ast.Dict, ast.Set, ast.Tuple, ) def _check_is_magic(self, node: ast.Num) -> None: parent = get_parent_ignoring_unary(node) if isinstance(parent, self._allowed_parents): return if node.n in constants.MAGIC_NUMBERS_WHITELIST: return if isinstance(node.n, int) and node.n <= constants.NON_MAGIC_MODULO: return self.add_violation(MagicNumberViolation(node, text=str(node.n))) def visit_Num(self, node: ast.Num) -> None: """ Checks numbers not to be magic constants inside the code. Raises: MagicNumberViolation """ self._check_is_magic(node) self.generic_visit(node) @final class WrongAssignmentVisitor(BaseNodeVisitor): """Visits all assign nodes.""" def _check_assign_targets(self, node: ast.Assign) -> None: if len(node.targets) > 1: self.add_violation(MultipleAssignmentsViolation(node)) def _check_unpacking_targets( self, node: ast.AST, targets: Iterable[ast.AST], ) -> None: for target in targets: if isinstance(target, ast.Starred): target = target.value if not isinstance(target, ast.Name): self.add_violation(IncorrectUnpackingViolation(node)) def visit_With(self, node: ast.With) -> None: """ Checks assignments inside context managers to be correct. Raises: IncorrectUnpackingViolation """ for withitem in node.items: if isinstance(withitem.optional_vars, ast.Tuple): self._check_unpacking_targets( node, withitem.optional_vars.elts, ) self.generic_visit(node) def visit_For(self, node: ast.For) -> None: """ Checks assignments inside ``for`` loops to be correct. Raises: IncorrectUnpackingViolation """ if isinstance(node.target, ast.Tuple): self._check_unpacking_targets(node, node.target.elts) self.generic_visit(node) def visit_Assign(self, node: ast.Assign) -> None: """ Checks assignments to be correct. Raises: MultipleAssignmentsViolation IncorrectUnpackingViolation """ self._check_assign_targets(node) if isinstance(node.targets[0], ast.Tuple): self._check_unpacking_targets(node, node.targets[0].elts) self.generic_visit(node) @final class WrongCollectionVisitor(BaseNodeVisitor): """Ensures that collection definitions are correct.""" _elements_in_sets: ClassVar[AnyNodes] = ( ast.Str, ast.Bytes, ast.Num, ast.NameConstant, ast.Name, ) def _report_set_elements(self, node: ast.Set, elements: List[str]) -> None: for element, count in Counter(elements).items(): if count > 1: self.add_violation( NonUniqueItemsInSetViolation(node, text=element), ) def _check_set_elements(self, node: ast.Set) -> None: elements: List[str] = [] for set_item in node.elts: real_set_item = unwrap_unary_node(set_item) if isinstance(real_set_item, self._elements_in_sets): source = astor.to_source(set_item) elements.append(source.strip().strip('(').strip(')')) self._report_set_elements(node, elements) def visit_Set(self, node: ast.Set) -> None: """ Ensures that set literals do not have any duplicate items. Raises: NonUniqueItemsInSetViolation """ self._check_set_elements(node) self.generic_visit(node) PK!g0wemake_python_styleguide/visitors/ast/classes.py# -*- coding: utf-8 -*- import ast from collections import Counter from typing import ClassVar, FrozenSet, List from wemake_python_styleguide import constants, types from wemake_python_styleguide.logics.functions import get_all_arguments from wemake_python_styleguide.logics.nodes import is_contained, is_doc_string from wemake_python_styleguide.violations.best_practices import ( BadMagicMethodViolation, BaseExceptionSubclassViolation, IncorrectBaseClassViolation, IncorrectClassBodyContentViolation, IncorrectSlotsViolation, MethodWithoutArgumentsViolation, StaticMethodViolation, YieldInsideInitViolation, ) from wemake_python_styleguide.violations.consistency import ( ObjectInBaseClassesListViolation, RequiredBaseClassViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor from wemake_python_styleguide.visitors.decorators import alias @types.final class WrongClassVisitor(BaseNodeVisitor): """ This class is responsible for restricting some ``class`` anti-patterns. Here we check for stylistic issues and design patterns. """ _allowed_body_nodes: ClassVar[types.AnyNodes] = ( ast.FunctionDef, # methods ast.AsyncFunctionDef, ast.ClassDef, # we allow some nested classes ast.Assign, # attributes ast.AnnAssign, # type annotations ) _allowed_base_classes_nodes: ClassVar[types.AnyNodes] = ( ast.Name, ast.Attribute, ast.Subscript, ) def _check_base_classes(self, node: ast.ClassDef) -> None: if len(node.bases) == 0: self.add_violation( RequiredBaseClassViolation(node, text=node.name), ) for base_name in node.bases: if not isinstance(base_name, self._allowed_base_classes_nodes): self.add_violation(IncorrectBaseClassViolation(node)) continue id_attr = getattr(base_name, 'id', None) if id_attr == 'BaseException': self.add_violation(BaseExceptionSubclassViolation(node)) elif id_attr == 'object' and len(node.bases) >= 2: self.add_violation( ObjectInBaseClassesListViolation(node, text=id_attr), ) def _check_wrong_body_nodes(self, node: ast.ClassDef) -> None: for sub_node in node.body: if isinstance(sub_node, self._allowed_body_nodes): continue if is_doc_string(sub_node): continue self.add_violation(IncorrectClassBodyContentViolation(sub_node)) def visit_ClassDef(self, node: ast.ClassDef) -> None: """ Checking class definitions. Raises: RequiredBaseClassViolation ObjectInBaseClassesListViolation IncorrectClassBodyContentViolation """ self._check_base_classes(node) self._check_wrong_body_nodes(node) self.generic_visit(node) @types.final @alias('visit_any_function', ( 'visit_FunctionDef', 'visit_AsyncFunctionDef', )) class WrongMethodVisitor(BaseNodeVisitor): """Visits functions, but treats them as methods.""" _staticmethod_names: ClassVar[FrozenSet[str]] = frozenset(( 'staticmethod', )) _not_appropriate_for_init: ClassVar[types.AnyNodes] = ( ast.Yield, ) def visit_any_function(self, node: types.AnyFunctionDef) -> None: """ Checking class methods: async and regular. Raises: StaticMethodViolation BadMagicMethodViolation YieldInsideInitViolation MethodWithoutArgumentsViolation """ self._check_decorators(node) self._check_bound_methods(node) self._check_method_contents(node) self.generic_visit(node) def _check_decorators(self, node: types.AnyFunctionDef) -> None: for decorator in node.decorator_list: decorator_name = getattr(decorator, 'id', None) if decorator_name in self._staticmethod_names: self.add_violation(StaticMethodViolation(node)) def _check_bound_methods(self, node: types.AnyFunctionDef) -> None: node_context = getattr(node, 'wps_context', None) if not isinstance(node_context, ast.ClassDef): return if len(get_all_arguments(node)) == 0: self.add_violation( MethodWithoutArgumentsViolation(node, text=node.name), ) if node.name in constants.MAGIC_METHODS_BLACKLIST: self.add_violation(BadMagicMethodViolation(node, text=node.name)) def _check_method_contents(self, node: types.AnyFunctionDef) -> None: if node.name == constants.INIT: if is_contained(node, self._not_appropriate_for_init): self.add_violation(YieldInsideInitViolation(node)) @types.final class WrongSlotsVisitor(BaseNodeVisitor): """Visits class attributes.""" _blacklisted_slots_nodes: ClassVar[types.AnyNodes] = ( ast.Dict, ast.List, ast.Set, ) def visit_Assign(self, node: ast.Assign) -> None: """ Checks all assigns that have correct context. Raises: IncorrectSlotsViolation """ context = getattr(node, 'wps_context', None) if isinstance(context, ast.ClassDef): self._check_slots(node) self.generic_visit(node) def _contains_slots_assign(self, node: ast.Assign) -> bool: for target in node.targets: if isinstance(target, ast.Name) and target.id == '__slots__': return True return False def _count_slots_items( self, node: ast.Assign, elements: ast.Tuple, ) -> None: fields: List[str] = [] for tuple_item in elements.elts: if not isinstance(tuple_item, ast.Str): self.add_violation(IncorrectSlotsViolation(node)) return fields.append(tuple_item.s) for _, counter in Counter(fields).items(): if counter > 1: self.add_violation(IncorrectSlotsViolation(node)) return def _check_slots(self, node: ast.Assign) -> None: if not self._contains_slots_assign(node): return if isinstance(node.value, self._blacklisted_slots_nodes): self.add_violation(IncorrectSlotsViolation(node)) return if isinstance(node.value, ast.Tuple): self._count_slots_items(node, node.value) PK!J4wemake_python_styleguide/visitors/ast/comparisons.py# -*- coding: utf-8 -*- import ast from typing import ClassVar, List, Optional, Sequence import astor from wemake_python_styleguide.logics.naming.name_nodes import is_same_variable from wemake_python_styleguide.logics.nodes import is_literal from wemake_python_styleguide.logics.operators import unwrap_unary_node from wemake_python_styleguide.types import AnyIf, AnyNodes, final from wemake_python_styleguide.violations.best_practices import ( SimplifiableIfViolation, ) from wemake_python_styleguide.violations.consistency import ( ComparisonOrderViolation, ConstantComparisonViolation, MultipleInComparisonViolation, RedundantComparisonViolation, WrongConditionalViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor from wemake_python_styleguide.visitors.decorators import alias @final class ComparisonSanityVisitor(BaseNodeVisitor): """Restricts the comparison of literals.""" def _has_multiple_in_comparisons(self, node: ast.Compare) -> bool: count = 0 for op in node.ops: if isinstance(op, ast.In): count += 1 return count > 1 def _check_literal_compare(self, node: ast.Compare) -> None: last_was_literal = is_literal(node.left) for comparator in node.comparators: next_is_literal = is_literal(comparator) if last_was_literal and next_is_literal: self.add_violation(ConstantComparisonViolation(node)) break last_was_literal = next_is_literal def _check_redundant_compare(self, node: ast.Compare) -> None: last_variable = node.left for next_variable in node.comparators: if is_same_variable(last_variable, next_variable): self.add_violation(RedundantComparisonViolation(node)) break last_variable = next_variable def _check_multiple_in_comparisons(self, node: ast.Compare) -> None: if self._has_multiple_in_comparisons(node): self.add_violation(MultipleInComparisonViolation(node)) def visit_Compare(self, node: ast.Compare) -> None: """ Ensures that compares are written correctly. Raises: ConstantComparisonViolation MultipleInComparisonViolation RedundantComparisonViolation """ self._check_literal_compare(node) self._check_redundant_compare(node) self._check_multiple_in_comparisons(node) self.generic_visit(node) @final class WrongComparisionOrderVisitor(BaseNodeVisitor): """Restricts comparision where argument doesn't come first.""" _allowed_left_nodes: ClassVar[AnyNodes] = ( ast.Name, ast.Call, ast.Attribute, ) _special_cases: ClassVar[AnyNodes] = ( ast.In, ast.NotIn, ) def _is_special_case(self, node: ast.Compare) -> bool: """ Operators ``in`` and ``not in`` are special cases. Why? Because it is perfectly fine to use something like: ``if 'key' in some_dict: ...`` This should not be an issue. When there are multiple special operators it is still a separate issue. """ return isinstance(node.ops[0], self._special_cases) def _is_left_node_valid(self, left: ast.AST) -> bool: if isinstance(left, self._allowed_left_nodes): return True if isinstance(left, ast.BinOp): left_node = self._is_left_node_valid(left.left) right_node = self._is_left_node_valid(left.right) return left_node or right_node return False def _has_wrong_nodes_on_the_right( self, comparators: Sequence[ast.AST], ) -> bool: for right in comparators: if isinstance(right, self._allowed_left_nodes): return True if isinstance(right, ast.BinOp): return self._has_wrong_nodes_on_the_right([ right.left, right.right, ]) return False def _check_ordering(self, node: ast.Compare) -> None: if self._is_left_node_valid(node.left): return if self._is_special_case(node): return if len(node.comparators) > 1: return if not self._has_wrong_nodes_on_the_right(node.comparators): return self.add_violation(ComparisonOrderViolation(node)) def visit_Compare(self, node: ast.Compare) -> None: """ Forbids comparision where argument doesn't come first. Raises: ComparisonOrderViolation """ self._check_ordering(node) self.generic_visit(node) @alias('visit_any_if', ( 'visit_If', 'visit_IfExp', )) class WrongConditionalVisitor(BaseNodeVisitor): """Finds wrong conditional arguments.""" _forbidden_nodes: ClassVar[AnyNodes] = ( # Constants: ast.Num, ast.Str, ast.Bytes, ast.NameConstant, # Collections: ast.List, ast.Set, ast.Dict, ast.Tuple, ) def visit_any_if(self, node: AnyIf) -> None: """ Ensures that if statements are using valid conditionals. Raises: WrongConditionalViolation """ if isinstance(node, ast.If): self._check_simplifiable_if(node) else: self._check_simplifiable_ifexpr(node) self._check_if_statement_conditional(node) self.generic_visit(node) def _is_simplifiable_assign( self, node_body: List[ast.stmt], ) -> Optional[str]: wrong_length = len(node_body) != 1 if wrong_length or not isinstance(node_body[0], ast.Assign): return None if len(node_body[0].targets) != 1: return None if not isinstance(node_body[0].value, ast.NameConstant): return None if node_body[0].value.value is None: return None return astor.to_source(node_body[0].targets[0]).strip() def _check_if_statement_conditional(self, node: AnyIf) -> None: real_node = unwrap_unary_node(node.test) if isinstance(real_node, self._forbidden_nodes): self.add_violation(WrongConditionalViolation(node)) def _check_simplifiable_if(self, node: ast.If) -> None: chain = getattr(node, 'wps_chain', None) chained = getattr(node, 'wps_chained', None) if chain is None and chained is None: body_var = self._is_simplifiable_assign(node.body) else_var = self._is_simplifiable_assign(node.orelse) if body_var and body_var == else_var: self.add_violation(SimplifiableIfViolation(node)) def _check_simplifiable_ifexpr(self, node: ast.IfExp) -> None: conditions = set() if isinstance(node.body, ast.NameConstant): conditions.add(node.body.value) if isinstance(node.orelse, ast.NameConstant): conditions.add(node.orelse.value) if conditions == {True, False}: self.add_violation(SimplifiableIfViolation(node)) PK!uh<wemake_python_styleguide/visitors/ast/complexity/__init__.py# -*- coding: utf-8 -*- PK!39  ;wemake_python_styleguide/visitors/ast/complexity/classes.py# -*- coding: utf-8 -*- import ast from wemake_python_styleguide.violations.complexity import ( TooManyBaseClassesViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor class ClassComplexityVisitor(BaseNodeVisitor): """Checks class complexity.""" def _check_base_classes(self, node: ast.ClassDef) -> None: if len(node.bases) > self.options.max_base_classes: self.add_violation( TooManyBaseClassesViolation(node, text=str(len(node.bases))), ) def visit_ClassDef(self, node: ast.ClassDef) -> None: """ Checking class definitions. Raises: TooManyBaseClassesViolation """ self._check_base_classes(node) self.generic_visit(node) PK! >:wemake_python_styleguide/visitors/ast/complexity/counts.py# -*- coding: utf-8 -*- import ast from collections import defaultdict from typing import ClassVar, DefaultDict, List, Union from wemake_python_styleguide.logics.functions import is_method from wemake_python_styleguide.logics.nodes import get_parent from wemake_python_styleguide.types import AnyFunctionDef, AnyImport, final from wemake_python_styleguide.violations.complexity import ( TooManyConditionsViolation, TooManyDecoratorsViolation, TooManyElifsViolation, TooManyExceptCasesViolation, TooManyImportsViolation, TooManyMethodsViolation, TooManyModuleMembersViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor from wemake_python_styleguide.visitors.decorators import alias ConditionNodes = Union[ast.If, ast.While, ast.IfExp] ModuleMembers = Union[ast.AsyncFunctionDef, ast.FunctionDef, ast.ClassDef] @final @alias('visit_module_members', ( 'visit_ClassDef', 'visit_AsyncFunctionDef', 'visit_FunctionDef', )) class ModuleMembersVisitor(BaseNodeVisitor): """Counts classes and functions in a module.""" def __init__(self, *args, **kwargs) -> None: """Creates a counter for tracked metrics.""" super().__init__(*args, **kwargs) self._public_items_count = 0 def _check_members_count(self, node: ModuleMembers) -> None: """This method increases the number of module members.""" is_real_method = is_method(getattr(node, 'function_type', None)) if isinstance(get_parent(node), ast.Module) and not is_real_method: self._public_items_count += 1 def _check_decorators_count(self, node: ModuleMembers) -> None: number_of_decorators = len(node.decorator_list) if number_of_decorators > self.options.max_decorators: self.add_violation( TooManyDecoratorsViolation( node, text=str(number_of_decorators), ), ) def _post_visit(self) -> None: if self._public_items_count > self.options.max_module_members: self.add_violation( TooManyModuleMembersViolation( text=str(self._public_items_count), ), ) def visit_module_members(self, node: ModuleMembers) -> None: """ Counts the number of ModuleMembers in a single module. Raises: TooManyModuleMembersViolation """ self._check_decorators_count(node) self._check_members_count(node) self.generic_visit(node) @final @alias('visit_any_import', ( 'visit_ImportFrom', 'visit_Import', )) class ImportMembersVisitor(BaseNodeVisitor): """Counts imports in a module.""" def __init__(self, *args, **kwargs) -> None: """Creates a counter for tracked metrics.""" super().__init__(*args, **kwargs) self._imports_count = 0 def _post_visit(self) -> None: if self._imports_count > self.options.max_imports: self.add_violation( TooManyImportsViolation(text=str(self._imports_count)), ) def visit_any_import(self, node: AnyImport) -> None: """ Counts the number of ``import`` and ``from ... import ...``. Raises: TooManyImportsViolation """ self._imports_count += 1 self.generic_visit(node) @final @alias('visit_any_function', ( 'visit_FunctionDef', 'visit_AsyncFunctionDef', )) class MethodMembersVisitor(BaseNodeVisitor): """Counts methods in a single class.""" def __init__(self, *args, **kwargs) -> None: """Creates a counter for tracked methods in different classes.""" super().__init__(*args, **kwargs) self._methods: DefaultDict[ast.ClassDef, int] = defaultdict(int) def _check_method(self, node: AnyFunctionDef) -> None: parent = get_parent(node) if isinstance(parent, ast.ClassDef): self._methods[parent] += 1 def _post_visit(self) -> None: for node, count in self._methods.items(): if count > self.options.max_methods: self.add_violation( TooManyMethodsViolation(node, text=str(count)), ) def visit_any_function(self, node: AnyFunctionDef) -> None: """ Counts the number of methods in a single class. Raises: TooManyMethodsViolation """ self._check_method(node) self.generic_visit(node) @final class ConditionsVisitor(BaseNodeVisitor): """Checks booleans for condition counts.""" #: Maximum number of conditions in a single ``if`` or ``while`` statement. _max_conditions: ClassVar[int] = 4 def _count_conditions(self, node: ast.BoolOp) -> int: counter = 0 for condition in node.values: if isinstance(condition, ast.BoolOp): counter += self._count_conditions(condition) else: counter += 1 return counter def _check_conditions(self, node: ast.BoolOp) -> None: conditions_count = self._count_conditions(node) if conditions_count > self._max_conditions: self.add_violation( TooManyConditionsViolation(node, text=str(conditions_count)), ) def visit_BoolOp(self, node: ast.BoolOp) -> None: """ Counts the number of conditions. Raises: TooManyConditionsViolation """ self._check_conditions(node) self.generic_visit(node) @final class ElifVisitor(BaseNodeVisitor): """Checks the number of ``elif`` cases inside conditions.""" #: Maximum number of `elif` blocks in a single `if` condition: _max_elifs: ClassVar[int] = 3 def __init__(self, *args, **kwargs) -> None: """Creates internal ``elif`` counter.""" super().__init__(*args, **kwargs) self._if_children: DefaultDict[ast.If, List[ast.If]] = defaultdict(list) def _get_root_if_node(self, node: ast.If) -> ast.If: for root, children in self._if_children.items(): if node in children: return root return node def _update_if_child(self, root: ast.If, node: ast.If) -> None: if node is not root: self._if_children[root].append(node) self._if_children[root].extend(node.orelse) # type: ignore def _check_elifs(self, node: ast.If) -> None: has_elif = all( isinstance(if_node, ast.If) for if_node in node.orelse ) if has_elif: root = self._get_root_if_node(node) self._update_if_child(root, node) def _post_visit(self): for root, children in self._if_children.items(): real_children_length = len(set(children)) if real_children_length > self._max_elifs: self.add_violation( TooManyElifsViolation(root, text=str(real_children_length)), ) def visit_If(self, node: ast.If) -> None: """ Checks condition not to reimplement switch. Raises: TooManyElifsViolation """ self._check_elifs(node) self.generic_visit(node) @final class TryExceptVisitor(BaseNodeVisitor): """Visits all try/except nodes to ensure that they are not too complex.""" #: Maximum number of ``except`` cases in a single ``try`` clause. _max_except_cases: ClassVar[int] = 3 def _check_except_count(self, node: ast.Try) -> None: if len(node.handlers) > self._max_except_cases: self.add_violation(TooManyExceptCasesViolation(node)) def visit_Try(self, node: ast.Try) -> None: """ Ensures that try/except is correct. Raises: TooManyExceptCasesViolation """ self._check_except_count(node) self.generic_visit(node) PK!k<wemake_python_styleguide/visitors/ast/complexity/function.py# -*- coding: utf-8 -*- import ast from collections import defaultdict from typing import ClassVar, DefaultDict, List from wemake_python_styleguide.constants import UNUSED_VARIABLE from wemake_python_styleguide.logics import functions from wemake_python_styleguide.logics.nodes import get_parent from wemake_python_styleguide.types import ( AnyFunctionDef, AnyFunctionDefAndLambda, AnyNodes, final, ) from wemake_python_styleguide.violations.complexity import ( TooManyArgumentsViolation, TooManyExpressionsViolation, TooManyLocalsViolation, TooManyReturnsViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor from wemake_python_styleguide.visitors.decorators import alias FunctionCounter = DefaultDict[AnyFunctionDef, int] FunctionCounterWithLambda = DefaultDict[AnyFunctionDefAndLambda, int] @final class _ComplexityCounter(object): """Helper class to encapsulate logic from the visitor.""" _not_contain_locals: ClassVar[AnyNodes] = ( ast.comprehension, ) def __init__(self) -> None: self.arguments: FunctionCounterWithLambda = defaultdict(int) self.returns: FunctionCounter = defaultdict(int) self.expressions: FunctionCounter = defaultdict(int) self.variables: DefaultDict[ AnyFunctionDef, List[str], ] = defaultdict(list) def _update_variables( self, function: AnyFunctionDef, variable_def: ast.Name, ) -> None: """ Increases the counter of local variables. What is treated as a local variable? Check ``TooManyLocalsViolation`` documentation. """ function_variables = self.variables[function] if variable_def.id not in function_variables: if variable_def.id == UNUSED_VARIABLE: return if isinstance(get_parent(variable_def), self._not_contain_locals): return function_variables.append(variable_def.id) def _check_sub_node(self, node: AnyFunctionDef, sub_node) -> None: is_variable = isinstance(sub_node, ast.Name) context = getattr(sub_node, 'ctx', None) if is_variable and isinstance(context, ast.Store): self._update_variables(node, sub_node) elif isinstance(sub_node, ast.Return): self.returns[node] += 1 elif isinstance(sub_node, ast.Expr): self.expressions[node] += 1 def check_arguments_count(self, node: AnyFunctionDefAndLambda) -> None: """Checks the number of the arguments in a function.""" self.arguments[node] = len(functions.get_all_arguments(node)) def check_function_complexity(self, node: AnyFunctionDef) -> None: """ In this function we iterate all the internal body's node. We check different complexity metrics based on these internals. """ for body_item in node.body: for sub_node in ast.walk(body_item): self._check_sub_node(node, sub_node) @final @alias('visit_any_function', ( 'visit_AsyncFunctionDef', 'visit_FunctionDef', )) class FunctionComplexityVisitor(BaseNodeVisitor): """ This class checks for complexity inside functions. This includes: 1. Number of arguments 2. Number of `return` statements 3. Number of expressions 4. Number of local variables """ def __init__(self, *args, **kwargs) -> None: """Creates a counter for tracked metrics.""" super().__init__(*args, **kwargs) self._counter = _ComplexityCounter() def _check_function_internals(self) -> None: for node, variables in self._counter.variables.items(): if len(variables) > self.options.max_local_variables: self.add_violation( TooManyLocalsViolation(node, text=str(len(variables))), ) for node, expressions in self._counter.expressions.items(): if expressions > self.options.max_expressions: self.add_violation( TooManyExpressionsViolation(node, text=str(expressions)), ) def _check_function_signature(self) -> None: for node, arguments in self._counter.arguments.items(): if arguments > self.options.max_arguments: self.add_violation( TooManyArgumentsViolation(node, text=str(arguments)), ) for node, returns in self._counter.returns.items(): if returns > self.options.max_returns: self.add_violation( TooManyReturnsViolation(node, text=str(returns)), ) def _post_visit(self) -> None: self._check_function_signature() self._check_function_internals() def visit_any_function(self, node: AnyFunctionDef) -> None: """ Checks function's internal complexity. Raises: TooManyExpressionsViolation TooManyReturnsViolation TooManyLocalsViolation TooManyArgumentsViolation """ self._counter.check_arguments_count(node) self._counter.check_function_complexity(node) self.generic_visit(node) def visit_Lambda(self, node: ast.Lambda) -> None: """ Checks lambda function's internal complexity. Raises: TooManyArgumentsViolation """ self._counter.check_arguments_count(node) self.generic_visit(node) PK!HZ| 9wemake_python_styleguide/visitors/ast/complexity/jones.py# -*- coding: utf-8 -*- """ Jones Complexity to count inline complexity. Based on the original `jones-complexity` project: https://github.com/Miserlou/JonesComplexity Original project is licensed under MIT. """ import ast from collections import defaultdict from statistics import median from typing import DefaultDict, List from wemake_python_styleguide.types import final from wemake_python_styleguide.violations.complexity import ( JonesScoreViolation, LineComplexityViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor @final class JonesComplexityVisitor(BaseNodeVisitor): """ This visitor is used to find complex lines in the code. Calculates the number of AST nodes per line of code. Also calculates the median nodes/line score. Then compares these numbers to the given tressholds. Some nodes are ignored because there's no sense in analyzing them. Some nodes like type annotations are not affecting line complexity, so we do not count them. """ _ignored_nodes = ( ast.FunctionDef, ast.ClassDef, ast.AsyncFunctionDef, ) def __init__(self, *args, **kwargs) -> None: """Initializes line number counter.""" super().__init__(*args, **kwargs) self._lines: DefaultDict[int, List[ast.AST]] = defaultdict(list) self._to_ignore: List[ast.AST] = [] def _post_visit(self) -> None: """ Triggers after the whole module was processed. Checks each line for its complexity, compares it to the tresshold. We also calculate the final Jones score for the whole module. """ for line_nodes in self._lines.values(): complexity = len(line_nodes) if complexity > self.options.max_line_complexity: self.add_violation(LineComplexityViolation( line_nodes[0], text=str(complexity), )) node_counts = [len(nodes) for nodes in self._lines.values()] total_count = median(node_counts) if node_counts else 0 if total_count > self.options.max_jones_score: self.add_violation(JonesScoreViolation(text=str(total_count))) def _maybe_ignore_child(self, node: ast.AST) -> bool: if isinstance(node, ast.AnnAssign): self._to_ignore.append(node.annotation) return node in self._to_ignore def visit(self, node: ast.AST) -> None: """ Visits all nodes, sums the number of nodes per line. Then calculates the median value of all line results. Raises: JonesScoreViolation LineComplexityViolation """ line_number = getattr(node, 'lineno', None) is_ignored = isinstance(node, self._ignored_nodes) if line_number is not None and not is_ignored: if not self._maybe_ignore_child(node): self._lines[line_number].append(node) self.generic_visit(node) PK!k :wemake_python_styleguide/visitors/ast/complexity/nested.py# -*- coding: utf-8 -*- import ast from typing import ClassVar from wemake_python_styleguide.constants import ( NESTED_CLASSES_WHITELIST, NESTED_FUNCTIONS_WHITELIST, ) from wemake_python_styleguide.logics.nodes import get_parent from wemake_python_styleguide.types import AnyFunctionDef, AnyNodes, final from wemake_python_styleguide.violations.best_practices import ( NestedClassViolation, NestedFunctionViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor from wemake_python_styleguide.visitors.decorators import alias @final @alias('visit_any_function', ( 'visit_FunctionDef', 'visit_AsyncFunctionDef', )) class NestedComplexityVisitor(BaseNodeVisitor): """ Checks that structures are not nested. We disallow to use nested functions and nested classes. Because flat is better than nested. We allow to nest function inside classes, that's called methods. """ _function_nodes: ClassVar[AnyNodes] = ( ast.FunctionDef, ast.AsyncFunctionDef, ) def _check_nested_function(self, node: AnyFunctionDef) -> None: is_inside_function = isinstance(get_parent(node), self._function_nodes) if is_inside_function and node.name not in NESTED_FUNCTIONS_WHITELIST: self.add_violation(NestedFunctionViolation(node, text=node.name)) def _check_nested_classes(self, node: ast.ClassDef) -> None: parent = get_parent(node) is_inside_class = isinstance(parent, ast.ClassDef) is_inside_function = isinstance(parent, self._function_nodes) if is_inside_class and node.name not in NESTED_CLASSES_WHITELIST: self.add_violation(NestedClassViolation(node, text=node.name)) elif is_inside_function: self.add_violation(NestedClassViolation(node, text=node.name)) def _check_nested_lambdas(self, node: ast.Lambda) -> None: if isinstance(get_parent(node), ast.Lambda): self.add_violation(NestedFunctionViolation(node, text='lambda')) def visit_ClassDef(self, node: ast.ClassDef) -> None: """ Used to find nested classes in other classes and functions. Uses ``NESTED_CLASSES_WHITELIST`` to respect some nested classes. Raises: NestedClassViolation """ self._check_nested_classes(node) self.generic_visit(node) def visit_any_function(self, node: AnyFunctionDef) -> None: """ Used to find nested functions. Uses ``NESTED_FUNCTIONS_WHITELIST`` to respect some nested functions. Raises: NestedFunctionViolation """ self._check_nested_function(node) self.generic_visit(node) def visit_Lambda(self, node: ast.Lambda) -> None: """ Used to find nested ``lambda`` functions. Raises: NestedFunctionViolation """ self._check_nested_lambdas(node) self.generic_visit(node) PK!q:wemake_python_styleguide/visitors/ast/complexity/offset.py# -*- coding: utf-8 -*- import ast from typing import ClassVar from wemake_python_styleguide.types import final from wemake_python_styleguide.violations.complexity import ( TooDeepNestingViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor from wemake_python_styleguide.visitors.decorators import alias @final @alias('visit_line_expression', ( 'visit_Try', 'visit_ExceptHandler', 'visit_For', 'visit_With', 'visit_While', 'visit_If', 'visit_Raise', 'visit_Return', 'visit_Continue', 'visit_Break', 'visit_Assign', 'visit_Expr', 'visit_Pass', 'visit_ClassDef', 'visit_FunctionDef', 'visit_AsyncFor', 'visit_AsyncWith', 'visit_AsyncFunctionDef', )) class OffsetVisitor(BaseNodeVisitor): """Checks offset values for several nodes.""" #: Maximum number of blocks to nest different structures: _max_offset_blocks: ClassVar[int] = 5 def _check_offset(self, node: ast.AST) -> None: offset = getattr(node, 'col_offset', 0) if offset > self._max_offset_blocks * 4: self.add_violation(TooDeepNestingViolation(node, text=str(offset))) def visit_line_expression(self, node: ast.AST) -> None: """ Checks statement's offset. We check only several nodes, because other nodes might have different offsets, which is fine. For example, ``ast.Name`` node has inline offset, which can take values from ``0`` to ``~80``. But ``Name`` node is allowed to behave like so. So, we only check nodes that represent "all liners". Raises: TooDeepNestingViolation """ self._check_offset(node) self.generic_visit(node) PK!13wemake_python_styleguide/visitors/ast/conditions.py# -*- coding: utf-8 -*- import ast from typing import ClassVar from wemake_python_styleguide.types import AnyNodes, final from wemake_python_styleguide.violations.best_practices import ( RedundantReturningElseViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor @final class IfStatementVisitor(BaseNodeVisitor): """Checks single and consecutive ``if`` statement nodes.""" #: Nodes that break or return the execution flow. _returning_nodes: ClassVar[AnyNodes] = ( ast.Break, ast.Raise, ast.Return, ) def _check_redundant_else(self, node: ast.If) -> None: if not node.orelse: return next_chain = getattr(node, 'wps_chain', None) # TODO: move into utils has_previous_chain = getattr(node, 'wps_chained', None) if next_chain or has_previous_chain: return if any(isinstance(line, self._returning_nodes) for line in node.body): self.add_violation(RedundantReturningElseViolation(node)) def visit_If(self, node: ast.If) -> None: """ Checks ``if`` nodes. Raises: RedundantReturningElseViolation """ self._check_redundant_else(node) self.generic_visit(node) PK!8`002wemake_python_styleguide/visitors/ast/functions.py# -*- coding: utf-8 -*- import ast from typing import Dict, List, Optional, Union from wemake_python_styleguide.constants import ( FUNCTIONS_BLACKLIST, UNUSED_VARIABLE, ) from wemake_python_styleguide.logics import functions from wemake_python_styleguide.logics.naming import access from wemake_python_styleguide.types import AnyFunctionDef, final from wemake_python_styleguide.violations.best_practices import ( BooleanPositionalArgumentViolation, IncorrectSuperCallViolation, WrongFunctionCallViolation, ) from wemake_python_styleguide.violations.naming import ( UnusedVariableIsUsedViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor from wemake_python_styleguide.visitors.decorators import alias LocalVariable = Union[ast.Name, ast.ExceptHandler] @final class WrongFunctionCallVisitor(BaseNodeVisitor): """ Responsible for restricting some dangerous function calls. All these functions are defined in ``FUNCTIONS_BLACKLIST``. """ def _check_wrong_function_called(self, node: ast.Call) -> None: function_name = functions.given_function_called( node, FUNCTIONS_BLACKLIST, ) if function_name: self.add_violation( WrongFunctionCallViolation(node, text=function_name), ) def _check_boolean_arguments(self, node: ast.Call) -> None: for arg in node.args: if isinstance(arg, ast.NameConstant): # We do not check for `None` values here: if arg.value is True or arg.value is False: self.add_violation( BooleanPositionalArgumentViolation( arg, text=str(arg.value), ), ) def _ensure_super_context(self, node: ast.Call) -> None: parent_context = getattr(node, 'wps_context', None) if isinstance(parent_context, (ast.FunctionDef, ast.AsyncFunctionDef)): grand_context = getattr(parent_context, 'wps_context', None) if isinstance(grand_context, ast.ClassDef): return self.add_violation( IncorrectSuperCallViolation(node, text='not inside method'), ) def _ensure_super_arguments(self, node: ast.Call) -> None: if len(node.args) > 0 or len(node.keywords) > 0: self.add_violation( IncorrectSuperCallViolation(node, text='remove arguments'), ) def _check_super_call(self, node: ast.Call) -> None: function_name = functions.given_function_called(node, ['super']) if function_name: self._ensure_super_context(node) self._ensure_super_arguments(node) def visit_Call(self, node: ast.Call) -> None: """ Used to find ``FUNCTIONS_BLACKLIST`` calls. Raises: BooleanPositionalArgumentViolation WrongFunctionCallViolation IncorrectSuperCallViolation """ self._check_wrong_function_called(node) self._check_boolean_arguments(node) self._check_super_call(node) self.generic_visit(node) @final @alias('visit_any_function', ( 'visit_AsyncFunctionDef', 'visit_FunctionDef', )) class FunctionDefinitionVisitor(BaseNodeVisitor): """Responsible for checking function internals.""" def _check_used_variables( self, local_variables: Dict[str, List[LocalVariable]], ) -> None: for varname, usages in local_variables.items(): for node in usages: if access.is_protected(varname) or varname == UNUSED_VARIABLE: self.add_violation( UnusedVariableIsUsedViolation(node, text=varname), ) def _maybe_update_variable( self, sub_node: LocalVariable, var_name: str, local_variables: Dict[str, List[LocalVariable]], ) -> None: if var_name in local_variables: local_variables[var_name].append(sub_node) return is_name_def = isinstance( sub_node, ast.Name, ) and isinstance( sub_node.ctx, ast.Store, ) if is_name_def or isinstance(sub_node, ast.ExceptHandler): local_variables[var_name] = [] def _get_variable_name(self, node: LocalVariable) -> Optional[str]: if isinstance(node, ast.Name): return node.id return getattr(node, 'name', None) def _check_unused_variables(self, node: AnyFunctionDef) -> None: local_variables: Dict[str, List[LocalVariable]] = {} for body_item in node.body: for sub_node in ast.walk(body_item): if not isinstance(sub_node, (ast.Name, ast.ExceptHandler)): continue var_name = self._get_variable_name(sub_node) if not var_name: continue self._maybe_update_variable( sub_node, var_name, local_variables, ) self._check_used_variables(local_variables) def visit_any_function(self, node: AnyFunctionDef) -> None: """ Checks regular, lambda, and async functions. Raises: UnusedVariableIsUsedViolation """ self._check_unused_variables(node) self.generic_visit(node) PK!e0wemake_python_styleguide/visitors/ast/imports.py# -*- coding: utf-8 -*- import ast from itertools import chain from typing import Callable from wemake_python_styleguide.constants import FUTURE_IMPORTS_WHITELIST from wemake_python_styleguide.logics import imports, nodes from wemake_python_styleguide.logics.naming import access from wemake_python_styleguide.types import AnyImport, final from wemake_python_styleguide.violations.base import BaseViolation from wemake_python_styleguide.violations.best_practices import ( FutureImportViolation, NestedImportViolation, ProtectedModuleViolation, ) from wemake_python_styleguide.violations.consistency import ( DottedRawImportViolation, LocalFolderImportViolation, ) from wemake_python_styleguide.violations.naming import SameAliasImportViolation from wemake_python_styleguide.visitors.base import BaseNodeVisitor ErrorCallback = Callable[[BaseViolation], None] # TODO: alias and move @final class _ImportsValidator(object): """Utility class to separate logic from the visitor.""" def __init__(self, error_callback: ErrorCallback) -> None: self._error_callback = error_callback def check_nested_import(self, node: AnyImport) -> None: parent = nodes.get_parent(node) if parent is not None and not isinstance(parent, ast.Module): self._error_callback(NestedImportViolation(node)) def check_local_import(self, node: ast.ImportFrom) -> None: if node.level != 0: self._error_callback(LocalFolderImportViolation(node)) def check_future_import(self, node: ast.ImportFrom) -> None: if node.module == '__future__': for alias in node.names: if alias.name not in FUTURE_IMPORTS_WHITELIST: self._error_callback( FutureImportViolation(node, text=alias.name), ) def check_dotted_raw_import(self, node: ast.Import) -> None: for alias in node.names: if '.' in alias.name: self._error_callback( DottedRawImportViolation(node, text=alias.name), ) def check_alias(self, node: AnyImport) -> None: for alias in node.names: if alias.asname == alias.name: self._error_callback( SameAliasImportViolation(node, text=alias.name), ) def check_protected_import(self, node: AnyImport) -> None: import_names = [alias.name for alias in node.names] for name in chain(imports.get_import_parts(node), import_names): if access.is_protected(name): self._error_callback(ProtectedModuleViolation(node)) @final class WrongImportVisitor(BaseNodeVisitor): """Responsible for finding wrong imports.""" def __init__(self, *args, **kwargs) -> None: """Creates a checker for tracked violations.""" super().__init__(*args, **kwargs) self._validator = _ImportsValidator(self.add_violation) def visit_Import(self, node: ast.Import) -> None: """ Used to find wrong ``import`` statements. Raises: SameAliasImportViolation DottedRawImportViolation NestedImportViolation """ self._validator.check_nested_import(node) self._validator.check_dotted_raw_import(node) self._validator.check_alias(node) self._validator.check_protected_import(node) self.generic_visit(node) def visit_ImportFrom(self, node: ast.ImportFrom) -> None: """ Used to find wrong ``from ... import ...`` statements. Raises: SameAliasImportViolation NestedImportViolation LocalFolderImportViolation FutureImportViolation """ self._validator.check_local_import(node) self._validator.check_nested_import(node) self._validator.check_future_import(node) self._validator.check_alias(node) self._validator.check_protected_import(node) self.generic_visit(node) PK!F""1wemake_python_styleguide/visitors/ast/keywords.py# -*- coding: utf-8 -*- import ast from collections import Counter from typing import ClassVar, List, Type, Union import astor from wemake_python_styleguide.logics.nodes import get_parent, is_contained from wemake_python_styleguide.types import AnyFunctionDef, AnyNodes, final from wemake_python_styleguide.violations.best_practices import ( BaseExceptionViolation, DuplicateExceptionViolation, RaiseNotImplementedViolation, RedundantFinallyViolation, TryExceptMultipleReturnPathViolation, WrongKeywordViolation, ) from wemake_python_styleguide.violations.consistency import ( InconsistentReturnViolation, InconsistentYieldViolation, MultipleContextManagerAssignmentsViolation, UselessExceptCaseViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor from wemake_python_styleguide.visitors.decorators import alias AnyWith = Union[ast.With, ast.AsyncWith] ReturningViolations = Union[ Type[InconsistentReturnViolation], Type[InconsistentYieldViolation], ] @final class WrongRaiseVisitor(BaseNodeVisitor): """Finds wrong ``raise`` keywords.""" def _check_exception_type(self, node: ast.Raise) -> None: exception = getattr(node, 'exc', None) if exception is None: return exception_func = getattr(exception, 'func', None) if exception_func: exception = exception_func exception_name = getattr(exception, 'id', None) if exception_name == 'NotImplemented': self.add_violation(RaiseNotImplementedViolation(node)) def visit_Raise(self, node: ast.Raise) -> None: """ Checks how ``raise`` keyword is used. Raises: RaiseNotImplementedViolation """ self._check_exception_type(node) self.generic_visit(node) @final @alias('visit_any_function', ( 'visit_FunctionDef', 'visit_AsyncFunctionDef', )) class ConsistentReturningVisitor(BaseNodeVisitor): """Finds incorrect and inconsistent ``return`` and ``yield`` nodes.""" def _check_last_return_in_function(self, node: ast.Return) -> None: parent = get_parent(node) if not isinstance(parent, (ast.FunctionDef, ast.AsyncFunctionDef)): return if node is parent.body[-1] and node.value is None: self.add_violation(InconsistentReturnViolation(node)) def _iterate_returning_values( self, node: AnyFunctionDef, returning_type, # mypy is not ok with this type declaration violation: ReturningViolations, ): returns: List[ast.Return] = [] has_values = False for sub_node in ast.walk(node): if isinstance(sub_node, returning_type): if sub_node.value: has_values = True returns.append(sub_node) for sub_node in returns: if not sub_node.value and has_values: self.add_violation(violation(sub_node)) def _check_return_values(self, node: AnyFunctionDef) -> None: self._iterate_returning_values( node, ast.Return, InconsistentReturnViolation, ) def _check_yield_values(self, node: AnyFunctionDef) -> None: self._iterate_returning_values( node, ast.Yield, InconsistentYieldViolation, ) def visit_Return(self, node: ast.Return) -> None: """ Checks ``return`` statements for consistency. Raises: InconsistentReturnViolation """ self._check_last_return_in_function(node) self.generic_visit(node) def visit_any_function(self, node: AnyFunctionDef) -> None: """ Helper to get all ``return`` and ``yield`` nodes in a function at once. Raises: InconsistentReturnViolation InconsistentYieldViolation """ self._check_return_values(node) self._check_yield_values(node) self.generic_visit(node) @final class WrongKeywordVisitor(BaseNodeVisitor): """Finds wrong keywords.""" _forbidden_keywords: ClassVar[AnyNodes] = ( ast.Pass, ast.Delete, ast.Global, ast.Nonlocal, ) def _check_keyword(self, node: ast.AST) -> None: if isinstance(node, self._forbidden_keywords): self.add_violation( WrongKeywordViolation( node, text=node.__class__.__qualname__.lower(), ), ) def visit(self, node: ast.AST) -> None: """ Used to find wrong keywords. Raises: WrongKeywordViolation """ self._check_keyword(node) self.generic_visit(node) @final class WrongTryExceptVisitor(BaseNodeVisitor): """Responsible for examining ``try`` and friends.""" _base_exception: ClassVar[str] = 'BaseException' def _check_if_needs_except(self, node: ast.Try) -> None: if node.finalbody and not node.handlers: self.add_violation(RedundantFinallyViolation(node)) def _check_exception_type(self, node: ast.ExceptHandler) -> None: exception_name = getattr(node, 'type', None) if exception_name is None: return exception_id = getattr(exception_name, 'id', None) if exception_id == self._base_exception: self.add_violation(BaseExceptionViolation(node)) def _check_duplicate_exceptions(self, node: ast.Try) -> None: exceptions: List[str] = [] for exc_handler in node.handlers: # There might be complex things hidden inside an exception type, # so we want to get the string representation of it: if isinstance(exc_handler.type, ast.Name): exceptions.append(astor.to_source(exc_handler.type).strip()) elif isinstance(exc_handler.type, ast.Tuple): exceptions.extend([ astor.to_source(node).strip() for node in exc_handler.type.elts ]) counts = Counter(exceptions) for exc_name, count in counts.items(): if count > 1: self.add_violation( DuplicateExceptionViolation(node, text=exc_name), ) def _check_return_path(self, node: ast.Try) -> None: try_has = any( is_contained(line, ast.Return) for line in node.body ) except_has = any( is_contained(except_handler, ast.Return) for except_handler in node.handlers ) else_has = any( is_contained(line, ast.Return) for line in node.orelse ) finally_has = any( is_contained(line, ast.Return) for line in node.finalbody ) if finally_has and (try_has or except_has): self.add_violation(TryExceptMultipleReturnPathViolation(node)) if else_has and try_has: self.add_violation(TryExceptMultipleReturnPathViolation(node)) def _check_useless_except(self, node: ast.ExceptHandler) -> None: if len(node.body) != 1: return body = node.body[0] if not isinstance(body, ast.Raise): return if isinstance(body.exc, ast.Call): return if isinstance(body.exc, ast.Name) and node.name: if body.exc.id != node.name: return self.add_violation(UselessExceptCaseViolation(node)) def visit_Try(self, node: ast.Try) -> None: """ Used for find finally in try blocks without except. Raises: RedundantFinallyViolation DuplicateExceptionViolation TryExceptMultipleReturnPathViolation """ self._check_if_needs_except(node) self._check_duplicate_exceptions(node) self._check_return_path(node) self.generic_visit(node) def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None: """ Checks all ``ExceptionHandler`` nodes. Raises: BaseExceptionViolation UselessExceptCaseViolation """ self._check_useless_except(node) self._check_exception_type(node) self.generic_visit(node) @final @alias('visit_any_with', ( 'visit_With', 'visit_AsyncWith', )) class WrongContextManagerVisitor(BaseNodeVisitor): """Checks context managers.""" def _check_target_assignment(self, node: AnyWith): if len(node.items) > 1: self.add_violation( MultipleContextManagerAssignmentsViolation(node), ) def visit_any_with(self, node: AnyWith) -> None: """ Checks the number of assignments for context managers. Raises: MultipleContextManagerAssignmentsViolation """ self._check_target_assignment(node) self.generic_visit(node) PK!ha>.wemake_python_styleguide/visitors/ast/loops.py# -*- coding: utf-8 -*- import ast from collections import defaultdict from typing import ClassVar, DefaultDict, List, Optional, Union from typing_extensions import final from wemake_python_styleguide.logics.nodes import get_parent, is_contained from wemake_python_styleguide.violations.best_practices import ( LambdaInsideLoopViolation, RedundantLoopElseViolation, YieldInComprehensionViolation, ) from wemake_python_styleguide.violations.complexity import ( TooManyForsInComprehensionViolation, ) from wemake_python_styleguide.violations.consistency import ( MultipleIfsInComprehensionViolation, UselessContinueViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor from wemake_python_styleguide.visitors.decorators import alias AnyLoop = Union[ast.For, ast.While, ast.AsyncFor] AnyComprehension = Union[ ast.ListComp, ast.DictComp, ast.SetComp, ast.GeneratorExp, ] @final @alias('visit_any_comprehension', ( 'visit_ListComp', 'visit_DictComp', 'visit_SetComp', 'visit_GeneratorExp', )) class WrongComprehensionVisitor(BaseNodeVisitor): """Checks comprehensions for correctness.""" _max_ifs: ClassVar[int] = 1 _max_fors: ClassVar[int] = 2 def __init__(self, *args, **kwargs) -> None: """Creates a counter for tracked metrics.""" super().__init__(*args, **kwargs) self._fors: DefaultDict[ast.AST, int] = defaultdict(int) def _check_ifs(self, node: ast.comprehension) -> None: if len(node.ifs) > self._max_ifs: # We are trying to fix line number in the report, # since `comprehension` does not have this property. parent = get_parent(node) or node self.add_violation(MultipleIfsInComprehensionViolation(parent)) def _check_fors(self, node: ast.comprehension) -> None: parent = get_parent(node) self._fors[parent] = len(parent.generators) # type: ignore def _check_contains_yield(self, node: AnyComprehension) -> None: for sub_node in ast.walk(node): if isinstance(sub_node, ast.Yield): self.add_violation(YieldInComprehensionViolation(node)) def _post_visit(self) -> None: for node, for_count in self._fors.items(): if for_count > self._max_fors: self.add_violation(TooManyForsInComprehensionViolation(node)) def visit_comprehension(self, node: ast.comprehension) -> None: """ Finds multiple ``if`` and ``for`` nodes inside the comprehension. Raises: MultipleIfsInComprehensionViolation TooManyForsInComprehensionViolation """ self._check_ifs(node) self._check_fors(node) self.generic_visit(node) def visit_any_comprehension(self, node: AnyComprehension) -> None: """ Finds incorrect patterns inside comprehensions. Raises: YieldInComprehensionViolation """ self._check_contains_yield(node) self.generic_visit(node) @final @alias('visit_any_loop', ( 'visit_For', 'visit_While', 'visit_AsyncFor', )) class WrongLoopVisitor(BaseNodeVisitor): """Responsible for examining loops.""" def _does_loop_contain_node( # TODO: move, reuse in annotations.py self, loop: Optional[AnyLoop], to_check: ast.Break, ) -> bool: if loop is None: return False for inner_node in ast.walk(loop): # We are checking this specific node, not just any `break`: if to_check is inner_node: return True return False def _has_break(self, node: AnyLoop) -> bool: closest_loop = None for subnode in ast.walk(node): if isinstance(subnode, (ast.For, ast.AsyncFor, ast.While)): if subnode is not node: closest_loop = subnode if isinstance(subnode, ast.Break): is_nested_break = self._does_loop_contain_node( closest_loop, subnode, ) if not is_nested_break: return True return False def _check_loop_needs_else(self, node: AnyLoop) -> None: if node.orelse and not self._has_break(node): self.add_violation(RedundantLoopElseViolation(node)) def _check_lambda_inside_loop(self, node: AnyLoop) -> None: for subnode in node.body: if is_contained(subnode, (ast.Lambda,)): self.add_violation(LambdaInsideLoopViolation(node)) def _check_useless_continue(self, node: AnyLoop) -> None: nodes_at_line: DefaultDict[int, List[ast.AST]] = defaultdict(list) for sub_node in ast.walk(node): lineno = getattr(sub_node, 'lineno', None) if lineno is not None: nodes_at_line[lineno].append(sub_node) last_line = nodes_at_line[sorted(nodes_at_line.keys())[-1]] if any(isinstance(last, ast.Continue) for last in last_line): self.add_violation(UselessContinueViolation(node)) def visit_any_loop(self, node: AnyLoop) -> None: """ Checks ``for`` and ``while`` loops. Raises: RedundantLoopElseViolation LambdaInsideLoopViolation """ self._check_loop_needs_else(node) self._check_lambda_inside_loop(node) self._check_useless_continue(node) self.generic_visit(node) PK!˗=  0wemake_python_styleguide/visitors/ast/modules.py# -*- coding: utf-8 -*- import ast from wemake_python_styleguide.constants import INIT from wemake_python_styleguide.logics.filenames import get_stem from wemake_python_styleguide.logics.nodes import is_doc_string from wemake_python_styleguide.types import final from wemake_python_styleguide.violations.best_practices import ( EmptyModuleViolation, InitModuleHasLogicViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor @final class EmptyModuleContentsVisitor(BaseNodeVisitor): """Restricts to have empty modules.""" def _is_init(self) -> bool: return get_stem(self.filename) == INIT def _check_module_contents(self, node: ast.Module) -> None: if self._is_init(): return if not node.body: self.add_violation(EmptyModuleViolation()) def _check_init_contents(self, node: ast.Module) -> None: if not self._is_init() or not node.body: return if not self.options.i_control_code: return if len(node.body) > 1: self.add_violation(InitModuleHasLogicViolation()) return if not is_doc_string(node.body[0]): self.add_violation(InitModuleHasLogicViolation()) def visit_Module(self, node: ast.Module) -> None: """ Checks that module has something other than module definition. We have completely different rules for ``__init__.py`` and regular files. Since, we believe that ``__init__.py`` must be empty. But, other files must have contents. Raises: EmptyModuleViolation InitModuleHasLogicViolation """ self._check_init_contents(node) self._check_module_contents(node) self.generic_visit(node) PK!d8ow'w'/wemake_python_styleguide/visitors/ast/naming.py# -*- coding: utf-8 -*- import ast from typing import Callable, List, Optional, Tuple, Union from wemake_python_styleguide.constants import ( MODULE_METADATA_VARIABLES_BLACKLIST, SPECIAL_ARGUMENT_NAMES_WHITELIST, VARIABLE_NAMES_BLACKLIST, ) from wemake_python_styleguide.logics import functions, nodes from wemake_python_styleguide.logics.naming import ( access, builtins, logical, name_nodes, ) from wemake_python_styleguide.types import ( AnyFunctionDef, AnyFunctionDefAndLambda, AnyImport, ConfigurationOptions, final, ) from wemake_python_styleguide.violations import base, naming from wemake_python_styleguide.violations.best_practices import ( ReassigningVariableToItselfViolation, WrongModuleMetadataViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor from wemake_python_styleguide.visitors.decorators import alias VariableDef = Union[ast.Name, ast.Attribute, ast.ExceptHandler] AssignTargets = List[ast.expr] AssignTargetsNameList = List[Union[str, Tuple[str]]] class _NameValidator(object): """Utility class to separate logic from the naming visitor.""" def __init__( self, error_callback: Callable[[base.BaseViolation], None], options: ConfigurationOptions, ) -> None: """Creates new instance of a name validator.""" self._error_callback = error_callback self._options = options def _ensure_underscores(self, node: ast.AST, name: str): if access.is_private(name): self._error_callback( naming.PrivateNameViolation(node, text=name), ) if logical.does_contain_underscored_number(name): self._error_callback( naming.UnderscoredNumberNameViolation(node, text=name), ) if logical.does_contain_consecutive_underscores(name): self._error_callback( naming.ConsecutiveUnderscoresInNameViolation( node, text=name, ), ) if builtins.is_wrong_alias(name): self._error_callback( naming.TrailingUnderscoreViolation(node, text=name), ) def _ensure_length(self, node: ast.AST, name: str) -> None: min_length = self._options.min_name_length if logical.is_too_short_name(name, min_length=min_length): self._error_callback(naming.TooShortNameViolation(node, text=name)) max_length = self._options.max_name_length if logical.is_too_long_name(name, max_length=max_length): self._error_callback(naming.TooLongNameViolation(node, text=name)) def check_name( self, node: ast.AST, name: str, is_first_argument: bool = False, ) -> None: if logical.is_wrong_name(name, VARIABLE_NAMES_BLACKLIST): self._error_callback( naming.WrongVariableNameViolation(node, text=name), ) if not is_first_argument: if logical.is_wrong_name(name, SPECIAL_ARGUMENT_NAMES_WHITELIST): self._error_callback( naming.ReservedArgumentNameViolation(node, text=name), ) if logical.does_contain_unicode(name): self._error_callback(naming.UnicodeNameViolation(node, text=name)) self._ensure_length(node, name) self._ensure_underscores(node, name) def check_function_signature(self, node: AnyFunctionDefAndLambda) -> None: arguments = functions.get_all_arguments(node) is_lambda = isinstance(node, ast.Lambda) for arg in arguments: should_check_argument = functions.is_first_argument( node, arg.arg, ) and not is_lambda self.check_name( arg, arg.arg, is_first_argument=should_check_argument, ) def check_attribute_name(self, node: ast.ClassDef) -> None: top_level_assigns = [ sub_node for sub_node in node.body if isinstance(sub_node, ast.Assign) ] for assignment in top_level_assigns: for target in assignment.targets: if not isinstance(target, ast.Name): continue name: Optional[str] = getattr(target, 'id', None) if name and logical.is_upper_case_name(name): self._error_callback( naming.UpperCaseAttributeViolation(target, text=name), ) @final @alias('visit_any_import', ( 'visit_ImportFrom', 'visit_Import', )) @alias('visit_any_function', ( 'visit_FunctionDef', 'visit_AsyncFunctionDef', )) @alias('visit_variable', ( 'visit_Name', 'visit_Attribute', 'visit_ExceptHandler', )) class WrongNameVisitor(BaseNodeVisitor): """Performs checks based on variable names.""" def __init__(self, *args, **kwargs) -> None: """Initializes new naming validator for this visitor.""" super().__init__(*args, **kwargs) self._validator = _NameValidator(self.add_violation, self.options) def visit_ClassDef(self, node: ast.ClassDef) -> None: """ Used to find upper attribute declarations. Raises: UpperCaseAttributeViolation UnicodeNameViolation TrailingUnderscoreViolation """ self._validator.check_attribute_name(node) self._validator.check_name(node, node.name) self.generic_visit(node) def visit_any_function(self, node: AnyFunctionDef) -> None: """ Used to find wrong function and method parameters. Raises: WrongVariableNameViolation TooShortNameViolation PrivateNameViolation TooLongNameViolation UnicodeNameViolation TrailingUnderscoreViolation """ self._validator.check_name(node, node.name) self._validator.check_function_signature(node) self.generic_visit(node) def visit_Lambda(self, node: ast.Lambda) -> None: """ Used to find wrong parameters. Raises: WrongVariableNameViolation TooShortNameViolation PrivateNameViolation TooLongNameViolation TrailingUnderscoreViolation """ self._validator.check_function_signature(node) self.generic_visit(node) def visit_any_import(self, node: AnyImport) -> None: """ Used to check wrong import alias names. Raises: WrongVariableNameViolation TooShortNameViolation PrivateNameViolation TooLongNameViolation TrailingUnderscoreViolation """ for alias_node in node.names: if alias_node.asname: self._validator.check_name(node, alias_node.asname) self.generic_visit(node) def visit_variable(self, node: VariableDef) -> None: """ Used to check wrong names of assigned. Raises: WrongVariableNameViolation TooShortNameViolation PrivateNameViolation TooLongNameViolation UnicodeNameViolation TrailingUnderscoreViolation """ variable_name = name_nodes.get_assigned_name(node) if variable_name is not None: self._validator.check_name(node, variable_name) self.generic_visit(node) @final class WrongModuleMetadataVisitor(BaseNodeVisitor): """Finds wrong metadata information of a module.""" def _check_metadata(self, node: ast.Assign) -> None: if not isinstance(nodes.get_parent(node), ast.Module): return for target_node in node.targets: target_node_id = getattr(target_node, 'id', None) if target_node_id in MODULE_METADATA_VARIABLES_BLACKLIST: self.add_violation( WrongModuleMetadataViolation(node, text=target_node_id), ) def visit_Assign(self, node: ast.Assign) -> None: """ Used to find the bad metadata variable names. Raises: WrongModuleMetadataViolation """ self._check_metadata(node) self.generic_visit(node) @final class WrongVariableAssignmentVisitor(BaseNodeVisitor): """Finds wrong variables assignments.""" def _create_target_names( self, target: AssignTargets, ) -> AssignTargetsNameList: """Creates list with names of targets of assignment.""" target_names = [] for ast_object in target: if isinstance(ast_object, ast.Name): target_names.append(getattr(ast_object, 'id', None)) if isinstance(ast_object, ast.Tuple): target_names.append(getattr(ast_object, 'elts', None)) for index, _ in enumerate(target_names): target_names[index] = tuple( name.id for name in target_names[index] if isinstance(name, ast.Name) ) return target_names def _check_assignment(self, node: ast.Assign) -> None: target_names = self._create_target_names(node.targets) if isinstance(node.value, ast.Tuple): node_values = node.value.elts values_names = tuple( getattr(node_value, 'id', None) for node_value in node_values ) else: values_names = getattr(node.value, 'id', None) has_repeatable_values = len(target_names) != len(set(target_names)) if values_names in target_names or has_repeatable_values: self.add_violation(ReassigningVariableToItselfViolation(node)) def visit_Assign(self, node: ast.Assign) -> None: """ Used to check assignment variable to itself. Raises: ReassigningVariableToItselfViolation """ self._check_assignment(node) self.generic_visit(node) PK!FQ3wemake_python_styleguide/visitors/ast/statements.py# -*- coding: utf-8 -*- import ast from typing import ClassVar, Mapping, Optional, Sequence, Union from wemake_python_styleguide.logics.collections import normalize_dict_elements from wemake_python_styleguide.logics.functions import get_all_arguments from wemake_python_styleguide.logics.nodes import get_parent, is_doc_string from wemake_python_styleguide.types import AnyFunctionDef, AnyNodes, final from wemake_python_styleguide.violations.best_practices import ( StatementHasNoEffectViolation, UnreachableCodeViolation, ) from wemake_python_styleguide.violations.consistency import ( ParametersIndentationViolation, UselessNodeViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor from wemake_python_styleguide.visitors.decorators import alias StatementWithBody = Union[ ast.If, ast.For, ast.AsyncFor, ast.While, ast.With, ast.AsyncWith, ast.Try, ast.ExceptHandler, ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Module, ] AnyCollection = Union[ ast.List, ast.Set, ast.Dict, ast.Tuple, ] @final @alias('visit_statement_with_body', ( 'visit_If', 'visit_For', 'visit_AsyncFor', 'visit_While', 'visit_With', 'visit_AsyncWith', 'visit_Try', 'visit_ExceptHandler', 'visit_FunctionDef', 'visit_AsyncFunctionDef', 'visit_ClassDef', 'visit_Module', )) class StatementsWithBodiesVisitor(BaseNodeVisitor): """ Responsible for restricting incorrect patterns and members inside bodies. This visitor checks all statements that have multiline bodies. """ _closing_nodes: ClassVar[AnyNodes] = ( ast.Raise, ast.Return, ast.Break, ast.Continue, ) _have_doc_strings: ClassVar[AnyNodes] = ( ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Module, ) # FIXME: not typed, `mypy` will complain about `isinstance` calls _nodes_with_orelse = ( ast.If, ast.For, ast.AsyncFor, ast.While, ast.Try, ) _have_effect: ClassVar[AnyNodes] = ( ast.Return, ast.YieldFrom, ast.Yield, ast.Raise, ast.Break, ast.Continue, ast.Call, ast.Await, ast.Nonlocal, ast.Global, ast.Delete, ast.Pass, ast.Assert, ) # Useless nodes: _generally_useless_body: ClassVar[AnyNodes] = ( ast.Break, ast.Continue, ast.Pass, ast.Ellipsis, ) _loop_useless_body: ClassVar[AnyNodes] = ( ast.Return, ast.Raise, ) _useless_combination: ClassVar[Mapping[str, AnyNodes]] = { 'For': _generally_useless_body + _loop_useless_body, 'AsyncFor': _generally_useless_body + _loop_useless_body, 'While': _generally_useless_body + _loop_useless_body, 'Try': _generally_useless_body + (ast.Raise,), 'With': _generally_useless_body, 'AsyncWith': _generally_useless_body, } def _check_useless_node( self, node: StatementWithBody, body: Sequence[ast.stmt], ) -> None: if len(body) != 1: return forbiden = self._useless_combination.get( node.__class__.__qualname__, None, ) if not forbiden or not isinstance(body[0], forbiden): return self.add_violation( UselessNodeViolation( node, text=node.__class__.__qualname__.lower(), ), ) def _check_expression( self, node: ast.Expr, is_first: bool = False, ) -> None: if isinstance(node.value, self._have_effect): return if is_first and is_doc_string(node): if isinstance(get_parent(node), self._have_doc_strings): return self.add_violation(StatementHasNoEffectViolation(node)) def _check_internals(self, body: Sequence[ast.stmt]) -> None: after_closing_node = False for index, statement in enumerate(body): if after_closing_node: self.add_violation(UnreachableCodeViolation(statement)) if isinstance(statement, self._closing_nodes): after_closing_node = True if isinstance(statement, ast.Expr): self._check_expression(statement, is_first=index == 0) def visit_statement_with_body(self, node: StatementWithBody) -> None: """ Visits statement's body internals. Raises: UnreachableCodeViolation """ self._check_internals(node.body) if isinstance(node, self._nodes_with_orelse): self._check_internals(node.orelse) if isinstance(node, ast.Try): self._check_internals(node.finalbody) self._check_useless_node(node, node.body) self.generic_visit(node) @final @alias('visit_collection', ( 'visit_List', 'visit_Set', 'visit_Dict', 'visit_Tuple', )) @alias('visit_any_function', ( 'visit_FunctionDef', 'visit_AsyncFunctionDef', )) class WrongParametersIndentationVisitor(BaseNodeVisitor): """Ensures that all parameters indentation follow our rules.""" def _check_first_element( self, node: ast.AST, statement: ast.AST, extra_lines: int, ) -> Optional[bool]: if statement.lineno == node.lineno and not extra_lines: return False return None def _check_rest_elements( self, node: ast.AST, statement: ast.AST, previous_line: int, multi_line_mode: Optional[bool], ) -> Optional[bool]: previous_has_break = previous_line != statement.lineno if not previous_has_break and multi_line_mode: self.add_violation(ParametersIndentationViolation(node)) return None elif previous_has_break and multi_line_mode is False: self.add_violation(ParametersIndentationViolation(node)) return None return previous_has_break def _check_indentation( self, node: ast.AST, elements: Sequence[ast.AST], extra_lines: int = 0, # we need it due to wrong lineno in collections ) -> None: multi_line_mode: Optional[bool] = None for index, statement in enumerate(elements): if index == 0: # We treat first element differently, # since it is impossible to say what kind of multi-line # parameters styles will be used at this moment. multi_line_mode = self._check_first_element( node, statement, extra_lines, ) else: multi_line_mode = self._check_rest_elements( node, statement, elements[index - 1].lineno, multi_line_mode, ) def visit_collection(self, node: AnyCollection) -> None: """Checks how collection items indentation.""" if isinstance(node, ast.Dict): elements = normalize_dict_elements(node) else: elements = node.elts self._check_indentation(node, elements, extra_lines=1) self.generic_visit(node) def visit_Call(self, node: ast.Call) -> None: """Checks call arguments indentation.""" all_args = [*node.args, *[kw.value for kw in node.keywords]] self._check_indentation(node, all_args) self.generic_visit(node) def visit_any_function(self, node: AnyFunctionDef) -> None: """Checks function parameters indentation.""" self._check_indentation(node, get_all_arguments(node)) self.generic_visit(node) def visit_ClassDef(self, node: ast.ClassDef) -> None: """Checks base classes indentation.""" all_args = [*node.bases, *[kw.value for kw in node.keywords]] self._check_indentation(node, all_args) self.generic_visit(node) PK!ud==)wemake_python_styleguide/visitors/base.py# -*- coding: utf-8 -*- """ Contains detailed technical documentation about how to write a :term:`visitor`. See also: Visitor is a well-known software engineering pattern: https://en.wikipedia.org/wiki/Visitor_pattern Each visitor might work with one or many :term:`violations `. Multiple visitors might one with the same violation. .. mermaid:: :caption: Visitor relation with violations. graph TD V1[Visitor 1] --> EA[Violation A] V1[Visitor 1] --> EB[Violation B] V2[Visitor 2] --> EA[Violation A] V2[Visitor 2] --> EC[Violation C] V3[Visitor 3] --> EZ[Violation Z] .. _visitors: Visitors API ------------ .. currentmodule:: wemake_python_styleguide.visitors.base .. autoclasstree:: wemake_python_styleguide.visitors.base .. autosummary:: :nosignatures: BaseNodeVisitor BaseFilenameVisitor BaseTokenVisitor The decision relies on what parameters do you need for the task. It is highly unlikely that you will need two parameters at the same time. See :ref:`tutorial` for more information about choosing a correct base class. Conventions ~~~~~~~~~~~ Then you will have to write logic for your visitor. We follow these conventions: - Public visitor methods start with ``visit_``, than comes the name of a token or node to be visited - All other methods and attributes should be protected - We try to separate as much logic from ``visit_`` methods as possible, so they only route for callbacks that actually executes the checks - We place repeating logics into ``logics/`` package to be able to reuse it There are different example of visitors in this project already. Reference ~~~~~~~~~ """ import ast import tokenize from typing import List, Sequence, Type from wemake_python_styleguide import constants from wemake_python_styleguide.logics.filenames import get_stem from wemake_python_styleguide.types import ConfigurationOptions, final from wemake_python_styleguide.violations.base import BaseViolation class BaseVisitor(object): """ Abstract base class for different types of visitors. Attributes: options: contains the options objects passed and parsed by ``flake8``. filename: filename passed by ``flake8``, each visitor has a file name. violations: list of :term:`violations ` for the specific visitor. """ def __init__( self, options: ConfigurationOptions, filename: str = constants.STDIN, ) -> None: """Creates base visitor instance.""" self.options = options self.filename = filename self.violations: List[BaseViolation] = [] @classmethod def from_checker( cls: Type['BaseVisitor'], checker, ) -> 'BaseVisitor': """ Constructs visitor instance from the checker. Each unique visitor class should know how to construct itself from the :term:`checker` instance. Generally speaking, each visitor class needs to eject required parameters from checker and then run its constructor with these parameters. """ return cls(options=checker.options, filename=checker.filename) @final def add_violation(self, violation: BaseViolation) -> None: """Adds violation to the visitor.""" self.violations.append(violation) def run(self) -> None: """ Abstract method to run a visitor. Each visitor should know what exactly it needs to do when it was told to ``run``. This method should be defined in all subclasses. """ raise NotImplementedError('Should be defined in a subclass') def _post_visit(self) -> None: """ Executed after all nodes have been visited. This method is useful for counting statistics, etc. By default does nothing. """ class BaseNodeVisitor(ast.NodeVisitor, BaseVisitor): """ Allows to store violations while traversing node tree. This class should be used as a base class for all ``ast`` based checkers. Method ``visit()`` is defined in ``NodeVisitor`` class. Attributes: tree: ``ast`` tree to be checked. """ def __init__( self, options: ConfigurationOptions, tree: ast.AST, **kwargs, ) -> None: """Creates new ``ast`` based instance.""" super().__init__(options, **kwargs) self.tree = tree @final @classmethod def from_checker( cls: Type['BaseNodeVisitor'], checker, ) -> 'BaseNodeVisitor': """Constructs visitor instance from the checker.""" return cls( options=checker.options, filename=checker.filename, tree=checker.tree, ) @final def run(self) -> None: """Recursively visits all ``ast`` nodes. Then executes post hook.""" self.visit(self.tree) self._post_visit() class BaseFilenameVisitor(BaseVisitor): """ Abstract base class that allows to visit and check module file names. Has ``visit_filename()`` method that should be defined in subclasses. Attributes: stem: the last part of the filename. Does not contain extension. """ stem: str def visit_filename(self) -> None: """ Abstract method to check module file names. This method should be overridden in a subclass. """ raise NotImplementedError('Should be defined in a subclass') @final def run(self) -> None: """ Checks module's filename. Skips modules that are checked as piped output. Since these modules are checked as a ``stdin`` input. And do not have names. """ if self.filename != constants.STDIN: self.stem = get_stem(self.filename) self.visit_filename() self._post_visit() class BaseTokenVisitor(BaseVisitor): """ Allows to check ``tokenize`` sequences. Attributes: file_tokens: ``tokenize.TokenInfo`` sequence to be checked. """ def __init__( self, options: ConfigurationOptions, file_tokens: Sequence[tokenize.TokenInfo], **kwargs, ) -> None: """Creates new ``tokenize`` based visitor instance.""" super().__init__(options, **kwargs) self.file_tokens = file_tokens @final @classmethod def from_checker( cls: Type['BaseTokenVisitor'], checker, ) -> 'BaseTokenVisitor': """Constructs ``tokenize`` based visitor instance from the checker.""" return cls( options=checker.options, filename=checker.filename, file_tokens=checker.file_tokens, ) def visit(self, token: tokenize.TokenInfo) -> None: """ Runs custom defined handlers in a visitor for each specific token type. Uses ``.exact_type`` property to fetch the token name. So, you have to be extra careful with tokens like ``->`` and other operators, since they might resolve in just ``OP`` name. Does nothing if handler for any token type is not defined. Inspired by ``NodeVisitor`` class. See also: https://docs.python.org/3/library/tokenize.html """ token_type = tokenize.tok_name[token.exact_type].lower() method = getattr(self, 'visit_' + token_type, None) if method is not None: method(token) @final def run(self) -> None: """Visits all token types that have a handler method.""" for token in self.file_tokens: self.visit(token) self._post_visit() PK!I0/wemake_python_styleguide/visitors/decorators.py# -*- coding: utf-8 -*- from typing import Callable, Tuple def alias( original: str, aliases: Tuple[str, ...], ) -> Callable[[type], type]: """ Decorator to alias handlers. Why do we need it? Because there are cases when we need to use the same method to handle different nodes types. We can just create aliases like ``visit_Import = visit_ImportFrom``, but it looks verbose and ugly. """ if len(aliases) != len(set(aliases)): raise ValueError('Found duplicate aliases') def decorator(cls: type) -> type: original_handler = getattr(cls, original) for alias in aliases: setattr(cls, alias, original_handler) return cls return decorator PK!uh7wemake_python_styleguide/visitors/filenames/__init__.py# -*- coding: utf-8 -*- PK!Dt 5wemake_python_styleguide/visitors/filenames/module.py# -*- coding: utf-8 -*- from wemake_python_styleguide import constants from wemake_python_styleguide.logics.naming import access, logical from wemake_python_styleguide.types import final from wemake_python_styleguide.violations.naming import ( ConsecutiveUnderscoresInNameViolation, PrivateNameViolation, TooLongNameViolation, TooShortNameViolation, UnderscoredNumberNameViolation, UnicodeNameViolation, WrongModuleMagicNameViolation, WrongModuleNamePatternViolation, WrongModuleNameViolation, ) from wemake_python_styleguide.visitors.base import BaseFilenameVisitor @final class WrongModuleNameVisitor(BaseFilenameVisitor): """Checks that modules have correct names.""" def _check_module_name(self) -> None: if logical.is_wrong_name(self.stem, constants.MODULE_NAMES_BLACKLIST): self.add_violation(WrongModuleNameViolation()) if access.is_magic(self.stem): if self.stem not in constants.MAGIC_MODULE_NAMES_WHITELIST: self.add_violation(WrongModuleMagicNameViolation()) if access.is_private(self.stem): self.add_violation(PrivateNameViolation(text=self.stem)) if logical.does_contain_unicode(self.stem): self.add_violation(UnicodeNameViolation(text=self.stem)) def _check_module_name_length(self) -> None: min_length = self.options.min_name_length if logical.is_too_short_name(self.stem, min_length=min_length): self.add_violation(TooShortNameViolation(text=self.stem)) max_length = self.options.max_name_length if logical.is_too_long_name(self.stem, max_length=max_length): self.add_violation(TooLongNameViolation(text=self.stem)) def _check_module_name_pattern(self) -> None: if not constants.MODULE_NAME_PATTERN.match(self.stem): self.add_violation(WrongModuleNamePatternViolation()) if logical.does_contain_consecutive_underscores(self.stem): self.add_violation( ConsecutiveUnderscoresInNameViolation(text=self.stem), ) if logical.does_contain_underscored_number(self.stem): self.add_violation(UnderscoredNumberNameViolation(text=self.stem)) def visit_filename(self) -> None: """ Checks a single module's filename. Raises: TooShortModuleNameViolation WrongModuleMagicNameViolation WrongModuleNameViolation WrongModuleNamePatternViolation WrongModuleNameUnderscoresViolation UnderscoredNumberNameViolation TooLongNameViolation """ self._check_module_name() self._check_module_name_length() self._check_module_name_pattern() PK!uh6wemake_python_styleguide/visitors/tokenize/__init__.py# -*- coding: utf-8 -*- PK!ٝ6wemake_python_styleguide/visitors/tokenize/comments.py# -*- coding: utf-8 -*- r""" Disallows to use incorrect magic comments. That's how a basic ``comment`` type token looks like: TokenInfo( type=57 (COMMENT), string='# noqa: Z100', start=(1, 4), end=(1, 16), line="u'' # noqa: Z100\n", ) """ import re import tokenize from typing import ClassVar, FrozenSet from typing.re import Pattern from wemake_python_styleguide.constants import MAX_NOQA_COMMENTS from wemake_python_styleguide.types import final from wemake_python_styleguide.violations.best_practices import ( OveruseOfNoqaCommentViolation, WrongDocCommentViolation, WrongMagicCommentViolation, ) from wemake_python_styleguide.violations.consistency import ( EmptyLineAfterCodingViolation, ) from wemake_python_styleguide.visitors.base import BaseTokenVisitor @final class WrongCommentVisitor(BaseTokenVisitor): """Checks comment tokens.""" _noqa_check: ClassVar[Pattern] = re.compile(r'^noqa:?($|[A-Z\d\,\s]+)') _type_check: ClassVar[Pattern] = re.compile( r'^type:\s?([\w\d\[\]\'\"\.]+)$', ) def __init__(self, *args, **kwargs) -> None: """Initializes a counter.""" super().__init__(*args, **kwargs) self._noqa_count = 0 def _get_comment_text(self, token: tokenize.TokenInfo) -> str: return token.string[1:].strip() def _check_noqa(self, token: tokenize.TokenInfo) -> None: comment_text = self._get_comment_text(token) match = self._noqa_check.match(comment_text) if not match: return self._noqa_count += 1 excludes = match.groups()[0].strip() if not excludes: # We can not pass the actual line here, # since it will be ignored due to `# noqa` comment: self.add_violation(WrongMagicCommentViolation(text=comment_text)) def _check_typed_ast(self, token: tokenize.TokenInfo) -> None: comment_text = self._get_comment_text(token) match = self._type_check.match(comment_text) if not match: return declared_type = match.groups()[0].strip() if declared_type != 'ignore': self.add_violation( WrongMagicCommentViolation(token, text=comment_text), ) def _check_empty_doc_comment(self, token: tokenize.TokenInfo) -> None: comment_text = self._get_comment_text(token) if comment_text == ':': self.add_violation(WrongDocCommentViolation(token)) def _post_visit(self) -> None: if self._noqa_count > MAX_NOQA_COMMENTS: self.add_violation( OveruseOfNoqaCommentViolation(text=str(self._noqa_count)), ) def visit_comment(self, token: tokenize.TokenInfo) -> None: """ Performs comment checks. Raises: OveruseOfNoqaCommentViolation WrongDocCommentViolation WrongMagicCommentViolation """ self._check_noqa(token) self._check_typed_ast(token) self._check_empty_doc_comment(token) @final class FileMagicCommentsVisitor(BaseTokenVisitor): """Checks comments for the whole file.""" _allowed_newlines: ClassVar[FrozenSet[int]] = frozenset(( tokenize.NL, tokenize.NEWLINE, tokenize.ENDMARKER, )) def _offset_for_comment_line(self, token: tokenize.TokenInfo) -> int: if token.exact_type == tokenize.COMMENT: return 2 return 0 def _check_empty_line_after_codding( self, token: tokenize.TokenInfo, ) -> None: """ Checks that we have a blank line after the magic comments. PEP-263 says: a magic comment must be placed into the source files either as first or second line in the file See also: https://www.python.org/dev/peps/pep-0263/ """ if token.start[0] == 1: tokens = iter(self.file_tokens[self.file_tokens.index(token):]) available_offset = 2 # comment + newline while True: next_token = next(tokens) if not available_offset: available_offset = self._offset_for_comment_line( next_token, ) if available_offset > 0: available_offset -= 1 continue if next_token.exact_type not in self._allowed_newlines: self.add_violation(EmptyLineAfterCodingViolation(token)) break def visit_comment(self, token: tokenize.TokenInfo) -> None: """ Checks special comments that are magic per each file. Raises: EmptyLineAfterCoddingViolation """ self._check_empty_line_after_codding(token) PK! qD6wemake_python_styleguide/visitors/tokenize/keywords.py# -*- coding: utf-8 -*- import keyword import tokenize from wemake_python_styleguide.types import final from wemake_python_styleguide.violations.consistency import ( MissingSpaceBetweenKeywordAndParenViolation, ) from wemake_python_styleguide.visitors.base import BaseTokenVisitor @final class WrongKeywordTokenVisitor(BaseTokenVisitor): """Visits keywords and finds violations related to their usage.""" def _check_space_before_open_paren(self, token: tokenize.TokenInfo) -> None: if token.line[token.end[1]:].startswith('('): self.add_violation( MissingSpaceBetweenKeywordAndParenViolation(token), ) def visit_name(self, token: tokenize.TokenInfo) -> None: """ Check keywords related rules. Raises: MissingSpaceBetweenKeywordAndParenViolation """ if keyword.iskeyword(token.string): self._check_space_before_open_paren(token) PK!U8wemake_python_styleguide/visitors/tokenize/primitives.py# -*- coding: utf-8 -*- import tokenize from typing import ClassVar, FrozenSet, Optional from flake8_quotes.docstring_detection import get_docstring_tokens from wemake_python_styleguide.logics.tokens import ( has_triple_string_quotes, split_prefixes, ) from wemake_python_styleguide.types import final from wemake_python_styleguide.violations.consistency import ( BadNumberSuffixViolation, ImplicitStringConcatenationViolation, IncorrectMultilineStringViolation, PartialFloatViolation, UnderscoredNumberViolation, UnicodeStringViolation, UppercaseStringModifierViolation, ) from wemake_python_styleguide.visitors.base import BaseTokenVisitor @final class WrongNumberTokenVisitor(BaseTokenVisitor): """Visits number tokens to find incorrect usages.""" _bad_number_suffixes: ClassVar[FrozenSet[str]] = frozenset(( 'X', 'O', 'B', 'E', )) def _check_underscored_number(self, token: tokenize.TokenInfo) -> None: if '_' in token.string: self.add_violation( UnderscoredNumberViolation(token, text=token.string), ) def _check_partial_float(self, token: tokenize.TokenInfo) -> None: if token.string.startswith('.') or token.string.endswith('.'): self.add_violation(PartialFloatViolation(token, text=token.string)) def _check_bad_number_suffixes(self, token: tokenize.TokenInfo) -> None: if any(char in token.string for char in self._bad_number_suffixes): self.add_violation( BadNumberSuffixViolation(token, text=token.string), ) def visit_number(self, token: tokenize.TokenInfo) -> None: """ Checks number declarations. Raises: UnderscoredNumberViolation PartialFloatViolation BadNumberSuffixViolation """ self._check_underscored_number(token) self._check_partial_float(token) self._check_bad_number_suffixes(token) @final class WrongStringTokenVisitor(BaseTokenVisitor): """Checks incorrect string tokens usages.""" _bad_string_modifiers: ClassVar[FrozenSet[str]] = frozenset(( 'R', 'F', 'B', 'U', )) def __init__(self, *args, **kwargs) -> None: """Initializes new visitor and saves all docstrings.""" super().__init__(*args, **kwargs) self._docstrings = get_docstring_tokens(self.file_tokens) def _check_correct_multiline(self, token: tokenize.TokenInfo) -> None: _, string_def = split_prefixes(token) if has_triple_string_quotes(string_def): if '\n' not in string_def and token not in self._docstrings: self.add_violation(IncorrectMultilineStringViolation(token)) def _check_string_modifiers(self, token: tokenize.TokenInfo) -> None: if token.string.lower().startswith('u'): self.add_violation( UnicodeStringViolation(token, text=token.string), ) modifiers, _ = split_prefixes(token) for mod in modifiers: if mod in self._bad_string_modifiers: self.add_violation( UppercaseStringModifierViolation(token, text=mod), ) def visit_string(self, token: tokenize.TokenInfo) -> None: """ Finds incorrect string usages. ``u`` can only be the only prefix. You can not combine it with ``r``, ``b``, or ``f``. Since it will raise a ``SyntaxError`` while parsing. Raises: UnicodeStringViolation IncorrectMultilineStringViolation """ self._check_correct_multiline(token) self._check_string_modifiers(token) @final class WrongStringConcatenationVisitor(BaseTokenVisitor): """Checks incorrect string concatenation.""" _ignored_tokens: ClassVar[FrozenSet[int]] = frozenset(( tokenize.NL, tokenize.NEWLINE, tokenize.INDENT, )) def __init__(self, *args, **kwargs) -> None: """Adds extra ``_previous_token`` property.""" super().__init__(*args, **kwargs) self._previous_token: Optional[tokenize.TokenInfo] = None def _check_concatenation(self, token: tokenize.TokenInfo) -> None: if token.exact_type in self._ignored_tokens: return if token.exact_type == tokenize.STRING: if self._previous_token: self.add_violation(ImplicitStringConcatenationViolation(token)) self._previous_token = token else: self._previous_token = None def visit(self, token: tokenize.TokenInfo) -> None: """ Ensures that all string are concatenated as we allow. Raises: ImplicitStringConcatenationViolation """ self._check_concatenation(token) PK!Mf8wemake_python_styleguide/visitors/tokenize/statements.py# -*- coding: utf-8 -*- import tokenize from collections import defaultdict from typing import ClassVar, DefaultDict, Dict, List, Sequence, Set, Tuple from wemake_python_styleguide.logics.tokens import only_contains from wemake_python_styleguide.types import final from wemake_python_styleguide.violations.consistency import ( ExtraIndentationViolation, WrongBracketPositionViolation, ) from wemake_python_styleguide.visitors.base import BaseTokenVisitor TokenLines = DefaultDict[int, List[tokenize.TokenInfo]] MATCHING: Dict[int, int] = { tokenize.LBRACE: tokenize.RBRACE, tokenize.LSQB: tokenize.RSQB, tokenize.LPAR: tokenize.RPAR, } ALLOWED_EMPTY_LINE_TOKENS: Set[int] = { tokenize.NL, tokenize.NEWLINE, *MATCHING.values(), } def _get_reverse_bracket(bracket: tokenize.TokenInfo) -> int: index = list(MATCHING.values()).index(bracket.exact_type) return list(MATCHING.keys())[index] @final class ExtraIndentationVisitor(BaseTokenVisitor): """ Is used to find extra indentation in nodes. Algorithm: 1. goes through all nodes in a module 2. remembers minimal indentation for each line 3. compares each two closest lines: indentation should not be >4 """ _ignored_tokens: ClassVar[Tuple[int, ...]] = ( tokenize.NEWLINE, ) _ignored_previous_token: ClassVar[Tuple[int, ...]] = ( tokenize.NL, ) def __init__(self, *args, **kwargs) -> None: """Creates empty counter.""" super().__init__(*args, **kwargs) self._offsets: Dict[int, tokenize.TokenInfo] = {} def _check_extra_indentation(self, token: tokenize.TokenInfo) -> None: lineno, offset = token.start if lineno not in self._offsets: self._offsets[lineno] = token def _get_token_offset(self, token: tokenize.TokenInfo) -> int: if token.exact_type == tokenize.INDENT: offset = token.end[1] else: offset = token.start[1] return offset def _check_individual_line( self, lines: Sequence[int], line: int, index: int, ) -> None: current_token = self._offsets[line] if current_token.exact_type in self._ignored_tokens: return previous_token = self._offsets[lines[index - 1]] if previous_token.exact_type in self._ignored_previous_token: return offset = self._get_token_offset(current_token) previous_offset = self._get_token_offset(previous_token) if offset > previous_offset + 4: self.add_violation(ExtraIndentationViolation(current_token)) def _post_visit(self) -> None: lines = sorted(self._offsets.keys()) for index, line in enumerate(lines): if index == 0 or line != lines[index - 1] + 1: continue self._check_individual_line(lines, line, index) def visit(self, token: tokenize.TokenInfo) -> None: """ Goes through all tokens to find wrong indentation. Raises: ExtraIndentationViolation """ self._check_extra_indentation(token) @final class BracketLocationVisitor(BaseTokenVisitor): """ Finds closing brackets location. We check that brackets can be on the same line or brackets can be the only tokens on the line. We track all kind of brackets: round, square, and curly. """ def __init__(self, *args, **kwargs) -> None: """Creates line tracking for tokens.""" super().__init__(*args, **kwargs) self._lines: TokenLines = defaultdict(list) def _annotate_brackets( self, tokens: List[tokenize.TokenInfo], ) -> Dict[int, int]: """Annotates each opening bracket with the nested level index.""" brackets = {bracket: 0 for bracket in MATCHING.keys()} for token in tokens: if token.exact_type in MATCHING.keys(): brackets[token.exact_type] += 1 if token.exact_type in MATCHING.values(): reverse_bracket = _get_reverse_bracket(token) if brackets[reverse_bracket] > 0: brackets[reverse_bracket] -= 1 return brackets def _check_closing( self, token: tokenize.TokenInfo, index: int, tokens: List[tokenize.TokenInfo], ) -> None: tokens_before = tokens[:index] annotated = self._annotate_brackets(tokens_before) if annotated[_get_reverse_bracket(token)] == 0: if not only_contains(tokens_before, ALLOWED_EMPTY_LINE_TOKENS): self.add_violation(WrongBracketPositionViolation(token)) def _check_individual_line(self, tokens: List[tokenize.TokenInfo]) -> None: for index, token in enumerate(tokens): if token.exact_type in MATCHING.values(): self._check_closing(token, index, tokens) def _post_visit(self) -> None: for _, tokens in self._lines.items(): self._check_individual_line(tokens) def visit(self, token: tokenize.TokenInfo) -> None: """ Goes trough all tokens to separate them by line numbers. Raises: WrongBracketPositionViolation """ self._lines[token.start[0]].append(token) PK!H";?9wemake_python_styleguide-0.7.1.dist-info/entry_points.txtNINK(I+ϋ劲-O TdT椦f%g&gY9Ch..PK!f000wemake_python_styleguide-0.7.1.dist-info/LICENSEMIT License Copyright (c) 2018 wemake.services Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!HڽTU.wemake_python_styleguide-0.7.1.dist-info/WHEEL A н#Z;/"d&F[xzw@Zpy3Fv]\fi4WZ^EgM_-]#0(q7PK!HkT m1wemake_python_styleguide-0.7.1.dist-info/METADATAYmW۸_BcB/9e{.o%н{68j˕g$4]Pph^Q <(*oFh<4vhף1׳&; f2'l [0όe2B31:x88qhma#-xb"Q d,rgob6U:1M6ȰU Le^G<=fSf^U"g΂VuɑuU_ebRDfMFcREp*>R 8ћ׭Eh=θ1r @Lc[ֵܖ59 YA'Rܑf[ t>4XU&R JmeR8VQh5֦3|Ɩc0V)Όc&ss{Di-dыƎ3hL ]5S 5,}͵fϡJLckSj_\̎4ɸJrU{WPY Qm7B㟈\ B%$a*cTZD"IXJ^}w b!JڛrZ)yQn~x,pe ޾.ǗyjGjdS"cr)(m/7S)`0 J_QQbsc}ËܸWd @8e+Vw~>ʊr|Cggy+`Kx|\_;t` ĥ]yX NDlӃ&;2?]UTaُB8VK c#LeAJ(8نgP@:(Q<,/ţ[?υ42C)*oϓTWa#3If/-S[flh-teFxؖǧR{>윧xjև!U^C{/iwZm?/dw#z?\{>'`~9\ӻd򿭣J=Yѧ?[?ޗ]k:2ɟ{{VɗV]g9\~v^a?OSf?eUVT 5|"MHCȹO%iDPJFsKFpE13]B Bϧ`B-KOE$3nшMXהUV~7c!!?SҢJ|i32lais- U Zw"t_-kVRoeF;͉.[X99v56_ſdaGX: H'-thpAֿD-Jz{Ogr7(%}U[9 uy.Aa.2l*fAo=& Eg=_{b3C+bآO^*h@"gjP5֟39f'| eFg%9LYt.Loʱ]zש3elv1 waSZ\;"0"h26XŨ0SLRL>Rl\iVbbXCkƀ!'c3"sK;0Q ~tk1鲟,<} [4QZ JhIE fZ[D~PV\ 9q, U")D1rՕukcCXV[2q\zMf|Jaia]Ob"̒E5.k8r k .|A\'$5ِKO!Cv3d gfvkq*5g@WE\8!9F#(A;LٰXi4(i#J0tO~eNvh A! &ձCl*A3`:4Ig-(=F spHeıC drA2v=@fr6u%Ys$l›Hb$D;R`Up$s4$Nu^"isQrx@E O+-$eck_՝_cw?3 3Ig,ySps~/4* d%~]<>70cfEh~JܶTZ.X]ҕ)96\X'Csb*$| A,ʙ]d* ]Rʍp"h\}hլn͈.,Eљ=VcHń/ YT%* <=UV=Ngq ~{x@@eMQ]l|(* X"!xim V!\ڥ9!^s&ɸx%;D _fcoa57A_&켡!4ZvwA<C. 357|w'zli}t:_OvfMZ(|e=O2׋IϺ5~OG<<,8!Wr&C! 4&"0curpnniu.qo~>G9JADU0AѢ>~ ñu."PXFǥ[;)9'H 5}!kd.]x7n ̢O76? Ϸ2 {!'1t^GuWz=GyOc󋕭,B݊Y{Urm'0LdH1Knb**?,1푂*7^!*U}XE]jAT@ 6;ta<tiD."8H,޼\@Ma K;pl#T g ۞:mͅH]V `ғ_$A|j[7 eɝDZIjUpZq؆6D _'vyI[r+TA9uaؿF{FBk)4 -n._,O&FXβq՚S1uo|7r 1-;\3E᤬#VWF M[w _z}hqGb)VZd+j y!;e<T'&n|BOB'BPs5\o Ь^'g f8":rbYYQ@JM}o'z3 r5f/ a]\>+PT D$1 ;`_F (fX4+R2=QNHdӚְQLvd߻'ެ >⯢iuXSg4{w,m 5و"ՊsM$~a*Y¬.iKrJxZA^} O]b5FR ~F7B' Ⳓ2]Lz$2Zp8x*oz_9_wWP TurhZJV@nk_1k/f}Ĕu0/łÔvnfNnNed54f%JQLH |vH*㹈u~Cpspap5MVJq Ӡ~>0[ܦNyJ<͕yol^rQp<ƾ܌W-G'ξ wYN6orq7 ()Si."(-y7zTZsMqa/m~^p[d΁7?|H܅3+'紛Kfܬ<) #R{4-IJs_PK!uh$wemake_python_styleguide/__init__.pyPK!a#Zwemake_python_styleguide/checker.pyPK!ٮ0V%Owemake_python_styleguide/constants.pyPK!uh+"wemake_python_styleguide/logics/__init__.pyPK!sx33.{"wemake_python_styleguide/logics/collections.pyPK!,%wemake_python_styleguide/logics/filenames.pyPK!/ X%<<,'wemake_python_styleguide/logics/functions.pyPK!7*g/wemake_python_styleguide/logics/imports.pyPK!uh20wemake_python_styleguide/logics/naming/__init__.pyPK!>]Z''041wemake_python_styleguide/logics/naming/access.pyPK!L"x[[26wemake_python_styleguide/logics/naming/builtins.pyPK!< 21T;wemake_python_styleguide/logics/naming/logical.pyPK!^=S  4IMwemake_python_styleguide/logics/naming/name_nodes.pyPK!]̈(Pwemake_python_styleguide/logics/nodes.pyPK!Ai,Uwemake_python_styleguide/logics/operators.pyPK!ܖ)2Zwemake_python_styleguide/logics/tokens.pyPK!uh,A^wemake_python_styleguide/options/__init__.pyPK!A??*^wemake_python_styleguide/options/config.pyPK!,*zwemake_python_styleguide/options/defaults.pyPK!}{??,wemake_python_styleguide/presets/__init__.pyPK!ڷ tt.wemake_python_styleguide/presets/complexity.pyPK!(X+Ywemake_python_styleguide/presets/general.pyPK!R22*uwemake_python_styleguide/presets/tokens.pyPK!uh4wemake_python_styleguide/transformations/__init__.pyPK!uh8Ywemake_python_styleguide/transformations/ast/__init__.pyPK!ISi8ǎwemake_python_styleguide/transformations/ast/bugfixes.pyPK!LPP<ܕwemake_python_styleguide/transformations/ast/enhancements.pyPK!U4wemake_python_styleguide/transformations/ast_tree.pyPK!d..̺ !wemake_python_styleguide/types.pyPK!lU#wemake_python_styleguide/version.pyPK!\/Ȳwemake_python_styleguide/violations/__init__.pyPK!YFF+wemake_python_styleguide/violations/base.pyPK!R5=wemake_python_styleguide/violations/best_practices.pyPK!9CC1w[wemake_python_styleguide/violations/complexity.pyPK!B"ff2wemake_python_styleguide/violations/consistency.pyPK!cߺ ??-wemake_python_styleguide/violations/naming.pyPK!uh-Fwemake_python_styleguide/visitors/__init__.pyPK!uh1/Gwemake_python_styleguide/visitors/ast/__init__.pyPK!14Gwemake_python_styleguide/visitors/ast/annotations.pyPK!j 3Nwemake_python_styleguide/visitors/ast/attributes.pyPK!OEE1Uwemake_python_styleguide/visitors/ast/builtins.pyPK!g0iwemake_python_styleguide/visitors/ast/classes.pyPK!J4ȃwemake_python_styleguide/visitors/ast/comparisons.pyPK!uh</wemake_python_styleguide/visitors/ast/complexity/__init__.pyPK!39  ;wemake_python_styleguide/visitors/ast/complexity/classes.pyPK! >:wemake_python_styleguide/visitors/ast/complexity/counts.pyPK!k<Hwemake_python_styleguide/visitors/ast/complexity/function.pyPK!HZ| 9Awemake_python_styleguide/visitors/ast/complexity/jones.pyPK!k :Bwemake_python_styleguide/visitors/ast/complexity/nested.pyPK!q:>wemake_python_styleguide/visitors/ast/complexity/offset.pyPK!13swemake_python_styleguide/visitors/ast/conditions.pyPK!8`002wemake_python_styleguide/visitors/ast/functions.pyPK!e0@wemake_python_styleguide/visitors/ast/imports.pyPK!F""1j#wemake_python_styleguide/visitors/ast/keywords.pyPK!ha>.Fwemake_python_styleguide/visitors/ast/loops.pyPK!˗=  0b\wemake_python_styleguide/visitors/ast/modules.pyPK!d8ow'w'/cwemake_python_styleguide/visitors/ast/naming.pyPK!FQ3wemake_python_styleguide/visitors/ast/statements.pyPK!ud==)wemake_python_styleguide/visitors/base.pyPK!I0/wemake_python_styleguide/visitors/decorators.pyPK!uh7Lwemake_python_styleguide/visitors/filenames/__init__.pyPK!Dt 5wemake_python_styleguide/visitors/filenames/module.pyPK!uh6wemake_python_styleguide/visitors/tokenize/__init__.pyPK!ٝ6Rwemake_python_styleguide/visitors/tokenize/comments.pyPK! qD6uwemake_python_styleguide/visitors/tokenize/keywords.pyPK!U8wemake_python_styleguide/visitors/tokenize/primitives.pyPK!Mf8wemake_python_styleguide/visitors/tokenize/statements.pyPK!H";?9wemake_python_styleguide-0.7.1.dist-info/entry_points.txtPK!f000wemake_python_styleguide-0.7.1.dist-info/LICENSEPK!HڽTU.wemake_python_styleguide-0.7.1.dist-info/WHEELPK!HkT m1wemake_python_styleguide-0.7.1.dist-info/METADATAPK!HR0 [/*wemake_python_styleguide-0.7.1.dist-info/RECORDPKHH5