Skip to content

Commit

Permalink
Merge b86bdf1 into d69f5ea
Browse files Browse the repository at this point in the history
  • Loading branch information
Pierre-Sassoulas authored Apr 19, 2021
2 parents d69f5ea + b86bdf1 commit 8edea93
Show file tree
Hide file tree
Showing 16 changed files with 73 additions and 50 deletions.
18 changes: 9 additions & 9 deletions astroid/brain/brain_builtin_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ def _extend_builtins(class_transforms):


def _builtin_filter_predicate(node, builtin_name):
if (
if ( # pylint: disable=too-many-boolean-expressions
builtin_name == "type"
and node.root().name == "re"
and isinstance(node.func, nodes.Name)
Expand Down Expand Up @@ -232,10 +232,12 @@ def _container_generic_inference(node, context, node_type, transform):
return transformed


def _container_generic_transform(arg, context, klass, iterables, build_elts):
def _container_generic_transform( # pylint: disable=inconsistent-return-statements
arg, context, klass, iterables, build_elts
):
if isinstance(arg, klass):
return arg
elif isinstance(arg, iterables):
if isinstance(arg, iterables):
if all(isinstance(elt, nodes.Const) for elt in arg.elts):
elts = [elt.value for elt in arg.elts]
else:
Expand Down Expand Up @@ -371,7 +373,7 @@ def infer_dict(node, context=None):
if not args and not kwargs:
# dict()
return nodes.Dict()
elif kwargs and not args:
if kwargs and not args:
# dict(a=1, b=2, c=4)
items = [(nodes.Const(key), value) for key, value in kwargs]
elif len(args) == 1 and kwargs:
Expand All @@ -383,7 +385,6 @@ def infer_dict(node, context=None):
items = _get_elts(args[0], context)
else:
raise UseInferenceDefault()

value = nodes.Dict(
col_offset=node.col_offset, lineno=node.lineno, parent=node.parent
)
Expand Down Expand Up @@ -417,7 +418,7 @@ def infer_super(node, context=None):
raise UseInferenceDefault

cls = scoped_nodes.get_wrapping_class(scope)
if not len(node.args):
if not node.args:
mro_pointer = cls
# In we are in a classmethod, the interpreter will fill
# automatically the class as the second argument, not an instance.
Expand Down Expand Up @@ -877,15 +878,14 @@ def _build_dict_with_elements(elements):

elements_with_value = [(element, default) for element in elements]
return _build_dict_with_elements(elements_with_value)

elif isinstance(inferred_values, nodes.Const) and isinstance(
if isinstance(inferred_values, nodes.Const) and isinstance(
inferred_values.value, (str, bytes)
):
elements = [
(nodes.Const(element), default) for element in inferred_values.value
]
return _build_dict_with_elements(elements)
elif isinstance(inferred_values, nodes.Dict):
if isinstance(inferred_values, nodes.Dict):
keys = inferred_values.itered()
for key in keys:
if not isinstance(key, accepted_iterable_elements):
Expand Down
2 changes: 1 addition & 1 deletion astroid/brain/brain_fstrings.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def _clone_node_with_lineno(node, parent, lineno):
return new_node


def _transform_formatted_value(node):
def _transform_formatted_value(node): # pylint: disable=inconsistent-return-statements
if node.value and node.value.lineno == 1:
if node.lineno != node.value.lineno:
new_node = astroid.FormattedValue(
Expand Down
8 changes: 4 additions & 4 deletions astroid/brain/brain_functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,14 @@ def attr_cache_clear(self):
return BoundMethod(proxy=node, bound=self._instance.parent.scope())


def _transform_lru_cache(node, context=None):
def _transform_lru_cache(node, context=None) -> None:
# TODO: this is not ideal, since the node should be immutable,
# but due to https://github.com/PyCQA/astroid/issues/354,
# there's not much we can do now.
# Replacing the node would work partially, because,
# in pylint, the old node would still be available, leading
# to spurious false positives.
node.special_attributes = LruWrappedModel()(node)
return


def _functools_partial_inference(node, context=None):
Expand Down Expand Up @@ -136,16 +135,17 @@ def _looks_like_lru_cache(node):
return False


def _looks_like_functools_member(node, member):
def _looks_like_functools_member(node, member) -> bool:
"""Check if the given Call node is a functools.partial call"""
if isinstance(node.func, astroid.Name):
return node.func.name == member
elif isinstance(node.func, astroid.Attribute):
if isinstance(node.func, astroid.Attribute):
return (
node.func.attrname == member
and isinstance(node.func.expr, astroid.Name)
and node.func.expr.name == "functools"
)
return False


_looks_like_partial = partial(_looks_like_functools_member, member="partial")
Expand Down
13 changes: 9 additions & 4 deletions astroid/brain/brain_gi.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
Helps with understanding everything imported from 'gi.repository'
"""

# pylint:disable=import-error,import-outside-toplevel

import inspect
import itertools
import sys
Expand Down Expand Up @@ -83,7 +85,7 @@ def _gi_build_stub(parent):

try:
obj = getattr(parent, name)
except:
except AttributeError:
continue

if inspect.isclass(obj):
Expand Down Expand Up @@ -188,11 +190,14 @@ def _import_gi_module(modname):
# Just inspecting the code can raise gi deprecation
# warnings, so ignore them.
try:
from gi import PyGIDeprecationWarning, PyGIWarning
from gi import ( # pylint:disable=import-error
PyGIDeprecationWarning,
PyGIWarning,
)

warnings.simplefilter("ignore", PyGIDeprecationWarning)
warnings.simplefilter("ignore", PyGIWarning)
except Exception:
except Exception: # pylint:disable=broad-except
pass

__import__(m)
Expand Down Expand Up @@ -242,7 +247,7 @@ def _register_require_version(node):
import gi

gi.require_version(node.args[0].value, node.args[1].value)
except Exception:
except Exception: # pylint:disable=broad-except
pass

return node
Expand Down
10 changes: 5 additions & 5 deletions astroid/brain/brain_namedtuple_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,15 @@ def _infer_first(node, context):
value = next(node.infer(context=context))
if value is util.Uninferable:
raise UseInferenceDefault()
else:
return value
return value
except StopIteration as exc:
raise InferenceError from exc


def _find_func_form_arguments(node, context):
def _extract_namedtuple_arg_or_keyword(position, key_name=None):

def _extract_namedtuple_arg_or_keyword( # pylint: disable=inconsistent-return-statements
position, key_name=None
):
if len(args) > position:
return _infer_first(args[position], context)
if key_name and key_name in found_keywords:
Expand Down Expand Up @@ -229,7 +229,7 @@ def _get_renamed_namedtuple_attributes(field_names):
names = list(field_names)
seen = set()
for i, name in enumerate(field_names):
if (
if ( # pylint: disable=too-many-boolean-expressions
not all(c.isalnum() or c == "_" for c in name)
or keyword.iskeyword(name)
or not name
Expand Down
3 changes: 2 additions & 1 deletion astroid/brain/brain_six.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ def _looks_like_decorated_with_six_add_metaclass(node):
return False


def transform_six_add_metaclass(node):
def transform_six_add_metaclass(node): # pylint: disable=inconsistent-return-statements
"""Check if the given class node is decorated with *six.add_metaclass*
If so, inject its argument as the metaclass of the underlying class.
Expand All @@ -192,6 +192,7 @@ def transform_six_add_metaclass(node):
metaclass = decorator.args[0]
node._metaclass = metaclass
return node
return


def _looks_like_nested_from_six_with_metaclass(node):
Expand Down
13 changes: 6 additions & 7 deletions astroid/brain/brain_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,10 @@ def looks_like_typing_typevar_or_newtype(node):
return False


def infer_typing_typevar_or_newtype(node, context=None):
def infer_typing_typevar_or_newtype(node, context_itton=None):
"""Infer a typing.TypeVar(...) or typing.NewType(...) call"""
try:
func = next(node.func.infer(context=context))
func = next(node.func.infer(context=context_itton))
except InferenceError as exc:
raise UseInferenceDefault from exc

Expand All @@ -119,16 +119,16 @@ def infer_typing_typevar_or_newtype(node, context=None):

typename = node.args[0].as_string().strip("'")
node = extract_node(TYPING_TYPE_TEMPLATE.format(typename))
return node.infer(context=context)
return node.infer(context=context_itton)


def _looks_like_typing_subscript(node):
"""Try to figure out if a Subscript node *might* be a typing-related subscript"""
if isinstance(node, nodes.Name):
return node.name in TYPING_MEMBERS
elif isinstance(node, nodes.Attribute):
if isinstance(node, nodes.Attribute):
return node.attrname in TYPING_MEMBERS
elif isinstance(node, nodes.Subscript):
if isinstance(node, nodes.Subscript):
return _looks_like_typing_subscript(node.value)
return False

Expand Down Expand Up @@ -232,8 +232,7 @@ def full_raiser(origin_func, attr, *args, **kwargs):
"""
if attr == "__class_getitem__":
raise AttributeInferenceError("__class_getitem__ access is not allowed")
else:
return origin_func(attr, *args, **kwargs)
return origin_func(attr, *args, **kwargs)

try:
node.getattr("__class_getitem__")
Expand Down
8 changes: 5 additions & 3 deletions astroid/interpreter/_import/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,13 +297,15 @@ def _precache_zipimporters(path=None):
new_paths = _cached_set_diff(req_paths, cached_paths)
for entry_path in new_paths:
try:
pic[entry_path] = zipimport.zipimporter(entry_path)
except zipimport.ZipImportError:
pic[entry_path] = zipimport.zipimporter( # pylint: disable=no-member
entry_path
)
except zipimport.ZipImportError: # pylint: disable=no-member
continue
return {
key: value
for key, value in pic.items()
if isinstance(value, zipimport.zipimporter)
if isinstance(value, zipimport.zipimporter) # pylint: disable=no-member
}


Expand Down
5 changes: 4 additions & 1 deletion astroid/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ def _can_load_extension(self, modname):

def ast_from_module_name(self, modname, context_file=None):
"""given a module name, return the astroid object"""
# pylint: disable=no-member
if modname in self.astroid_cache:
return self.astroid_cache[modname]
if modname == "__main__":
Expand Down Expand Up @@ -215,7 +216,9 @@ def zip_import_data(self, filepath):
except ValueError:
continue
try:
importer = zipimport.zipimporter(eggpath + ext)
importer = zipimport.zipimporter( # pylint: disable=no-member
eggpath + ext
)
zmodname = resource.replace(os.path.sep, ".")
if importer.is_package(resource):
zmodname = zmodname + ".__init__"
Expand Down
19 changes: 14 additions & 5 deletions pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,18 @@ confidence=
# no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W"

disable=fixme, invalid-name, missing-docstring, too-few-public-methods,
disable=fixme,
invalid-name,
missing-docstring,
too-few-public-methods,
too-many-public-methods,
# We know about it and we're doing our best to remove it
# in 2.0
too-many-boolean-expressions,
too-many-branches,
too-many-statements,
# We know about it and we're doing our best to remove it in 2.0 (oups)
cyclic-import,
wrong-import-position,
wrong-import-order,
# The check is faulty in most cases and it doesn't take in
# account how the variable is being used. For instance,
# using a variable that is a list or a generator in an
Expand All @@ -103,7 +110,9 @@ disable=fixme, invalid-name, missing-docstring, too-few-public-methods,
# black handles these
format,
# temporary until we fix the problems with InferenceContexts
no-member
no-member,
# everything here is legacy not checked in astroid/brain
duplicate-code,


[BASIC]
Expand Down Expand Up @@ -248,7 +257,7 @@ ignore-comments=yes
ignore-docstrings=yes

# Ignore imports when computing similarities.
ignore-imports=no
ignore-imports=yes


[SPELLING]
Expand Down
6 changes: 3 additions & 3 deletions tests/unittest_brain.py
Original file line number Diff line number Diff line change
Expand Up @@ -498,8 +498,7 @@ class B(six.with_metaclass(A, C)):
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.ClassDef)
self.assertEqual(inferred.name, "B")
bases = inferred.bases
self.assertIsInstance(bases[0], nodes.Call)
self.assertIsInstance(inferred.bases[0], nodes.Call)
ancestors = tuple(inferred.ancestors())
self.assertIsInstance(ancestors[0], nodes.ClassDef)
self.assertEqual(ancestors[0].name, "C")
Expand Down Expand Up @@ -1003,7 +1002,8 @@ def test_invalid_type_subscript(self):
self.assertIsInstance(val_inf, astroid.ClassDef)
self.assertEqual(val_inf.name, "str")
with self.assertRaises(astroid.exceptions.AttributeInferenceError):
meth_inf = val_inf.getattr("__class_getitem__")[0]
# pylint: disable=expression-not-assigned
val_inf.getattr("__class_getitem__")[0]

@test_utils.require_version(minver="3.9")
def test_builtin_subscriptable(self):
Expand Down
4 changes: 3 additions & 1 deletion tests/unittest_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,9 @@ def test_file_from_module(self):
"""check if the unittest filepath is equals to the result of the method"""
self.assertEqual(
_get_file_from_object(unittest),
self.manager.file_from_module_name("unittest", None).location,
self.manager.file_from_module_name( # pylint: disable=no-member
"unittest", None
).location,
)

def test_file_from_module_name_astro_building_exception(self):
Expand Down
4 changes: 2 additions & 2 deletions tests/unittest_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1166,8 +1166,8 @@ def f(a):
# type: (A) -> A
pass
"""
astroid = builder.parse(data)
f = astroid.body[0]
parsed_data = builder.parse(data)
f = parsed_data.body[0]
assert f.type_comment_args[0].parent is f
assert f.type_comment_returns.parent is f

Expand Down
4 changes: 3 additions & 1 deletion tests/unittest_raw_building.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,19 +51,21 @@ def test_build_function(self):

def test_build_function_args(self):
args = ["myArgs1", "myArgs2"]
# pylint: disable=no-member
node = build_function("MyFunction", args)
self.assertEqual("myArgs1", node.args.args[0].name)
self.assertEqual("myArgs2", node.args.args[1].name)
self.assertEqual(2, len(node.args.args))

def test_build_function_defaults(self):
defaults = ["defaults1", "defaults2"]
# pylint: disable=no-member
node = build_function(name="MyFunction", args=None, defaults=defaults)
self.assertEqual(2, len(node.args.defaults))

def test_build_function_posonlyargs(self):
node = build_function(name="MyFunction", posonlyargs=["a", "b"])
self.assertEqual(2, len(node.args.posonlyargs))
self.assertEqual(2, len(node.args.posonlyargs)) # pylint: disable=no-member

def test_build_from_import(self):
names = ["exceptions, inference, inspector"]
Expand Down
Loading

0 comments on commit 8edea93

Please sign in to comment.