PK!uh$wemake_python_styleguide/__init__.py# -*- coding: utf-8 -*- PK!u NN#wemake_python_styleguide/checker.py# -*- coding: utf-8 -*- """ Entry point to the app. Writing new plugin ------------------ First of all, you have to decide: 1. Are you writing a separate plugin and adding it as a dependency? 2. Are you writing an built-in extension to this styleguide? How to make a decision? Will this plugin be useful to other developers without this styleguide? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If so, it would be wise to create a separate ``flake8`` plugin. Then you can add newly created plugin as a dependency. Our rules do not make any sense without each other. Real world examples: - `flake8-eradicate `_ Can this plugin be used with the existing checker? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``flake8`` has a very strict API about plugins. Here are some problems that you may encounter: - Some plugins are called once per file, some are called once per line - Plugins should define clear ``violation code`` / ``checker`` relation - It is impossible to use the same letter violation codes for several checkers Real world examples: - `flake8-broken-line `_ Writing new visitor ------------------- If you are still willing to write a builtin extension to our styleguide, you will have to write a :ref:`violation ` and/or :ref:`visitor `. Checker API ----------- .. autoclass:: Checker :members: :special-members: :exclude-members: __weakref__ """ import ast import tokenize from typing import Generator, Sequence from flake8.options.manager import OptionManager from wemake_python_styleguide import constants, types, version from wemake_python_styleguide.options.config import Configuration from wemake_python_styleguide.visitors.presets import ( complexity, general, tokens, ) class Checker(object): """ Main checker class. It is an entry point to the whole app. 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. options: option structure passed by ``flake8``. visitors: sequence of visitors that we run with this checker. """ name = version.pkg_name version = version.pkg_version config = Configuration() options: types.ConfigurationOptions visitors: Sequence[types.VisitorClass] = ( *general.GENERAL_PRESET, *complexity.COMPLEXITY_PRESET, *tokens.TOKENS_PRESET, ) def __init__( self, tree: ast.Module, 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``. file_tokens: ``tokenize.tokenize`` parsed file tokens. filename: module file name, might be empty if piping is used. See also: http://flake8.pycqa.org/en/latest/plugin-development/index.html """ self.tree = 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:`.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[types.VisitorClass], ) -> Generator[types.CheckResult, None, None]: """ Runs all passed visitors one by one. Yields: Violations that were found by the passed visitors. """ 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) -> Generator[types.CheckResult, None, None]: """ Runs the checker. This method is used by ``flake8`` API. It is executed after all configuration is parsed. """ yield from self._run_checks(self.visitors) PK!c6F %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 # TODO: use consistent `.` for the `#:` comments # TODO: use consistent names: `*_BLACKLIST` and `*_WHITELIST` #: List of functions we forbid to use. BAD_FUNCTIONS = frozenset(( # Code generation: 'eval', 'exec', 'compile', # Magic: 'globals', 'locals', 'vars', 'dir', # IO: 'input', # Attribute access: 'hasattr', 'delattr', # Misc: 'copyright', 'help', 'credits', # Dynamic imports: '__import__', # OOP: 'staticmethod', )) #: List of module metadata we forbid to use. BAD_MODULE_METADATA_VARIABLES = frozenset(( '__author__', '__all__', '__version__', '__about__', )) #: List of variable names we forbid to use. BAD_VARIABLE_NAMES = frozenset(( # Meaningless words: 'data', 'result', 'results', 'item', 'items', 'value', 'values', 'val', 'vals', 'var', 'vars', 'content', 'contents', 'info', 'handle', 'handler', 'file', 'obj', 'objects', 'objs', 'some', # Confusables: 'no', 'true', 'false', # Names from examples: 'foo', 'bar', 'baz', )) #: List of magic methods that are forbiden to use. BAD_MAGIC_METHODS = 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 = frozenset(( 'Meta', # django forms, models, drf, etc 'Params', # factoryboy specific )) #: List of nested functions' names we allow to use. NESTED_FUNCTIONS_WHITELIST = frozenset(( 'decorator', 'factory', )) #: List of allowed ``__future__`` imports. FUTURE_IMPORTS_WHITELIST = frozenset(( 'annotations', 'generator_stop', )) #: List of blacklisted module names: BAD_MODULE_NAMES = frozenset(( 'util', 'utils', 'utilities', 'helpers', )) #: List of allowed module magic names: MAGIC_MODULE_NAMES_WHITELIST = frozenset(( '__init__', '__main__', )) #: Regex pattern to name modules: MODULE_NAME_PATTERN = 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 = frozenset(( 0.5, 100, 1000, 1024, # bytes 24, # hours 60, # seconds, minutes )) # Internal variables # They are not publicly documented since they are not used by the end user. # This variable is used as a default filename, when it is not passed by flake8: STDIN = 'stdin' # TODO: rename to `INIT_MODULE` # This variable is used to specify as a placeholder for `__init__.py`: INIT = '__init__' PK!uh+wemake_python_styleguide/logics/__init__.py# -*- coding: utf-8 -*- PK!,;,wemake_python_styleguide/logics/filenames.py# -*- coding: utf-8 -*- from pathlib import PurePath from typing import Iterable from typing.re import Pattern from wemake_python_styleguide import constants from wemake_python_styleguide.options import defaults def _get_stem(file_path: str) -> str: return PurePath(file_path).stem def is_stem_in_list(file_path: str, to_check: Iterable[str]) -> bool: """ Checks whether module's name is included in a search list. >>> is_stem_in_list('/some/module.py', ['other']) False >>> is_stem_in_list('partial/module.py', ['module']) True >>> is_stem_in_list('module.py', ['module']) True >>> is_stem_in_list('C:/User/package/__init__.py', ['__init__']) True """ return _get_stem(file_path) in to_check def is_magic(file_path: str) -> bool: """ Checks whether the given `file_path` contains the magic module name. >>> is_magic('__init__.py') True >>> is_magic('some.py') False >>> is_magic('/home/user/cli.py') False >>> is_magic('/home/user/__version__.py') True >>> is_magic('D:/python/__main__.py') True """ stem = _get_stem(file_path) return stem.startswith('__') and stem.endswith('__') def is_too_short_stem( file_path: str, min_length: int = defaults.MIN_MODULE_NAME_LENGTH, ) -> bool: """ Checks whether the file's stem fits into the minimum length. >>> is_too_short_stem('a.py') True >>> is_too_short_stem('prefix/b.py') True >>> is_too_short_stem('regular.py') False >>> is_too_short_stem('c:/package/abc.py', min_length=4) True """ stem = _get_stem(file_path) return len(stem) < min_length def is_matching_pattern( file_path: str, pattern: Pattern = constants.MODULE_NAME_PATTERN, ) -> bool: r""" Checks whether the file's stem matches the given pattern. >>> is_matching_pattern('some.py') True >>> is_matching_pattern('__init__.py') True >>> is_matching_pattern('MyModule.py') False >>> import re >>> is_matching_pattern('123.py', pattern=re.compile(r'\d{3}')) True """ stem = _get_stem(file_path) return pattern.match(stem) is not None PK!s,wemake_python_styleguide/logics/functions.py# -*- coding: utf-8 -*- from ast import Call from typing import Iterable, Optional def given_function_called(node: Call, to_check: Iterable[str]) -> str: """ Returns function name if it is called and contained in the `to_check`. >>> import ast >>> module = ast.parse('print("some value")') >>> given_function_called(module.body[0].value, ['print']) 'print' """ function_name = getattr(node.func, 'id', None) function_value = getattr(node.func, 'value', None) function_inner_id = getattr(function_value, 'id', None) function_attr = getattr(node.func, 'attr', None) is_restricted_function_attribute = ( function_inner_id in to_check and function_attr in to_check ) if function_name in to_check or is_restricted_function_attribute: 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('') False """ return function_type in ['method', 'classmethod'] PK!\rr*wemake_python_styleguide/logics/imports.py# -*- coding: utf-8 -*- import ast from wemake_python_styleguide.types import AnyImport def get_error_text(node: AnyImport) -> str: """Returns correct error text for import nodes.""" module = getattr(node, 'module', None) if module is not None: return module if isinstance(node, ast.Import): return node.names[0].name return '.' PK!%%(wemake_python_styleguide/logics/nodes.py# -*- coding: utf-8 -*- import ast from typing import Iterable, Type def is_subtype_of_any( node: ast.AST, to_check: Iterable[Type[ast.AST]], ) -> bool: """ Checks whether the given node is subtype of any of the provided types. >>> import ast >>> node = ast.parse('') # ast.Module >>> is_subtype_of_any(node, [ast.Str, ast.Name]) False >>> is_subtype_of_any(node, [ast.Module]) True >>> is_subtype_of_any(node, []) False """ return any(isinstance(node, class_) for class_ in to_check) PK!aZ,wemake_python_styleguide/logics/variables.py# -*- coding: utf-8 -*- from typing import Iterable, Optional from wemake_python_styleguide.options.defaults import MIN_VARIABLE_LENGTH def is_wrong_variable_name(name: str, to_check: Iterable[str]) -> bool: """ Checks that variable is not prohibited by explicitly listing it's name. >>> is_wrong_variable_name('wrong', ['wrong']) True >>> is_wrong_variable_name('correct', ['wrong']) False >>> is_wrong_variable_name('_wrong', ['wrong']) True >>> is_wrong_variable_name('wrong_', ['wrong']) True >>> is_wrong_variable_name('wrong__', ['wrong']) False >>> is_wrong_variable_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_too_short_variable_name( name: Optional[str], min_length: int = MIN_VARIABLE_LENGTH, ) -> bool: """ Checks for too short variable names. >>> is_too_short_variable_name('test') False >>> is_too_short_variable_name(None) False >>> is_too_short_variable_name('o') True >>> is_too_short_variable_name('_') False >>> is_too_short_variable_name('z1') False >>> is_too_short_variable_name('z', min_length=1) False """ return name is not None and name != '_' and len(name) < min_length def is_private_variable(name: Optional[str]) -> bool: """ Checks if variable has private name pattern. >>> is_private_variable(None) False >>> is_private_variable('regular') False >>> is_private_variable('__private') True >>> is_private_variable('_protected') False >>> is_private_variable('__magic__') False """ return ( name is not None and name.startswith('__') and not name.endswith('__') ) PK!uh,wemake_python_styleguide/options/__init__.py# -*- coding: utf-8 -*- PK! ԗ*wemake_python_styleguide/options/config.py# -*- coding: utf-8 -*- from typing import Dict, Optional, Sequence, Union import attr from flake8.options.manager import OptionManager from wemake_python_styleguide.options import defaults ConfigValues = Dict[str, Union[str, int, bool]] @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' 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-variable-length`` - minimum number of chars to define a valid variable name, defaults to :str:`wemake_python_styleguide.options.defaults.MIN_VARIABLE_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 module names related checks: - ``min-module-name-length`` - minimum required module's name length, defaults to :str:`wemake_python_styleguide.options.defaults.MIN_MODULE_NAME_LENGTH` 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-offset-blocks`` - maximum number of block to nest expressions, defaults to :str:`wemake_python_styleguide.options.defaults.MAX_OFFSET_BLOCKS` - ``max-elifs`` - maximum number of ``elif`` blocks, defaults to :str:`wemake_python_styleguide.options.defaults.MAX_ELIFS` - `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-conditions`` - maximum number of boolean conditions in a single ``if`` or ``while`` node, defaults to :str:`wemake_python_styleguide.options.defaults.MAX_CONDITIONS` All options are configurable via ``flake8`` CLI: Example:: flake8 --max-returns=2 --max-elifs=2 Or you can provide options in ``tox.ini`` or ``setup.cfg``: Example:: [flake8] max-returns = 2 max-elifs = 2 We use ``setup.cfg`` as a default way to provide configuration. """ options: 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-offset-blocks', defaults.MAX_OFFSET_BLOCKS, 'Maximum number of blocks to nest different structures.', ), _Option( '--max-elifs', defaults.MAX_ELIFS, 'Maximum number of `elif` blocks.', ), _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-conditions', defaults.MAX_CONDITIONS, 'Maximum number of conditions in a `if` or `while` node.', ), # General: _Option( '--min-variable-length', defaults.MIN_VARIABLE_LENGTH, 'Minimum required length of the variable name.', ), _Option( '--i-control-code', defaults.I_CONTROL_CODE, 'Whether you control ones who use your code.', action='store_true', type=None, ), # File names: _Option( '--min-module-name-length', defaults.MIN_MODULE_NAME_LENGTH, "Minimum required module's name length", ), ] 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. """ # General #: Minimum variable's name length: MIN_VARIABLE_LENGTH = 2 #: Whether you control ones who use your code: I_CONTROL_CODE = True # Complexity #: Maximum number of `return` statements allowed in a single function: MAX_RETURNS = 5 #: Maximum number of local variables in a function: MAX_LOCAL_VARIABLES = 5 #: Maximum number of expressions in a single function: MAX_EXPRESSIONS = 9 #: Maximum number of arguments for functions or method, `self` is not counted: MAX_ARGUMENTS = 5 #: Maximum number of blocks to nest different structures: MAX_OFFSET_BLOCKS = 5 #: Maximum number of `elif` blocks in a single `if` condition: MAX_ELIFS = 3 #: Maximum number of classes and functions in a single module: MAX_MODULE_MEMBERS = 7 #: Maximum number of methods in a single class: MAX_METHODS = 7 #: Maximum line complexity: MAX_LINE_COMPLEXITY = 14 # 7 * 2, also almost guessed #: Maximum median module Jones complexity: MAX_JONES_SCORE = 12 # this value was "guessed" based on existing source code #: Maximum number of imports in a single module: MAX_IMPORTS = 12 #: Maximum number of conditions in a single ``if`` or ``while`` statement: MAX_CONDITIONS = 4 # Modules #: Minimum required module's name length: MIN_MODULE_NAME_LENGTH = 3 PK!tV!wemake_python_styleguide/types.py# -*- coding: utf-8 -*- """ This module contains custom ``mypy`` types that we commonly use. 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 """ import ast from typing import TYPE_CHECKING, Tuple, Type, Union if TYPE_CHECKING: # pragma: no cover from typing_extensions import Protocol # noqa: Z435 # This solves cycle imports problem: from .visitors import base # noqa: F401,Z300,Z435 else: # We do not need to do anything if type checker is not working: Protocol = object #: Visitor type definition: VisitorClass = Type['base.BaseVisitor'] #: 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] #: Flake8 API format to return error messages: CheckResult = Tuple[int, int, str, type] class ConfigurationOptions(Protocol): """ Provides structure for the options we use in our checker. Then this protocol is passed to each individual visitor and used there. It uses structural sub-typing, and does not represent any kind of a real class or structure. This class actually works only when running type check. At other cases it is just an ``object``. See also: https://mypy.readthedocs.io/en/latest/protocols.html """ # General: min_variable_length: int i_control_code: bool # Complexity: max_arguments: int max_local_variables: int max_returns: int max_expressions: int max_offset_blocks: int max_elifs: int max_module_members: int max_methods: int max_line_complexity: int max_jones_score: int max_imports: int max_conditions: int # File names: min_module_name_length: int PK!.m#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: str = _get_version(pkg_name) PK!uh/wemake_python_styleguide/violations/__init__.py# -*- coding: utf-8 -*- PK!E&+wemake_python_styleguide/violations/base.py# -*- coding: utf-8 -*- """ Contains detailed information about violation and how to use them. .. _violations: Writing new violation --------------------- First of all, you have to select the correct base class for new violation. The main criteria is what logic will be used to find the flaw in your code. .. currentmodule:: wemake_python_styleguide.violations.base Available base classes ~~~~~~~~~~~~~~~~~~~~~~ .. autosummary:: :nosignatures: ASTViolation TokenizeViolation SimpleViolation Violation can not have more than one base class. Since it does not make sense to have two different node types at the same time. Violations API -------------- """ import ast import tokenize from typing import Tuple, Union #: General type for all possible nodes where error happens. ErrorNode = Union[ ast.AST, tokenize.TokenInfo, None, ] class BaseStyleViolation(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. should_use_text: formatting option. Some do not require extra text. """ error_template: str code: int should_use_text: bool = True 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 if text is None: self._text = node.__class__.__name__.lower() else: self._text = text 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 def message(self) -> str: """ Returns error's formatted message with code and reason. Conditionally formats the ``error_template`` if it is required. """ if self.should_use_text: message = self.error_template.format(self._text) else: message = self.error_template return '{0} {1}'.format(self._full_code(), message) def node_items(self) -> Tuple[int, int, str]: """Returns tuple to match ``flake8`` API format.""" return (*self._location(), self.message()) class ASTViolation(BaseStyleViolation): """Violation for ``ast`` based style visitors.""" _node: ast.AST 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 TokenizeViolation(BaseStyleViolation): """Violation for ``tokenize`` based visitors.""" _node: tokenize.TokenInfo def _location(self) -> Tuple[int, int]: return self._node.start class SimpleViolation(BaseStyleViolation): """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! 995wemake_python_styleguide/violations/best_practices.py# -*- coding: utf-8 -*- """ These checks ensures that you follow the best practices. Note: Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Readability counts. Special cases aren't special enough to break the rules. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. .. currentmodule:: wemake_python_styleguide.violations.best_practices Summary ------- .. autosummary:: :nosignatures: WrongMagicCommentViolation WrongDocCommentViolation WrongModuleMetadataViolation EmptyModuleViolation InitModuleHasLogicViolation WrongKeywordViolation WrongFunctionCallViolation FutureImportViolation RaiseNotImplementedViolation NestedFunctionViolation NestedClassViolation MagicNumberViolation StaticMethodViolation BadMagicMethodViolation NestedImportViolation Comments -------- .. autoclass:: WrongMagicCommentViolation .. autoclass:: WrongDocCommentViolation Modules ------- .. autoclass:: WrongModuleMetadataViolation .. autoclass:: EmptyModuleViolation .. autoclass:: InitModuleHasLogicViolation Builtins -------- .. autoclass:: WrongKeywordViolation .. autoclass:: WrongFunctionCallViolation .. autoclass:: FutureImportViolation .. autoclass:: RaiseNotImplementedViolation Design ------ .. autoclass:: NestedFunctionViolation .. autoclass:: NestedClassViolation .. autoclass:: MagicNumberViolation .. autoclass:: StaticMethodViolation .. autoclass:: BadMagicMethodViolation .. autoclass:: NestedImportViolation """ from wemake_python_styleguide.violations.base import ( ASTViolation, SimpleViolation, TokenizeViolation, ) 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 # Wrong: type = MyClass.get_type() # noqa coordinate = 10 # type: int Note: Returns Z400 as error code """ code = 400 #: Error message shown to the user. error_template = 'Found wrong magic comment: {0}' 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'] Note: Returns Z401 as error code """ code = 401 should_use_text = False #: Error message shown to the user. error_template = 'Found wrong doc comment' # Modules: 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.BAD_MODULE_METADATA_VARIABLES` for full list of bad names. Example:: # Wrong: __author__ = 'Nikita Sobolev' __version__ = 0.1.2 Note: Returns Z410 as error code """ #: Error message shown to the user. error_template = 'Found wrong metadata variable {0}' code = 410 class EmptyModuleViolation(ASTViolation): """ Forbids to have empty modules. Reasoning: Why is it even there? Do not polute 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 Note: Returns Z411 as error code """ should_use_text = False #: Error message shown to the user. error_template = 'Found empty module' code = 411 class InitModuleHasLogicViolation(ASTViolation): """ 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 Note: Returns Z412 as error code """ should_use_text = False #: Error message shown to the user. error_template = 'Found `__init__` module with logic' code = 412 # Modules: 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 Note: Returns Z420 as error code """ #: Error message shown to the user. error_template = 'Found wrong keyword "{0}"' code = 420 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.BAD_FUNCTIONS` for the full list of blacklisted functions. See also: https://www.youtube.com/watch?v=YjHsOrOOSuI Note: Returns Z421 as error code """ #: Error message shown to the user. error_template = 'Found wrong function call "{0}"' code = 421 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 Note: Returns Z422 as error code """ #: Error message shown to the user. error_template = 'Found future import "{0}"' code = 422 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 See Also: https://stackoverflow.com/a/44575926/4842742 Note: Returns Z423 as error code """ should_use_text = False #: Error message shown to the user. error_template = 'Found raise NotImplemented' code = 423 # Design: 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(): ... Note: Returns Z430 as error code """ #: Error message shown to the user. error_template = 'Found nested function "{0}"' code = 430 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): ... Note: Returns Z431 as error code """ #: Error message shown to the user. error_template = 'Found nested class "{0}"' code = 431 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` See also: https://en.wikipedia.org/wiki/Magic_number_(programming) Note: Returns Z432 as error code """ code = 432 #: Error message shown to the user. error_template = 'Found magic number: {0}' 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. Note: Returns Z433 as error code """ should_use_text = False #: Error message shown to the user. error_template = 'Found using `@staticmethod`' code = 433 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 you code to use custom methods instead. It will give more context to your app. See :py:data:`~wemake_python_styleguide.constants.BAD_MAGIC_METHODS` for the full blacklist of the magic methods. See also: https://www.youtube.com/watch?v=F6u5rhUQ6dU Note: Returns Z434 as error code """ #: Error message shown to the user. error_template = 'Found using restricted magic method "{0}"' code = 434 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 you 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 See also: https://github.com/seddonym/layer_linter Note: Returns Z435 as error code """ #: Error message shown to the user. error_template = 'Found nested import "{0}"' code = 435 PK! &331wemake_python_styleguide/violations/complexity.py# -*- coding: utf-8 -*- """ These checks finds 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. Flat is better than nested. Namespaces are one honking great idea -- let's do more of those! .. currentmodule:: wemake_python_styleguide.violations.complexity Summary ------- .. autosummary:: :nosignatures: JonesScoreViolation TooManyImportsViolation TooManyModuleMembersViolation TooManyLocalsViolation TooManyArgumentsViolation TooManyReturnsViolation TooManyExpressionsViolation TooManyMethodsViolation TooDeepNestingViolation LineComplexityViolation TooManyConditionsViolation TooManyElifsViolation Module complexity ----------------- .. autoclass:: JonesScoreViolation .. autoclass:: TooManyImportsViolation .. autoclass:: TooManyModuleMembersViolation Function and class complexity ----------------------------- .. autoclass:: TooManyLocalsViolation .. autoclass:: TooManyArgumentsViolation .. autoclass:: TooManyReturnsViolation .. autoclass:: TooManyExpressionsViolation .. autoclass:: TooManyMethodsViolation Structures complexity --------------------- .. autoclass:: TooDeepNestingViolation .. autoclass:: LineComplexityViolation .. autoclass:: TooManyConditionsViolation .. autoclass:: TooManyElifsViolation """ from wemake_python_styleguide.violations.base import ( ASTViolation, SimpleViolation, ) 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. See also: https://github.com/Miserlou/JonesComplexity This rule is configurable with ``--max-module-score``. Note: Returns Z200 as error code """ should_use_text = False #: Error message shown to the user. error_template = 'Found module with high Jones Complexity score' code = 200 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 ...``. This rule is configurable with ``--max-imports``. Note: Returns Z201 as error code """ #: Error message shown to the user. error_template = 'Found module with too many imports: {0}' code = 201 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. This rule is configurable with ``--max-module-members``. Note: Returns Z202 as error code """ should_use_text = False #: Error message shown to the user. error_template = 'Found too many module members' code = 202 # Functions and classes: 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 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. 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. This rule is configurable with ``--max-local-variables``. Note: Returns Z210 as error code """ #: Error message shown to the user. error_template = 'Found too many local variables "{0}"' code = 210 class TooManyArgumentsViolation(ASTViolation): """ Forbids to have too many arguments for a function or method. Reasoning: This is an indicator of a bad design. When 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. This rule is configurable with ``--max-arguments``. Note: Returns Z211 as error code """ #: Error message shown to the user. error_template = 'Found too many arguments "{0}"' code = 211 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. This rule is configurable with ``--max-returns``. Note: Returns Z212 as error code """ #: Error message shown to the user. error_template = 'Found too many return statements "{0}"' code = 212 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. This rule is configurable with ``--max-expressions``. Note: Returns Z213 as error code """ #: Error message shown to the user. error_template = 'Found too many expressions "{0}"' code = 213 class TooManyMethodsViolation(SimpleViolation): """ 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. See: https://en.wikipedia.org/wiki/God_object 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 attributes of a class. This rule is configurable with ``--max-methods``. Note: Returns Z214 as error code """ #: Error message shown to the user. error_template = 'Found too many methods "{0}"' code = 214 # Structures: class TooDeepNestingViolation(ASTViolation): """ Forbids nesting blocks too deep. Reasoning: If nesting is too deep that indicates usage of a 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. This rule is configurable with ``--max-offset-blocks``. Note: Returns Z220 as error code """ #: Error message shown to the user. error_template = 'Found too deep nesting "{0}"' code = 220 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 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. See also: https://github.com/Miserlou/JonesComplexity This rule is configurable with ``--max-line-complexity``. Note: Returns Z221 as error code """ #: Error message shown to the user. error_template = 'Found line with high Jones Complexity: {0}' code = 221 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 only check ``if`` and ``while`` nodes for this type of complexity. We check ``if`` nodes inside list comprehensions and ternary expressions. We count ``and`` and ``or`` keywords as conditions. Example:: # The next line has 2 conditions: if x_coord > 1 and x_coord < 10: ... This rule is configurable with ``--max-conditions``. Note: Returns Z222 as error code """ #: Error message shown to the user. error_template = 'Found a condition with too much logic: {0}' code = 222 class TooManyElifsViolation(ASTViolation): """ Forbids to use many ``elif`` branches. Reasoning: This rule is specifically important, because many ``elif`` branches indicate a complex flow in your design: you are reimplementing ``switch`` in python. Solution: There are different design patters to use instead. For example, you can use some interface that just call a specific method without ``if``. This rule is configurable with ``--max-elifs``. Note: Returns Z223 as error code """ should_use_text = False #: Error message shown to the user. error_template = 'Found too many `elif` branches' code = 223 PK! ,,2wemake_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. Note: Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. .. currentmodule:: wemake_python_styleguide.violations.consistency Summary ------- .. autosummary:: :nosignatures: LocalFolderImportViolation DottedRawImportViolation UnicodeStringViolation UnderscoredNumberViolation PartialFloatViolation FormattedStringViolation RequiredBaseClassViolation MultipleIfsInComprehensionViolation Consistency checks ------------------ .. autoclass:: LocalFolderImportViolation .. autoclass:: DottedRawImportViolation .. autoclass:: UnicodeStringViolation .. autoclass:: UnderscoredNumberViolation .. autoclass:: PartialFloatViolation .. autoclass:: FormattedStringViolation .. autoclass:: RequiredBaseClassViolation .. autoclass:: MultipleIfsInComprehensionViolation """ from wemake_python_styleguide.violations.base import ( ASTViolation, TokenizeViolation, ) 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. Example:: # Correct: from my_package.version import get_version # Wrong: from .version import get_version from ..drivers import MySQLDriver Note: Returns Z300 as error code """ #: Error message shown to the user. error_template = 'Found local folder import "{0}"' code = 300 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 Note: Returns Z301 as error code """ #: Error message shown to the user. error_template = 'Found dotted raw import "{0}"' code = 301 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' Note: Returns Z302 as error code """ code = 302 #: Error message shown to the user. error_template = 'Found unicode string prefix: {0}' 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 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 Note: Returns Z303 as error code """ code = 303 #: Error message shown to the user. error_template = 'Found underscored number: {0}' 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. Note: Returns Z304 as error code """ code = 304 #: Error message shown to the user. error_template = 'Found partial float: {0}' class FormattedStringViolation(ASTViolation): """ Forbids to use ``f`` strings. Reasoning: ``f`` strings looses 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') Note: Returns Z305 as error code """ should_use_text = False #: Error message shown to the user. error_template = 'Found `f` string' code = 305 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: ... Note: Returns Z306 as error code """ #: Error message shown to the user. error_template = 'Found class without a base class "{0}"' code = 306 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')] Note: Returns Z307 as error code """ should_use_text = False #: Error message shown to the user. error_template = 'Found list comprehension with multiple `if`s' code = 307 PK!V)V)-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. Note: Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Readability counts. Namespaces are one honking great idea -- let's do more of those! 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 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 are not allowed - When writing abbreviations in ``UpperCase`` capitalize all letters: ``HTTPAddress`` - When writting abbreviations in ``snake_case`` use lowercase: ``http_address`` - When writting numbers in ``snake_case`` do not use extra ``_`` as in ``http2_protocol`` Packages ~~~~~~~~ - Packages should use ``snake_case`` - One word for a package is the most prefitable name Modules ~~~~~~~ - Modules should use ``snake_case`` - Module names should not be too short - Module names should not overuse magic names - Module names should be valid Python variable names Classes ~~~~~~~ - Classes should use ``UpperCase`` - Python's built-in classes, however are typically lowercase words - Exception classes should end with ``Error`` Instance attributes ~~~~~~~~~~~~~~~~~~~ - Instance attributes should use ``snake_case`` with no exceptions Class attributes ~~~~~~~~~~~~~~~~ - Class attributes should use ``snake_case`` with no exceptions Functions and methods ~~~~~~~~~~~~~~~~~~~~~ - Functions and methods should use ``snake_case`` with no exceptions Method arguments ~~~~~~~~~~~~~~~~ - Instance methods should have their first argument named ``self`` - Class methods should have their first argument named ``cls`` - Metaclass methods should have their first argument named ``mcs`` - When argument is unused it should be prefixed with an underscore - 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 might be separated from other arguments with ``*`` Global (module level) variables ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Global variables should use ``CONSTANT_CASE`` - Unless other is required by the API, example: ``urlpatterns`` in Django Variables ~~~~~~~~~ - Variables should use ``snake_case`` - When some variable is unused it should be prefixed with an underscore Type aliases ~~~~~~~~~~~~ - Should use ``UpperCase`` as real classes - Should not contain word ``type`` in its name - Generic types should be called ``TT`` or ``KK`` or ``VV`` - 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 TooShortModuleNameViolation WrongModuleNameUnderscoresViolation WrongModuleNamePatternViolation WrongVariableNameViolation TooShortVariableNameViolation PrivateNameViolation SameAliasImportViolation Module names ------------ .. autoclass:: WrongModuleNameViolation .. autoclass:: WrongModuleMagicNameViolation .. autoclass:: TooShortModuleNameViolation .. autoclass:: WrongModuleNameUnderscoresViolation .. autoclass:: WrongModuleNamePatternViolation Variable names -------------- .. autoclass:: WrongVariableNameViolation .. autoclass:: TooShortVariableNameViolation .. autoclass:: PrivateNameViolation .. autoclass:: SameAliasImportViolation """ from wemake_python_styleguide.violations.base import ( ASTViolation, SimpleViolation, ) 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.BAD_MODULE_NAMES` for the full list of bad module names. Example:: # Correct: github.py views.py # Wrong: utils.py helpers.py Note: Returns Z100 as error code """ should_use_text = False #: Error message shown to the user. error_template = 'Found wrong module name' code = 100 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 Note: Returns Z101 as error code """ should_use_text = False #: Error message shown to the user. error_template = 'Found wrong module magic name' code = 101 class TooShortModuleNameViolation(SimpleViolation): """ Forbids to use module name shorter than some breakpoint. Reasoning: Too short module names are not expressive enough. We will have to open the code to find out what is going on there. Solution: Rename the module. This rule is configurable with ``--min-module-name-length``. Note: Returns Z102 as error code """ should_use_text = False #: Error message shown to the user. error_template = 'Found too short module name' code = 102 class WrongModuleNameUnderscoresViolation(SimpleViolation): """ Forbids to use multiple underscores in a row in a module name. Reasoning: It is hard to tell how many underscores are there: two or three? Solution: Keep just one underscore in a module name. Example:: # Correct: __init__.py some_module_name.py test.py # Wrong: some__wrong__name.py my__module.py __fake__magic__.py Note: Returns Z103 as error code """ should_use_text = False #: Error message shown to the user. error_template = 'Found repeating underscores in a module name' code = 103 class WrongModuleNamePatternViolation(SimpleViolation): """ Forbids to use module names that do not match our pattern. Reasoning: 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 Note: Returns Z104 as error code """ should_use_text = False #: Error message shown to the user. error_template = 'Found incorrect module name pattern' code = 104 # Variables 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 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.BAD_VARIABLE_NAMES` for the full list of blacklisted variable names. Example:: # Correct: html_node_item = None # Wrong: item = None Note: Returns Z110 as error code """ #: Error message shown to the user. error_template = 'Found wrong variable name "{0}"' code = 110 class TooShortVariableNameViolation(ASTViolation): """ Forbids to have too short variable names. Reasoning: It is hard to understand what the variable means and why it is used, if it's name is too short. Solution: Think of another name. Give more context to it. This rule is configurable with ``--min-variable-length``. Example:: # Correct: x_coordinate = 1 abscissa = 2 # Wrong: x = 1 y = 2 Note: Returns Z111 as error code """ #: Error message shown to the user. error_template = 'Found too short name "{0}"' code = 111 class PrivateNameViolation(ASTViolation): """ 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: variables, attributes, functions, and methods. Example:: # Correct: def _collect_coverage(self): ... # Wrong: def __collect_coverage(self): ... Note: Returns Z112 as error code """ #: Error message shown to the user. error_template = 'Found private name pattern "{0}"' code = 112 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 Note: Returns Z113 as error code """ #: Error message shown to the user. error_template = 'Found same alias import "{0}"' code = 113 PK!uh-wemake_python_styleguide/visitors/__init__.py# -*- coding: utf-8 -*- PK!uh1wemake_python_styleguide/visitors/ast/__init__.py# -*- coding: utf-8 -*- PK!Y>0wemake_python_styleguide/visitors/ast/classes.py# -*- coding: utf-8 -*- import ast from wemake_python_styleguide.constants import BAD_MAGIC_METHODS from wemake_python_styleguide.types import AnyFunctionDef from wemake_python_styleguide.violations.best_practices import ( BadMagicMethodViolation, StaticMethodViolation, ) from wemake_python_styleguide.violations.consistency import ( RequiredBaseClassViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor from wemake_python_styleguide.visitors.decorators import alias @alias('visit_any_function', ( 'visit_FunctionDef', 'visit_AsyncFunctionDef', )) class WrongClassVisitor(BaseNodeVisitor): """ This class is responsible for restricting some ``class`` antipatterns. Here we check for stylistic issues and design patterns. """ def _check_decorators(self, node: AnyFunctionDef) -> None: for decorator in node.decorator_list: decorator_name = getattr(decorator, 'id', None) if decorator_name == 'staticmethod': # TODO: refactor magic str self.add_violation(StaticMethodViolation(node)) def _check_magic_methods(self, node: AnyFunctionDef) -> None: if node.name in BAD_MAGIC_METHODS: self.add_violation(BadMagicMethodViolation(node, text=node.name)) def _check_base_class(self, node: ast.ClassDef) -> None: if len(node.bases) == 0: self.add_violation(RequiredBaseClassViolation(node, text=node.name)) def visit_ClassDef(self, node: ast.ClassDef) -> None: """ Checking class definitions. Raises: RequiredBaseClassViolation """ self._check_base_class(node) self.generic_visit(node) def visit_any_function(self, node: AnyFunctionDef) -> None: """ Checking class methods: async and regular. Raises: StaticMethodViolation BadMagicMethodViolation """ self._check_decorators(node) self._check_magic_methods(node) self.generic_visit(node) PK!uh<wemake_python_styleguide/visitors/ast/complexity/__init__.py# -*- coding: utf-8 -*- PK!AA:wemake_python_styleguide/visitors/ast/complexity/counts.py# -*- coding: utf-8 -*- import ast from collections import defaultdict from typing import DefaultDict, Union from wemake_python_styleguide.logics.functions import is_method from wemake_python_styleguide.types import AnyFunctionDef, AnyImport from wemake_python_styleguide.violations.complexity import ( TooManyConditionsViolation, 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] @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.""" parent = getattr(node, 'parent', None) is_real_method = is_method(getattr(node, 'function_type', None)) if isinstance(parent, ast.Module) and not is_real_method: self._public_items_count += 1 def _post_visit(self) -> None: if self._public_items_count > self.options.max_module_members: self.add_violation(TooManyModuleMembersViolation()) def visit_module_members(self, node: ModuleMembers) -> None: """ Counts the number of ModuleMembers in a single module. Raises: TooManyModuleMembersViolation """ self._check_members_count(node) self.generic_visit(node) @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) @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 = getattr(node, 'parent', None) 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(text=node.name)) 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) @alias('visit_condition', ( 'visit_While', 'visit_IfExp', 'visit_If', )) class ConditionsVisitor(BaseNodeVisitor): """Checks ``if`` and ``while`` statements for condition counts.""" def __init__(self, *args, **kwargs) -> None: """Creates a counter for tracked conditions.""" super().__init__(*args, **kwargs) self._conditions: DefaultDict[ast.AST, int] = defaultdict(int) def _check_conditions(self, node: ast.AST) -> None: for condition in ast.walk(node): if isinstance(condition, (ast.And, ast.Or)): self._conditions[node] += 1 def _post_visit(self) -> None: for node, count in self._conditions.items(): if count > self.options.max_conditions - 1: self.add_violation( TooManyConditionsViolation(node, text=str(count)), ) def visit_comprehension(self, node: ast.comprehension) -> None: """ Counts the number of conditions in list comprehensions. Raises: TooManyConditionsViolation """ if node.ifs: # We only check the first `if`, since it is forbidden # to have more than one at a time # by `MultipleIfsInComprehensionViolation` self._check_conditions(node.ifs[0]) self.generic_visit(node) def visit_condition(self, node: ConditionNodes) -> None: """ Counts the number of conditions. Raises: TooManyConditionsViolation """ self._check_conditions(node.test) self.generic_visit(node) PK!_cdd<wemake_python_styleguide/visitors/ast/complexity/function.py# -*- coding: utf-8 -*- import ast from collections import defaultdict from typing import DefaultDict, List from wemake_python_styleguide.logics.functions import is_method from wemake_python_styleguide.types import AnyFunctionDef from wemake_python_styleguide.violations.complexity import ( TooManyArgumentsViolation, TooManyElifsViolation, TooManyExpressionsViolation, TooManyLocalsViolation, TooManyReturnsViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor from wemake_python_styleguide.visitors.decorators import alias FunctionCounter = DefaultDict[AnyFunctionDef, int] class _ComplexityCounter(object): """Helper class to encapsulate logic from the visitor.""" def __init__(self) -> None: self.arguments: FunctionCounter = defaultdict(int) self.elifs: FunctionCounter = 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_name: str, ) -> None: """ Increases the counter of local variables. What is treated as a local variable? Check ``TooManyLocalsViolation`` documentation. """ function_variables = self.variables[function] if variable_name not in function_variables and variable_name != '_': function_variables.append(variable_name) def _update_elifs(self, node: AnyFunctionDef, sub_node: ast.If) -> None: has_elif = any( isinstance(if_node, ast.If) for if_node in sub_node.orelse ) if has_elif: self.elifs[node] += 1 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.id) elif isinstance(sub_node, ast.Return): self.returns[node] += 1 elif isinstance(sub_node, ast.Expr): self.expressions[node] += 1 elif isinstance(sub_node, ast.If): self._update_elifs(node, sub_node) def check_arguments_count(self, node: AnyFunctionDef) -> None: """Checks the number of the arguments in a function.""" counter = 0 has_extra_arg = 0 if is_method(getattr(node, 'function_type', None)): has_extra_arg = 1 counter += len(node.args.args) + len(node.args.kwonlyargs) if node.args.vararg: counter += 1 if node.args.kwarg: counter += 1 self.arguments[node] = counter - has_extra_arg 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) @alias('visit_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 5. Number of `elif` branches """ def __init__(self, *args, **kwargs) -> None: """Creates a counter for tracked metrics.""" super().__init__(*args, **kwargs) self._counter = _ComplexityCounter() def _check_possible_switch(self) -> None: for node, elifs in self._counter.elifs.items(): if elifs > self.options.max_elifs: self.add_violation(TooManyElifsViolation(node)) 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=node.name), ) for node, expressions in self._counter.expressions.items(): if expressions > self.options.max_expressions: self.add_violation( TooManyExpressionsViolation(node, text=node.name), ) 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=node.name), ) def _post_visit(self) -> None: self._check_function_signature() self._check_function_internals() self._check_possible_switch() def visit_function(self, node: AnyFunctionDef) -> None: """ Checks function's internal complexity. Raises: TooManyExpressionsViolation TooManyReturnsViolation TooManyLocalsViolation TooManyArgumentsViolation TooManyElifsViolation """ self._counter.check_arguments_count(node) self._counter.check_function_complexity(node) self.generic_visit(node) PK!:jr 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.logics.nodes import is_subtype_of_any from wemake_python_styleguide.violations.complexity import ( JonesScoreViolation, LineComplexityViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor class JonesComplexityVisitor(BaseNodeVisitor): # TODO: consider `logical_line` """ 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()) 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 = is_subtype_of_any(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!jsg g :wemake_python_styleguide/visitors/ast/complexity/nested.py# -*- coding: utf-8 -*- import ast from wemake_python_styleguide.constants import ( NESTED_CLASSES_WHITELIST, NESTED_FUNCTIONS_WHITELIST, ) from wemake_python_styleguide.types import AnyFunctionDef 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 @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 = ( ast.FunctionDef, ast.AsyncFunctionDef, ) def _check_nested_function(self, node: AnyFunctionDef) -> None: parent = getattr(node, 'parent', None) is_inside_function = isinstance(parent, 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 = getattr(node, 'parent', None) 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: parent = getattr(node, 'parent', None) if isinstance(parent, ast.Lambda): self.add_violation(NestedFunctionViolation(node)) 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!H:wemake_python_styleguide/visitors/ast/complexity/offset.py# -*- coding: utf-8 -*- import ast from wemake_python_styleguide.violations.complexity import ( TooDeepNestingViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor from wemake_python_styleguide.visitors.decorators import alias @alias('visit_line_expression', ( 'visit_Try', 'visit_ExceptHandler', 'visit_Expr', 'visit_For', 'visit_With', 'visit_While', 'visit_If', 'visit_Raise', 'visit_Return', 'visit_Continue', 'visit_Break', 'visit_Assign', 'visit_Expr', 'visit_AsyncFor', 'visit_AsyncWith', 'visit_Await', )) class OffsetVisitor(BaseNodeVisitor): """Checks offset values for several nodes.""" def _check_offset(self, node: ast.AST) -> None: offset = getattr(node, 'col_offset', None) if offset is not None and offset > self.options.max_offset_blocks * 4: self.add_violation(TooDeepNestingViolation(node)) 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!uܘ2wemake_python_styleguide/visitors/ast/functions.py# -*- coding: utf-8 -*- import ast from wemake_python_styleguide.constants import BAD_FUNCTIONS from wemake_python_styleguide.logics.functions import given_function_called from wemake_python_styleguide.violations.best_practices import ( WrongFunctionCallViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor class WrongFunctionCallVisitor(BaseNodeVisitor): """ Responsible for restricting some dangerous function calls. All these functions are defined in ``BAD_FUNCTIONS``. """ def visit_Call(self, node: ast.Call) -> None: """ Used to find ``BAD_FUNCTIONS`` calls. Raises: WrongFunctionCallViolation """ function_name = given_function_called(node, BAD_FUNCTIONS) if function_name: self.add_violation(WrongFunctionCallViolation( node, text=function_name, )) self.generic_visit(node) PK!oG 0wemake_python_styleguide/visitors/ast/imports.py# -*- coding: utf-8 -*- import ast from wemake_python_styleguide.constants import FUTURE_IMPORTS_WHITELIST from wemake_python_styleguide.logics.imports import get_error_text from wemake_python_styleguide.types import AnyImport from wemake_python_styleguide.violations.best_practices import ( FutureImportViolation, NestedImportViolation, ) 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 class _ImportsChecker(object): """Utility class to separate logic from the visitor.""" def __init__(self, delegate: 'WrongImportVisitor') -> None: self.delegate = delegate def check_nested_import(self, node: AnyImport) -> None: text = get_error_text(node) parent = getattr(node, 'parent', None) if parent is not None and not isinstance(parent, ast.Module): self.delegate.add_violation(NestedImportViolation(node, text=text)) def check_local_import(self, node: ast.ImportFrom) -> None: text = get_error_text(node) if node.level != 0: self.delegate.add_violation( LocalFolderImportViolation(node, text=text), ) 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.delegate.add_violation( 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.delegate.add_violation( DottedRawImportViolation(node, text=alias.name), ) def check_alias(self, node: AnyImport) -> None: for alias in node.names: if alias.asname == alias.name: self.delegate.add_violation( SameAliasImportViolation(node, text=alias.name), ) 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._checker = _ImportsChecker(self) def visit_Import(self, node: ast.Import) -> None: """ Used to find wrong ``import`` statements. Raises: SameAliasImportViolation DottedRawImportViolation NestedImportViolation """ self._checker.check_nested_import(node) self._checker.check_dotted_raw_import(node) self._checker.check_alias(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._checker.check_local_import(node) self._checker.check_nested_import(node) self._checker.check_future_import(node) self._checker.check_alias(node) self.generic_visit(node) PK!,1wemake_python_styleguide/visitors/ast/keywords.py# -*- coding: utf-8 -*- import ast from wemake_python_styleguide.violations.best_practices import ( RaiseNotImplementedViolation, WrongKeywordViolation, ) from wemake_python_styleguide.violations.consistency import ( MultipleIfsInComprehensionViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor 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) class WrongKeywordVisitor(BaseNodeVisitor): """Finds wrong keywords.""" _forbidden_keywords = ( 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)) def visit(self, node: ast.AST) -> None: """ Used to find wrong keywords. Raises: WrongKeywordViolation """ self._check_keyword(node) self.generic_visit(node) class WrongListComprehensionVisitor(BaseNodeVisitor): """Checks list comprehensions.""" def _check_ifs(self, node: ast.comprehension) -> None: if len(node.ifs) > 1: self.add_violation(MultipleIfsInComprehensionViolation(node)) def visit_comprehension(self, node: ast.comprehension) -> None: """ Finds multiple ``if`` nodes inside the comprehension. Raises: MultipleIfsInComprehensionViolation, """ self._check_ifs(node) self.generic_visit(node) PK!bee0wemake_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 is_stem_in_list from wemake_python_styleguide.violations.best_practices import ( EmptyModuleViolation, InitModuleHasLogicViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor class WrongContentsVisitor(BaseNodeVisitor): """Restricts to have empty modules.""" def _is_init(self) -> bool: return is_stem_in_list(self.filename, [INIT]) def _is_doc_string(self, node: ast.stmt) -> bool: # TODO: move if not isinstance(node, ast.Expr): return False return isinstance(node.value, ast.Str) def _check_module_contents(self, node: ast.Module) -> None: if self._is_init(): return if not node.body: self.add_violation(EmptyModuleViolation(node)) 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(node)) return if not self._is_doc_string(node.body[0]): self.add_violation(InitModuleHasLogicViolation(node)) 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!9/wemake_python_styleguide/visitors/ast/naming.py# -*- coding: utf-8 -*- import ast from wemake_python_styleguide.constants import ( BAD_MODULE_METADATA_VARIABLES, BAD_VARIABLE_NAMES, ) from wemake_python_styleguide.logics.variables import ( is_private_variable, is_too_short_variable_name, is_wrong_variable_name, ) from wemake_python_styleguide.types import AnyFunctionDef, AnyImport from wemake_python_styleguide.violations.best_practices import ( WrongModuleMetadataViolation, ) from wemake_python_styleguide.violations.naming import ( PrivateNameViolation, TooShortVariableNameViolation, WrongVariableNameViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor from wemake_python_styleguide.visitors.decorators import alias @alias('visit_any_import', ( 'visit_ImportFrom', 'visit_Import', )) @alias('visit_any_function', ( 'visit_FunctionDef', 'visit_AsyncFunctionDef', )) class WrongNameVisitor(BaseNodeVisitor): """ Performs checks based on variable names. It is responsible for finding short and blacklisted variables, functions, and arguments. """ def _check_name(self, node: ast.AST, name: str) -> None: if is_wrong_variable_name(name, BAD_VARIABLE_NAMES): self.add_violation(WrongVariableNameViolation(node, text=name)) min_length = self.options.min_variable_length if is_too_short_variable_name(name, min_length=min_length): self.add_violation(TooShortVariableNameViolation(node, text=name)) if is_private_variable(name): self.add_violation(PrivateNameViolation(node, text=name)) def _check_function_signature(self, node: AnyFunctionDef) -> None: for arg in node.args.args: self._check_name(node, arg.arg) for arg in node.args.kwonlyargs: self._check_name(node, arg.arg) if node.args.vararg: self._check_name(node, node.args.vararg.arg) if node.args.kwarg: self._check_name(node, node.args.kwarg.arg) def visit_Attribute(self, node: ast.Attribute) -> None: """ Used to find wrong attribute names inside classes. Raises: WrongVariableNameViolation TooShortVariableNameViolation PrivateNameViolation """ if isinstance(node.ctx, ast.Store): self._check_name(node, node.attr) self.generic_visit(node) def visit_any_function(self, node: AnyFunctionDef) -> None: """ Used to find wrong function and method parameters. Raises: WrongVariableNameViolation TooShortVariableNameViolation PrivateNameViolation """ self._check_name(node, node.name) self._check_function_signature(node) self.generic_visit(node) def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None: """ Used to find wrong exception instances in ``try``/``except``. Raises: WrongVariableNameViolation TooShortVariableNameViolation PrivateNameViolation """ self._check_name(node, getattr(node, 'name', None)) self.generic_visit(node) def visit_Name(self, node: ast.Name) -> None: """ Used to find wrong regular variables. Raises: WrongVariableNameViolation TooShortVariableNameViolation PrivateNameViolation """ if isinstance(node.ctx, ast.Store): self._check_name(node, node.id) self.generic_visit(node) def visit_any_import(self, node: AnyImport) -> None: """ Used to check wrong import alias names. Raises: WrongVariableNameViolation TooShortVariableNameViolation PrivateNameViolation """ for alias_node in node.names: if alias_node.asname: self._check_name(node, alias_node.asname) self.generic_visit(node) class WrongModuleMetadataVisitor(BaseNodeVisitor): """Finds wrong metadata information of a module.""" def _check_metadata(self, node: ast.Assign) -> None: node_parent = getattr(node, 'parent', None) if not isinstance(node_parent, ast.Module): return for target_node in node.targets: target_node_id = getattr(target_node, 'id', None) if target_node_id in BAD_MODULE_METADATA_VARIABLES: 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) PK!*  0wemake_python_styleguide/visitors/ast/numbers.py# -*- coding: utf-8 -*- import ast from typing import Optional from wemake_python_styleguide.constants import MAGIC_NUMBERS_WHITELIST from wemake_python_styleguide.violations.best_practices import ( MagicNumberViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor class MagicNumberVisitor(BaseNodeVisitor): """Checks magic numbers used in the code.""" _allowed_parents = ( ast.Assign, # Constructor usages: ast.FunctionDef, ast.AsyncFunctionDef, ast.arguments, # Primitives: ast.List, ast.Dict, ast.Set, ast.Tuple, ) _proxy_parents = ( ast.UnaryOp, ) def _get_real_parent(self, node: Optional[ast.AST]) -> Optional[ast.AST]: """ Returns real number's parent. What can go wrong? 1. Number can be negative: ``x = -1``, so ``1`` has ``UnaryOp`` as parent, but should return ``Assign`` """ parent = getattr(node, 'parent', None) if isinstance(parent, self._proxy_parents): return self._get_real_parent(parent) return parent def _check_is_magic(self, node: ast.Num) -> None: parent = self._get_real_parent(node) if isinstance(parent, self._allowed_parents): return if node.n in MAGIC_NUMBERS_WHITELIST: return if isinstance(node.n, int) and node.n <= 10: 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) PK!Je440wemake_python_styleguide/visitors/ast/strings.py# -*- coding: utf-8 -*- from wemake_python_styleguide.violations.consistency import ( FormattedStringViolation, ) from wemake_python_styleguide.visitors.base import BaseNodeVisitor class WrongStringVisitor(BaseNodeVisitor): """Restricts to use ``f`` strings.""" def visit_JoinedStr(self, node) -> None: # type is not defined in ast yet """ Restricts to use ``f`` strings. Raises: FormattedStringViolation """ self.add_violation(FormattedStringViolation(node)) self.generic_visit(node) PK!YT??)wemake_python_styleguide/visitors/base.py# -*- coding: utf-8 -*- """ Contains detailed documentation about how to write a visitor. .. _visitors: Creating new visitor -------------------- First of all, you have to decide what base class do you want to use? .. currentmodule:: wemake_python_styleguide.visitors.base Available base classes ~~~~~~~~~~~~~~~~~~~~~~ .. 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. Visitors API ------------ """ import ast import tokenize from typing import List, Sequence, Type from wemake_python_styleguide import constants from wemake_python_styleguide.types import ConfigurationOptions from wemake_python_styleguide.violations.base import BaseStyleViolation 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 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[BaseStyleViolation] = [] @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 ``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) def add_violation(self, violation: BaseStyleViolation) -> 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') 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 @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, ) def _post_visit(self) -> None: """ Executed after all nodes have been visited. This method is useful for counting statistics, etc. By default does nothing. """ 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. """ 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') 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.visit_filename() 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 @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. 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) def run(self) -> None: """Visits all token types that have a handler method.""" for token in self.file_tokens: self.visit(token) PK!&R/wemake_python_styleguide/visitors/decorators.py# -*- coding: utf-8 -*- from typing import Callable, Iterable def alias( original: str, aliases: Iterable[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. """ 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! ` ` @wemake_python_styleguide/visitors/filenames/wrong_module_name.py# -*- coding: utf-8 -*- from wemake_python_styleguide import constants from wemake_python_styleguide.logics import filenames from wemake_python_styleguide.violations.naming import ( TooShortModuleNameViolation, WrongModuleMagicNameViolation, WrongModuleNamePatternViolation, WrongModuleNameUnderscoresViolation, WrongModuleNameViolation, ) from wemake_python_styleguide.visitors.base import BaseFilenameVisitor class WrongModuleNameVisitor(BaseFilenameVisitor): """Checks that modules have correct names.""" def _check_module_name(self) -> None: is_wrong_name = filenames.is_stem_in_list( self.filename, constants.BAD_MODULE_NAMES, ) if is_wrong_name: self.add_violation(WrongModuleNameViolation()) def _check_magic_name(self) -> None: if filenames.is_magic(self.filename): good_magic = filenames.is_stem_in_list( self.filename, constants.MAGIC_MODULE_NAMES_WHITELIST, ) if not good_magic: self.add_violation(WrongModuleMagicNameViolation()) def _check_module_name_length(self) -> None: is_short = filenames.is_too_short_stem( self.filename, min_length=self.options.min_module_name_length, ) if is_short: self.add_violation(TooShortModuleNameViolation()) def _check_module_name_pattern(self) -> None: if not filenames.is_matching_pattern(self.filename): self.add_violation(WrongModuleNamePatternViolation()) def _check_underscores(self) -> None: repeating_underscores = self.filename.count('__') if filenames.is_magic(self.filename): repeating_underscores -= 2 if repeating_underscores > 0: self.add_violation(WrongModuleNameUnderscoresViolation()) def visit_filename(self) -> None: """ Checks a single module's filename. Raises: TooShortModuleNameViolation WrongModuleMagicNameViolation WrongModuleNameViolation WrongModuleNamePatternViolation WrongModuleNameUnderscoresViolation """ self._check_module_name() self._check_magic_name() self._check_module_name_length() self._check_module_name_pattern() self._check_underscores() PK!uh5wemake_python_styleguide/visitors/presets/__init__.py# -*- coding: utf-8 -*- PK!cys  7wemake_python_styleguide/visitors/presets/complexity.py# -*- coding: utf-8 -*- from wemake_python_styleguide.visitors.ast.complexity import ( 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, ) PK!?g--4wemake_python_styleguide/visitors/presets/general.py# -*- coding: utf-8 -*- from wemake_python_styleguide.visitors.ast import keywords, naming, numbers from wemake_python_styleguide.visitors.ast.classes import WrongClassVisitor from wemake_python_styleguide.visitors.ast.functions import ( WrongFunctionCallVisitor, ) from wemake_python_styleguide.visitors.ast.imports import WrongImportVisitor from wemake_python_styleguide.visitors.ast.modules import WrongContentsVisitor from wemake_python_styleguide.visitors.ast.strings import WrongStringVisitor from wemake_python_styleguide.visitors.filenames.wrong_module_name import ( WrongModuleNameVisitor, ) #: Used to store all general visitors to be later passed to checker: GENERAL_PRESET = ( # General: keywords.WrongRaiseVisitor, keywords.WrongKeywordVisitor, WrongFunctionCallVisitor, WrongImportVisitor, naming.WrongNameVisitor, naming.WrongModuleMetadataVisitor, numbers.MagicNumberVisitor, WrongStringVisitor, WrongContentsVisitor, # Classes: WrongClassVisitor, # Modules: WrongModuleNameVisitor, ) PK!mm3wemake_python_styleguide/visitors/presets/tokens.py# -*- coding: utf-8 -*- from wemake_python_styleguide.visitors.tokenize.comments import ( WrongCommentVisitor, ) from wemake_python_styleguide.visitors.tokenize.primitives import ( WrongPrimitivesVisitor, ) #: Used to store all token related visitors to be later passed to checker: TOKENS_PRESET = ( WrongCommentVisitor, WrongPrimitivesVisitor, ) 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 wemake_python_styleguide.violations.best_practices import ( WrongDocCommentViolation, WrongMagicCommentViolation, ) from wemake_python_styleguide.visitors.base import BaseTokenVisitor class WrongCommentVisitor(BaseTokenVisitor): """Checks comment tokens.""" noqa_check = re.compile(r'^noqa:?($|[A-Z\d\,\s]+)') type_check = re.compile(r'^type:\s?([\w\d\[\]\'\"\.]+)$') 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 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 visit_comment(self, token: tokenize.TokenInfo) -> None: """ Performs comment checks. Raises: WrongDocCommentViolation WrongMagicCommentViolation """ self._check_noqa(token) self._check_typed_ast(token) self._check_empty_doc_comment(token) PK! 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 visit_string(self, token: tokenize.TokenInfo) -> None: """ Checks string declarations. ``u`` can only be the only prefix. You can not combine it with ``r``, ``b``, or ``f``. Raises: UnicodeStringViolation """ if token.string.startswith('u'): self.add_violation(UnicodeStringViolation(token, text=token.string)) def visit_number(self, token: tokenize.TokenInfo) -> None: """ Checks number declarations. Raises: UnderscoredNumberViolation PartialFloatViolation """ self._check_underscored_number(token) self._check_partial_float(token) PK!H";?9wemake_python_styleguide-0.2.0.dist-info/entry_points.txtNINK(I+ϋ劲-O TdT椦f%g&gY9Ch..PK!f000wemake_python_styleguide-0.2.0.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_zTT.wemake_python_styleguide-0.2.0.dist-info/WHEEL A н#Z;/"d&F[xzw@Zpy3Fv]n0H*J>mlcAPK!HƊ 1wemake_python_styleguide-0.2.0.dist-info/METADATAXkWM>_= f&xy$D[@W={6sLL UB2]]zjs& \i!kA8-6pbnF2g<-E½ {r2 ռNGM6L"Ahx2rUcƓh^4WSs SHSV~@01#XBz`k\|wTnaۛ5/2yR&vɼ˄oe 3%d;caB֗z색Z~K^Z*,|vLr?j~~ۍ͍ rNp}$r~Ehv y.ʏmޤ[dg;Dp:V 1>PhSo1MmlYyo~ޗ\ yZbz$xPsGaOy,xXѓ[ԊWm1Z4v<]ivPOW]sx2[6F:}mr)}&ӳ^{Q瘞|?'o :띟س;yv:=ޣg{óYI{J3]ۓOۯ'1im>:{n}ov?ⓞufY%:oOΞm7Y5?R:jFSXRYcqكBd;%V*Q_¢TЫNFq}R(kheTWoS񸿊.&\bkdMt 027cWw:_d)YQujl9z>udwÒtonٖqI#E<.7+2mnTO':neduƹƠ*~Y/ Ǽ!ґ@%]]m;y4ͭ^ceweo[BQ  sigșd 45e<(֎rdPZ$n,Cq,hcf,FkE$s3ߗTH,pN\(T&‡ƞMeY]P($p,"Gw g7#es IlݮA Z{m\B7tpJ;Pϯ]6¾R.Ћ ] 6CPc* YI67 FjXTP*`C+D;},>ɒLK[cҁThn"QAYbHfƱH %K;j|(`d&C3*Qf^ѫmu_h[J>J&j\G~3WBA[{3 Hf%gmu8a>[ 5:JAi+ }ٗg?`MJoXCUIV ~RjrMt$Ц|h+әSj.)ۑ& zm.`fºιy8'f6i.9-x.)AJBo@ғ`+j`2^Rʃ?Q,{̀u] {{bXq6&`GTr`H/KqulH ]5iSIi%1$3^afut\tbgdUfkT ej%Rxh%rp86W0GOGW}zy:S"%[@9Џ> s:ܣe31'M .D껧>tYt^Ƹ|S;kՊ1l!EfQ+s7! P%x MvafR8Gv)';WDm CC*5aO]!~Pz1M~W,n"bSHV6uRfn{vth"vMgw=Aq:X͔1+M}4SBU/y.B9!\鳥tUEQ](-@V+*P!`#lR0{+^"EkwK(b󺳉7gBg!Ԣn*/u6,};T'%-Nh36F}w4+("AK{m; `$0N;`1ʂGFC 4&UܼAAفwM{Lc! n[Gh,s6'Ex[sjgX3࣋8mhVK"D"o"%~\<΋W7-L!k^ǐ-!`|a&Fc6\#z)IYpcG ےVjJG k9Ki.%=ᢺl 0e*$1z;.Ƃ^vsJى OQteBqy#U/˺T3Zĺ`n%ǘfIMCknS)n Do;ԪY<ϻM0I"93^ { !!7kuY_f]8QvKˉ`!2dT:*6{pڙ)/BB}?Ȩax18gI"9} ^mm(JԈ}7,- V89٘ՠJDp׀ -p7IAouR̦`aF!:y*"!҆+?]WUW^'$ΏƱ[?7$9#6O'q;ƾW#$@kCh.tkg$Ӝxٖ7 vP!bo`~G9t_Aύs!|c^Hߚ:H˥vSB1_[{kϚ:8սr0ul#(f SM:ԤK-1 >:|e]浝(o{gF3SYɭ-gپ!a?*,~heb/Gu0ᑷKq6#VUnPG9CyYmnُ'v-@?0sac)Bޛ'P׷k@ϠnfBО jw0@m0-\6}E#D~B25:Il%+ONl߯o%C|D&bZs '0sщѐ 3sV^-Óc$p7wB *WV(0CD^PK!uh$wemake_python_styleguide/__init__.pyPK!u NN#Zwemake_python_styleguide/checker.pyPK!c6F %wemake_python_styleguide/constants.pyPK!uh+wemake_python_styleguide/logics/__init__.pyPK!,;,] wemake_python_styleguide/logics/filenames.pyPK!s,G)wemake_python_styleguide/logics/functions.pyPK!\rr*V.wemake_python_styleguide/logics/imports.pyPK!%%(0wemake_python_styleguide/logics/nodes.pyPK!aZ,{2wemake_python_styleguide/logics/variables.pyPK!uh,u:wemake_python_styleguide/options/__init__.pyPK! ԗ*:wemake_python_styleguide/options/config.pyPK!],Uwemake_python_styleguide/options/defaults.pyPK!tV!]wemake_python_styleguide/types.pyPK!.m#ewemake_python_styleguide/version.pyPK!uh/@gwemake_python_styleguide/violations/__init__.pyPK!E&+gwemake_python_styleguide/violations/base.pyPK! 995vwemake_python_styleguide/violations/best_practices.pyPK! &331Ѱwemake_python_styleguide/violations/complexity.pyPK! ,,2wemake_python_styleguide/violations/consistency.pyPK!V)V)-wemake_python_styleguide/violations/naming.pyPK!uh-2,wemake_python_styleguide/visitors/__init__.pyPK!uh1,wemake_python_styleguide/visitors/ast/__init__.pyPK!Y>0,wemake_python_styleguide/visitors/ast/classes.pyPK!uh<O5wemake_python_styleguide/visitors/ast/complexity/__init__.pyPK!AA:5wemake_python_styleguide/visitors/ast/complexity/counts.pyPK!_cdd<ZKwemake_python_styleguide/visitors/ast/complexity/function.pyPK!:jr 9bwemake_python_styleguide/visitors/ast/complexity/jones.pyPK!jsg g :8nwemake_python_styleguide/visitors/ast/complexity/nested.pyPK!H:ywemake_python_styleguide/visitors/ast/complexity/offset.pyPK!uܘ2Dwemake_python_styleguide/visitors/ast/functions.pyPK!oG 0Jwemake_python_styleguide/visitors/ast/imports.pyPK!,1&wemake_python_styleguide/visitors/ast/keywords.pyPK!bee0Mwemake_python_styleguide/visitors/ast/modules.pyPK!9/wemake_python_styleguide/visitors/ast/naming.pyPK!*  0Owemake_python_styleguide/visitors/ast/numbers.pyPK!Je440wemake_python_styleguide/visitors/ast/strings.pyPK!YT??)+wemake_python_styleguide/visitors/base.pyPK!&R/wemake_python_styleguide/visitors/decorators.pyPK!uh7wemake_python_styleguide/visitors/filenames/__init__.pyPK! ` ` @wemake_python_styleguide/visitors/filenames/wrong_module_name.pyPK!uh5wemake_python_styleguide/visitors/presets/__init__.pyPK!cys  7wemake_python_styleguide/visitors/presets/complexity.pyPK!?g--4swemake_python_styleguide/visitors/presets/general.pyPK!mm3wemake_python_styleguide/visitors/presets/tokens.pyPK!uh6wemake_python_styleguide/visitors/tokenize/__init__.pyPK!6wemake_python_styleguide/visitors/tokenize/comments.pyPK!