Skip to content

Commit

Permalink
Import astroid with import x or from x import y but not both
Browse files Browse the repository at this point in the history
Remove unused imports for astroid
  • Loading branch information
Pierre-Sassoulas committed Mar 28, 2021
1 parent d2db40c commit 14f20e2
Show file tree
Hide file tree
Showing 19 changed files with 102 additions and 110 deletions.
3 changes: 1 addition & 2 deletions doc/how_tos/transform_plugins.rst
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ Module, Class, Function etc. In our case we need to transform a class. It can be
.. sourcecode:: python

import astroid
from astroid import MANAGER

def register(linter):
# Needed for registering the plugin.
Expand All @@ -79,7 +78,7 @@ Module, Class, Function etc. In our case we need to transform a class. It can be
for f in warnings.WarningMessage._WARNING_DETAILS:
cls.locals[f] = [astroid.ClassDef(f, None)]

MANAGER.register_transform(astroid.ClassDef, transform)
astroid.MANAGER.register_transform(astroid.ClassDef, transform)

Let's go through the plugin. First, we need to register a class transform, which
is done via the ``register_transform`` function in ``MANAGER``. It takes the node
Expand Down
5 changes: 2 additions & 3 deletions pylint/checkers/async.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import sys

import astroid
from astroid import bases, exceptions

from pylint import checkers, interfaces, utils
from pylint.checkers import utils as checker_utils
Expand Down Expand Up @@ -64,7 +63,7 @@ def visit_asyncwith(self, node):
# with contextlib.asynccontextmanager.
if decorated_with(inferred, self._async_generators):
continue
elif isinstance(inferred, bases.AsyncGenerator):
elif isinstance(inferred, astroid.bases.AsyncGenerator):
# Check if we are dealing with a function decorated
# with contextlib.asynccontextmanager.
if decorated_with(inferred.parent, self._async_generators):
Expand All @@ -73,7 +72,7 @@ def visit_asyncwith(self, node):
try:
inferred.getattr("__aenter__")
inferred.getattr("__aexit__")
except exceptions.NotFoundError:
except astroid.exceptions.NotFoundError:
if isinstance(inferred, astroid.Instance):
# If we do not know the bases of this class,
# just skip it.
Expand Down
5 changes: 1 addition & 4 deletions pylint/checkers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,6 @@
from typing import Pattern

import astroid
import astroid.bases
import astroid.scoped_nodes
from astroid.arguments import CallSite

from pylint import checkers, exceptions, interfaces
from pylint import utils as lint_utils
Expand Down Expand Up @@ -1269,7 +1266,7 @@ def visit_lambda(self, node):
# return something else (but we don't check that, yet).
return

call_site = CallSite.from_call(call)
call_site = astroid.arguments.CallSite.from_call(call)
ordinary_args = list(node.args.args)
new_call_args = list(self._filter_vararg(node, call.args))
if node.args.kwarg:
Expand Down
30 changes: 13 additions & 17 deletions pylint/checkers/classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,6 @@
from itertools import chain, zip_longest

import astroid
from astroid import decorators, objects
from astroid.bases import BUILTINS, Generator
from astroid.exceptions import DuplicateBasesError, InconsistentMroError
from astroid.scoped_nodes import function_to_method

from pylint.checkers import BaseChecker
from pylint.checkers.utils import (
Expand Down Expand Up @@ -403,7 +399,7 @@ def _is_attribute_property(name, klass):
attributes = klass.getattr(name)
except astroid.NotFoundError:
return False
property_name = f"{BUILTINS}.property"
property_name = f"{astroid.bases.BUILTINS}.property"
for attr in attributes:
if attr is astroid.Uninferable:
continue
Expand Down Expand Up @@ -774,11 +770,11 @@ def __init__(self, linter=None):
self._first_attrs = []
self._meth_could_be_func = None

@decorators.cachedproperty
@astroid.decorators.cachedproperty
def _dummy_rgx(self):
return get_global_option(self, "dummy-variables-rgx", default=None)

@decorators.cachedproperty
@astroid.decorators.cachedproperty
def _ignore_mixin(self):
return get_global_option(self, "ignore-mixin-members", default=True)

Expand Down Expand Up @@ -811,9 +807,9 @@ def _check_consistent_mro(self, node):
"""Detect that a class has a consistent mro or duplicate bases."""
try:
node.mro()
except InconsistentMroError:
except astroid.InconsistentMroError:
self.add_message("inconsistent-mro", args=node.name, node=node)
except DuplicateBasesError:
except astroid.DuplicateBasesError:
self.add_message("duplicate-bases", args=node.name, node=node)
except NotImplementedError:
# Old style class, there's no mro so don't do anything.
Expand All @@ -829,7 +825,7 @@ def _check_proper_bases(self, node):
if not ancestor:
continue
if isinstance(ancestor, astroid.Instance) and ancestor.is_subtype_of(
f"{BUILTINS}.type"
f"{astroid.bases.BUILTINS}.type"
):
continue

Expand Down Expand Up @@ -1056,7 +1052,7 @@ def _check_useless_super_delegation(self, function):
except astroid.InferenceError:
return
else:
if not isinstance(super_call, objects.Super):
if not isinstance(super_call, astroid.objects.Super):
return

# The name should be the same.
Expand Down Expand Up @@ -1673,7 +1669,7 @@ def _check_init(self, node):
and klass._proxied.name == "super"
):
return
if isinstance(klass, objects.Super):
if isinstance(klass, astroid.objects.Super):
return
try:
del not_called_yet[klass]
Expand Down Expand Up @@ -1704,8 +1700,8 @@ def _check_signature(self, method1, refmethod, class_type, cls):
return

instance = cls.instantiate_class()
method1 = function_to_method(method1, instance)
refmethod = function_to_method(refmethod, instance)
method1 = astroid.scoped_nodes.function_to_method(method1, instance)
refmethod = astroid.scoped_nodes.function_to_method(refmethod, instance)

# Don't care about functions with unknown argument (builtins).
if method1.args.args is None or refmethod.args.args is None:
Expand Down Expand Up @@ -1900,7 +1896,7 @@ def _check_unexpected_method_signature(self, node):
# by no-method-argument.
return

if decorated_with(node, [BUILTINS + ".staticmethod"]):
if decorated_with(node, [astroid.bases.BUILTINS + ".staticmethod"]):
# We expect to not take in consideration self.
all_args = node.args.args
else:
Expand Down Expand Up @@ -1991,8 +1987,8 @@ def _is_iterator(node):
if node is astroid.Uninferable:
# Just ignore Uninferable objects.
return True
if isinstance(node, Generator):
# Generators can be itered.
if isinstance(node, astroid.bases.Generator):
# Generators can be iterated.
return True

if isinstance(node, astroid.Instance):
Expand Down
11 changes: 6 additions & 5 deletions pylint/checkers/design_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
from collections import defaultdict

import astroid
from astroid import BoolOp, If, decorators

from pylint import utils
from pylint.checkers import BaseChecker
Expand Down Expand Up @@ -137,7 +136,7 @@ def _count_boolean_expressions(bool_op):
"""
nb_bool_expr = 0
for bool_expr in bool_op.get_children():
if isinstance(bool_expr, BoolOp):
if isinstance(bool_expr, astroid.BoolOp):
nb_bool_expr += _count_boolean_expressions(bool_expr)
else:
nb_bool_expr += 1
Expand Down Expand Up @@ -284,7 +283,7 @@ def _inc_all_stmts(self, amount):
for i in range(len(self._stmts)):
self._stmts[i] += amount

@decorators.cachedproperty
@astroid.decorators.cachedproperty
def _ignored_argument_names(self):
return utils.get_global_option(self, "ignored-argument-names", default=None)

Expand Down Expand Up @@ -460,7 +459,9 @@ def visit_if(self, node):
self._check_boolean_expressions(node)
branches = 1
# don't double count If nodes coming from some 'elif'
if node.orelse and (len(node.orelse) > 1 or not isinstance(node.orelse[0], If)):
if node.orelse and (
len(node.orelse) > 1 or not isinstance(node.orelse[0], astroid.If)
):
branches += 1
self._inc_branch(node, branches)
self._inc_all_stmts(branches)
Expand All @@ -471,7 +472,7 @@ def _check_boolean_expressions(self, node):
if the "if" node test is a BoolOp node
"""
condition = node.test
if not isinstance(condition, BoolOp):
if not isinstance(condition, astroid.BoolOp):
return
nb_bool_expr = _count_boolean_expressions(condition)
if nb_bool_expr > self.config.max_bool_expr:
Expand Down
5 changes: 2 additions & 3 deletions pylint/checkers/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
import typing

import astroid
from astroid.node_classes import NodeNG

from pylint import checkers, interfaces
from pylint.checkers import utils
Expand Down Expand Up @@ -433,8 +432,8 @@ def _check_catching_non_exception(self, handler, exc, part):
def _check_try_except_raise(self, node):
def gather_exceptions_from_handler(
handler,
) -> typing.Optional[typing.List[NodeNG]]:
exceptions = [] # type: typing.List[NodeNG]
) -> typing.Optional[typing.List[astroid.node_classes.NodeNG]]:
exceptions = [] # type: typing.List[astroid.node_classes.NodeNG]
if handler.type:
exceptions_in_handler = utils.safe_infer(handler.type)
if isinstance(exceptions_in_handler, astroid.Tuple):
Expand Down
12 changes: 6 additions & 6 deletions pylint/checkers/imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@
from distutils import sysconfig

import astroid
from astroid import modutils
from astroid.decorators import cached

from pylint.checkers import BaseChecker, DeprecatedMixin
from pylint.checkers.utils import (
Expand Down Expand Up @@ -810,14 +808,16 @@ def _add_imported_module(self, node, importedmodname):
base = os.path.splitext(os.path.basename(module_file))[0]

try:
importedmodname = modutils.get_module_part(importedmodname, module_file)
importedmodname = astroid.modutils.get_module_part(
importedmodname, module_file
)
except ImportError:
pass

if context_name == importedmodname:
self.add_message("import-self", node=node)

elif not modutils.is_standard_module(importedmodname):
elif not astroid.modutils.is_standard_module(importedmodname):
# if this is not a package __init__ module
if base != "__init__" and context_name not in self._module_pkg:
# record the module's parent, or the module itself if this is
Expand Down Expand Up @@ -921,14 +921,14 @@ def _filter_dependencies_graph(self, internal):
graph[importee].add(importer)
return graph

@cached
@astroid.decorators.cached
def _external_dependencies_info(self):
"""return cached external dependencies information or build and
cache them
"""
return self._filter_dependencies_graph(internal=False)

@cached
@astroid.decorators.cached
def _internal_dependencies_info(self):
"""return cached internal dependencies information or build and
cache them
Expand Down
9 changes: 5 additions & 4 deletions pylint/checkers/python3.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@
from collections import namedtuple

import astroid
from astroid import bases

from pylint import checkers, interfaces
from pylint.checkers import utils
Expand Down Expand Up @@ -978,7 +977,9 @@ def visit_functiondef(self, node):
# classmethod 1 argument should cause a failure, if it is a
# staticmethod 0 arguments should cause a failure.
failing_arg_count = 1
if utils.decorated_with(node, [bases.BUILTINS + ".staticmethod"]):
if utils.decorated_with(
node, [astroid.bases.BUILTINS + ".staticmethod"]
):
failing_arg_count = 0
if len(node.args.args) == failing_arg_count:
self.add_message("next-method-defined", node=node)
Expand Down Expand Up @@ -1116,7 +1117,7 @@ def _check_cmp_argument(self, node):
if not inferred:
return

builtins_list = f"{bases.BUILTINS}.list"
builtins_list = f"{astroid.bases.BUILTINS}.list"
if isinstance(inferred, astroid.List) or inferred.qname() == builtins_list:
kwargs = node.keywords

Expand All @@ -1125,7 +1126,7 @@ def _check_cmp_argument(self, node):
if not inferred:
return

builtins_sorted = f"{bases.BUILTINS}.sorted"
builtins_sorted = f"{astroid.bases.BUILTINS}.sorted"
if inferred.qname() == builtins_sorted:
kwargs = node.keywords

Expand Down
8 changes: 6 additions & 2 deletions pylint/checkers/refactoring/len_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from typing import List

import astroid
from astroid import DictComp, GeneratorExp, ListComp, SetComp

from pylint import checkers, interfaces
from pylint.checkers import utils
Expand Down Expand Up @@ -68,7 +67,12 @@ def visit_call(self, node):
if not utils.is_test_condition(node, parent):
return
len_arg = node.args[0]
generator_or_comprehension = (ListComp, SetComp, DictComp, GeneratorExp)
generator_or_comprehension = (
astroid.ListComp,
astroid.SetComp,
astroid.DictComp,
astroid.GeneratorExp,
)
if isinstance(len_arg, generator_or_comprehension):
# The node is a generator or comprehension as in len([x for x in ...])
self.add_message("len-as-condition", node=node)
Expand Down
3 changes: 1 addition & 2 deletions pylint/checkers/refactoring/refactoring_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from typing import List

import astroid
from astroid import decorators

from pylint import checkers, interfaces
from pylint import utils as lint_utils
Expand Down Expand Up @@ -335,7 +334,7 @@ def open(self):
# do this in open since config not fully initialized in __init__
self._never_returning_functions = set(self.config.never_returning_functions)

@decorators.cachedproperty
@astroid.decorators.cachedproperty
def _dummy_rgx(self):
return lint_utils.get_global_option(self, "dummy-variables-rgx", default=None)

Expand Down
9 changes: 5 additions & 4 deletions pylint/checkers/stdlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,6 @@
import sys

import astroid
from astroid.bases import Instance
from astroid.node_classes import Const

from pylint.checkers import BaseChecker, DeprecatedMixin, utils
from pylint.interfaces import IAstroidChecker
Expand Down Expand Up @@ -382,7 +380,10 @@ def _check_datetime(self, node):
inferred = next(node.infer())
except astroid.InferenceError:
return
if isinstance(inferred, Instance) and inferred.qname() == "datetime.time":
if (
isinstance(inferred, astroid.Instance)
and inferred.qname() == "datetime.time"
):
self.add_message("boolean-datetime", node=node)

def _check_open_mode(self, node):
Expand Down Expand Up @@ -442,7 +443,7 @@ def _check_invalid_envvar_value(self, node, infer, message, call_arg, allow_none
return

name = infer.qname()
if isinstance(call_arg, Const):
if isinstance(call_arg, astroid.Const):
emit = False
if call_arg.value is None:
emit = not allow_none
Expand Down
Loading

0 comments on commit 14f20e2

Please sign in to comment.