Skip to content

Commit

Permalink
Refactors astor usages
Browse files Browse the repository at this point in the history
  • Loading branch information
sobolevn committed Aug 10, 2019
1 parent a31944d commit 39a3cae
Show file tree
Hide file tree
Showing 12 changed files with 44 additions and 40 deletions.
4 changes: 3 additions & 1 deletion .importlinter
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,15 @@ forbidden_modules =
pycodestyle
mccabe
radon
astor

ignore_imports =
# These modules must import from flake8 to provide required API:
wemake_python_styleguide.checker -> flake8
wemake_python_styleguide.formatter -> flake8
wemake_python_styleguide.formatter -> pygments
wemake_python_styleguide.options.config -> flake8
wemake_python_styleguide.formatter -> pygments
wemake_python_styleguide.logic.source -> astor


[importlinter:contract:subapi-restrictions]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ def test_false_condition_keywords(
'0.1',
'"0"',
'[None]',
'(0,)',
'{1, 2, 3}',
'{name: "0"}',
'True',
Expand Down
8 changes: 3 additions & 5 deletions wemake_python_styleguide/logic/compares.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
from collections import defaultdict
from typing import DefaultDict, Mapping, Set, Tuple, Type, Union

import astor
import attr
from typing_extensions import Final, final

from wemake_python_styleguide.logic import source


@final
@attr.dataclass(frozen=True, slots=True)
Expand Down Expand Up @@ -95,14 +96,11 @@ def _find_lower_upper_bounds(
self._mutate(
comparison_node,
operator,
self._get_operand_name(operand),
source.node_to_string(operand),
operand is left_operand,
)
left_operand = right_operand

def _get_operand_name(self, operand: ast.AST) -> str:
return astor.to_source(operand)

def _mutate(
self,
comparison_node: ast.Compare,
Expand Down
5 changes: 2 additions & 3 deletions wemake_python_styleguide/logic/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
from ast import Call, Yield, YieldFrom, arg
from typing import Container, List, Optional

import astor

from wemake_python_styleguide.logic import source
from wemake_python_styleguide.logic.walk import is_contained
from wemake_python_styleguide.types import (
AnyFunctionDef,
Expand All @@ -25,7 +24,7 @@ def given_function_called(node: Call, to_check: Container[str]) -> str:
''
"""
function_name = astor.to_source(node.func).strip()
function_name = source.node_to_string(node.func)
if function_name in to_check:
return function_name
return ''
Expand Down
10 changes: 10 additions & 0 deletions wemake_python_styleguide/logic/source.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# -*- coding: utf-8 -*-

import ast

import astor


def node_to_string(node: ast.AST) -> str:
"""Returns the source code by doing ``ast`` to string convert."""
return astor.to_source(node).strip()
7 changes: 3 additions & 4 deletions wemake_python_styleguide/visitors/ast/builtins.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@
from contextlib import suppress
from typing import ClassVar, DefaultDict, Iterable, List, Sequence, Union

import astor
from typing_extensions import final

from wemake_python_styleguide import constants
from wemake_python_styleguide.compat.aliases import FunctionNodes
from wemake_python_styleguide.logic import safe_eval
from wemake_python_styleguide.logic import safe_eval, source
from wemake_python_styleguide.logic.naming.name_nodes import extract_name
from wemake_python_styleguide.logic.operators import (
get_parent_ignoring_unary,
Expand Down Expand Up @@ -257,8 +256,8 @@ def _check_set_elements(
real_item = unwrap_unary_node(set_item)
if isinstance(real_item, self._elements_in_sets):
# Similar look:
source = astor.to_source(set_item)
elements.append(source.strip().strip('(').strip(')'))
node_repr = source.node_to_string(set_item)
elements.append(node_repr.strip().strip('(').strip(')'))

real_item = unwrap_starred_node(real_item)

Expand Down
4 changes: 2 additions & 2 deletions wemake_python_styleguide/visitors/ast/classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from collections import defaultdict
from typing import ClassVar, DefaultDict, FrozenSet, List, Optional, Tuple

import astor
from typing_extensions import final

from wemake_python_styleguide import constants, types
Expand All @@ -15,6 +14,7 @@
functions,
nodes,
prop_access,
source,
strings,
walk,
)
Expand Down Expand Up @@ -306,7 +306,7 @@ def _slot_item_name(self, node: ast.AST) -> Optional[str]:
if isinstance(node, ast.Str):
return node.s
if isinstance(node, ast.Starred):
return astor.to_source(node).strip()
return source.node_to_string(node)
return None

def _are_correct_slots(self, slots: List[ast.AST]) -> bool:
Expand Down
4 changes: 2 additions & 2 deletions wemake_python_styleguide/visitors/ast/compares.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import ast
from typing import ClassVar, List, Optional, Sequence

import astor
from typing_extensions import final

from wemake_python_styleguide.compat.aliases import AssignNodes
Expand All @@ -14,6 +13,7 @@
ifs,
nodes,
operators,
source,
)
from wemake_python_styleguide.logic.naming.name_nodes import is_same_variable
from wemake_python_styleguide.types import AnyIf, AnyNodes
Expand Down Expand Up @@ -299,7 +299,7 @@ def _is_simplifiable_assign(
if len(targets) != 1:
return None

return astor.to_source(targets[0]).strip()
return source.node_to_string(targets[0])

def _check_constant_condition(self, node: AnyIf) -> None:
real_node = operators.unwrap_unary_node(node.test)
Expand Down
9 changes: 4 additions & 5 deletions wemake_python_styleguide/visitors/ast/complexity/overuses.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@
from collections import defaultdict
from typing import ClassVar, DefaultDict, List, Union

import astor
from typing_extensions import final

from wemake_python_styleguide.compat.aliases import FunctionNodes
from wemake_python_styleguide.constants import SPECIAL_ARGUMENT_NAMES_WHITELIST
from wemake_python_styleguide.logic import nodes, walk
from wemake_python_styleguide.logic import nodes, source, walk
from wemake_python_styleguide.types import AnyNodes
from wemake_python_styleguide.violations import complexity
from wemake_python_styleguide.visitors import base
Expand Down Expand Up @@ -122,7 +121,7 @@ def _add_expression(self, node: ast.AST) -> None:
if any(ignore(node) for ignore in ignore_predicates):
return

source_code = astor.to_source(node).strip()
source_code = source.node_to_string(node)
self._module_expressions[source_code].append(node)

maybe_function = walk.get_closest_parent(node, FunctionNodes)
Expand Down Expand Up @@ -175,12 +174,12 @@ def _post_visit(self) -> None:
)

for function_contexts in self._function_expressions.values():
for source, function_nodes in function_contexts.items():
for src, function_nodes in function_contexts.items():
if len(function_nodes) > self.options.max_function_expressions:
self.add_violation(
complexity.OverusedExpressionViolation(
function_nodes[0],
text=self._msg.format(source, len(function_nodes)),
text=self._msg.format(src, len(function_nodes)),
),
)

Expand Down
9 changes: 4 additions & 5 deletions wemake_python_styleguide/visitors/ast/conditions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@
from functools import reduce
from typing import ClassVar, DefaultDict, Dict, List, Set, Type

import astor
from typing_extensions import final

from wemake_python_styleguide.logic import ifs
from wemake_python_styleguide.logic import ifs, source
from wemake_python_styleguide.logic.compares import CompareBounds
from wemake_python_styleguide.logic.functions import given_function_called
from wemake_python_styleguide.logic.nodes import get_parent
Expand Down Expand Up @@ -41,7 +40,7 @@ def _duplicated_isinstance_call(node: ast.BoolOp) -> List[str]:
if not given_function_called(call, {'isinstance'}):
continue

isinstance_object = astor.to_source(call.args[0]).strip()
isinstance_object = source.node_to_string(call.args[0])
counter[isinstance_object] += 1

return [
Expand Down Expand Up @@ -192,7 +191,7 @@ def _get_all_names(
if isinstance(operand, ast.BoolOp):
names.extend(self._get_all_names(operand))
else:
names.append(astor.to_source(operand))
names.append(source.node_to_string(operand))
return names

def _check_same_elements(self, node: ast.BoolOp) -> None:
Expand Down Expand Up @@ -247,7 +246,7 @@ def _check_implicit_in(self, node: ast.BoolOp) -> None:
if not isinstance(compare.ops[0], allowed_ops[node.op.__class__]):
return

variables.append({astor.to_source(compare.left)})
variables.append({source.node_to_string(compare.left)})

for duplicate in _get_duplicate_names(variables):
self.add_violation(
Expand Down
6 changes: 3 additions & 3 deletions wemake_python_styleguide/visitors/ast/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
from collections import Counter
from typing import ClassVar, List, Tuple

import astor
from typing_extensions import final

from wemake_python_styleguide.logic import source
from wemake_python_styleguide.logic.walk import is_contained
from wemake_python_styleguide.types import AnyNodes
from wemake_python_styleguide.violations.best_practices import (
Expand Down Expand Up @@ -105,10 +105,10 @@ def _check_duplicate_exceptions(self, node: ast.Try) -> None:
# There might be complex things hidden inside an exception type,
# so we want to get the string representation of it:
if isinstance(exc_handler.type, ast.Name):
exceptions.append(astor.to_source(exc_handler.type).strip())
exceptions.append(source.node_to_string(exc_handler.type))
elif isinstance(exc_handler.type, ast.Tuple):
exceptions.extend([
astor.to_source(node).strip()
source.node_to_string(node)
for node in exc_handler.type.elts
])

Expand Down
17 changes: 8 additions & 9 deletions wemake_python_styleguide/visitors/ast/keywords.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,15 +103,14 @@ def _check_last_return_in_function(self, node: ast.Return) -> None:
walk.get_subnodes_by_type(parent, ast.Return),
)))

if node is parent.body[-1]:
last_value_return = (
len(parent.body) > 1 and
returns < 2 and
isinstance(node.value, ast.NameConstant) and
node.value.value is None
)
if node.value is None or last_value_return:
self.add_violation(InconsistentReturnViolation(node))
last_value_return = (
len(parent.body) > 1 and
returns < 2 and
isinstance(node.value, ast.NameConstant) and
node.value.value is None
)
if node.value is None or last_value_return:
self.add_violation(InconsistentReturnViolation(node))

def _iterate_returning_values(
self,
Expand Down

0 comments on commit 39a3cae

Please sign in to comment.