summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorClaudiu Popa <pcmanticore@gmail.com>2018-10-02 09:43:56 +0200
committerClaudiu Popa <pcmanticore@gmail.com>2018-10-02 09:43:56 +0200
commitadd5f7b8eba427de9d39caae864bbc6dc37ef980 (patch)
tree86bb7df77f389062879365e97df0c3d53d38a8a6
parentbb46cd198b93f3715da94089d42f39fc910892ff (diff)
downloadastroid-git-add5f7b8eba427de9d39caae864bbc6dc37ef980.tar.gz
Initial formatting of astroid
-rw-r--r--astroid/__init__.py30
-rw-r--r--astroid/__pkginfo__.py48
-rw-r--r--astroid/_ast.py10
-rw-r--r--astroid/arguments.py100
-rw-r--r--astroid/as_string.py383
-rw-r--r--astroid/bases.py195
-rw-r--r--astroid/brain/brain_argparse.py19
-rw-r--r--astroid/brain/brain_attrs.py12
-rw-r--r--astroid/brain/brain_builtin_inference.py249
-rw-r--r--astroid/brain/brain_collections.py26
-rw-r--r--astroid/brain/brain_curses.py8
-rw-r--r--astroid/brain/brain_dateutil.py12
-rw-r--r--astroid/brain/brain_fstrings.py37
-rw-r--r--astroid/brain/brain_functools.py49
-rw-r--r--astroid/brain/brain_gi.py47
-rw-r--r--astroid/brain/brain_hashlib.py29
-rw-r--r--astroid/brain/brain_io.py32
-rw-r--r--astroid/brain/brain_mechanize.py9
-rw-r--r--astroid/brain/brain_multiprocessing.py34
-rw-r--r--astroid/brain/brain_namedtuple_enum.py209
-rw-r--r--astroid/brain/brain_nose.py36
-rw-r--r--astroid/brain/brain_numpy.py62
-rw-r--r--astroid/brain/brain_pkg_resources.py9
-rw-r--r--astroid/brain/brain_pytest.py11
-rw-r--r--astroid/brain/brain_qt.py52
-rw-r--r--astroid/brain/brain_random.py44
-rw-r--r--astroid/brain/brain_re.py8
-rw-r--r--astroid/brain/brain_six.py33
-rw-r--r--astroid/brain/brain_ssl.py8
-rw-r--r--astroid/brain/brain_subprocess.py40
-rw-r--r--astroid/brain/brain_threading.py8
-rw-r--r--astroid/brain/brain_typing.py19
-rw-r--r--astroid/brain/brain_uuid.py6
-rw-r--r--astroid/builder.py93
-rw-r--r--astroid/context.py21
-rw-r--r--astroid/decorators.py20
-rw-r--r--astroid/exceptions.py33
-rw-r--r--astroid/helpers.py54
-rw-r--r--astroid/inference.py237
-rw-r--r--astroid/interpreter/_import/spec.py153
-rw-r--r--astroid/interpreter/_import/util.py3
-rw-r--r--astroid/interpreter/dunder_lookup.py31
-rw-r--r--astroid/interpreter/objectmodel.py169
-rw-r--r--astroid/manager.py125
-rw-r--r--astroid/mixins.py25
-rw-r--r--astroid/modutils.py133
-rw-r--r--astroid/node_classes.py698
-rw-r--r--astroid/nodes.py169
-rw-r--r--astroid/objects.py76
-rw-r--r--astroid/protocols.py276
-rw-r--r--astroid/raw_building.py114
-rw-r--r--astroid/rebuilder.py639
-rw-r--r--astroid/scoped_nodes.py465
-rw-r--r--astroid/test_utils.py27
-rw-r--r--astroid/tests/resources.py14
-rw-r--r--astroid/tests/unittest_brain.py1009
-rw-r--r--astroid/tests/unittest_brain_numpy.py509
-rw-r--r--astroid/tests/unittest_builder.py399
-rw-r--r--astroid/tests/unittest_helpers.py135
-rw-r--r--astroid/tests/unittest_inference.py2144
-rw-r--r--astroid/tests/unittest_lookup.py261
-rw-r--r--astroid/tests/unittest_manager.py195
-rw-r--r--astroid/tests/unittest_modutils.py230
-rw-r--r--astroid/tests/unittest_nodes.py484
-rw-r--r--astroid/tests/unittest_object_model.py279
-rw-r--r--astroid/tests/unittest_objects.py253
-rw-r--r--astroid/tests/unittest_protocols.py97
-rw-r--r--astroid/tests/unittest_python3.py239
-rw-r--r--astroid/tests/unittest_raw_building.py51
-rw-r--r--astroid/tests/unittest_regrtest.py128
-rw-r--r--astroid/tests/unittest_scoped_nodes.py1405
-rw-r--r--astroid/tests/unittest_transforms.py77
-rw-r--r--astroid/tests/unittest_utils.py62
-rw-r--r--astroid/transforms.py2
-rw-r--r--astroid/util.py44
75 files changed, 7773 insertions, 5679 deletions
diff --git a/astroid/__init__.py b/astroid/__init__.py
index 0ce6a8e9..524486d7 100644
--- a/astroid/__init__.py
+++ b/astroid/__init__.py
@@ -43,7 +43,7 @@ import sys
import wrapt
-_Context = enum.Enum('Context', 'Load Store Del')
+_Context = enum.Enum("Context", "Load Store Del")
Load = _Context.Load
Store = _Context.Store
Del = _Context.Del
@@ -51,6 +51,7 @@ del _Context
from .__pkginfo__ import version as __version__
+
# WARNING: internal imports order matters !
# pylint: disable=redefined-builtin
@@ -74,6 +75,7 @@ from astroid.util import Uninferable, YES
# make a manager instance (borg) accessible from astroid package
from astroid.manager import AstroidManager
+
MANAGER = AstroidManager()
del AstroidManager
@@ -93,6 +95,8 @@ def _inference_tip_cached(func, instance, args, kwargs, _cache={}):
original, copy = itertools.tee(result)
_cache[func, node] = list(copy)
return original
+
+
# pylint: enable=dangerous-default-value
@@ -117,19 +121,25 @@ def inference_tip(infer_function, raise_on_overwrite=False):
node. Use a predicate in the transform to prevent
excess overwrites.
"""
+
def transform(node, infer_function=infer_function):
- if (raise_on_overwrite
- and node._explicit_inference is not None
- and node._explicit_inference is not infer_function):
+ if (
+ raise_on_overwrite
+ and node._explicit_inference is not None
+ and node._explicit_inference is not infer_function
+ ):
raise InferenceOverwriteError(
"Inference already set to {existing_inference}. "
- "Trying to overwrite with {new_inference} for {node}"
- .format(existing_inference=infer_function,
- new_inference=node._explicit_inference,
- node=node))
+ "Trying to overwrite with {new_inference} for {node}".format(
+ existing_inference=infer_function,
+ new_inference=node._explicit_inference,
+ node=node,
+ )
+ )
# pylint: disable=no-value-for-parameter
node._explicit_inference = _inference_tip_cached(infer_function)
return node
+
return transform
@@ -146,11 +156,11 @@ def register_module_extender(manager, module_name, get_extension_mod):
# load brain plugins
-BRAIN_MODULES_DIR = os.path.join(os.path.dirname(__file__), 'brain')
+BRAIN_MODULES_DIR = os.path.join(os.path.dirname(__file__), "brain")
if BRAIN_MODULES_DIR not in sys.path:
# add it to the end of the list so user path take precedence
sys.path.append(BRAIN_MODULES_DIR)
# load modules in this directory
for module in os.listdir(BRAIN_MODULES_DIR):
- if module.endswith('.py'):
+ if module.endswith(".py"):
__import__(module[:-3])
diff --git a/astroid/__pkginfo__.py b/astroid/__pkginfo__.py
index cf3b1ba8..f14d6df9 100644
--- a/astroid/__pkginfo__.py
+++ b/astroid/__pkginfo__.py
@@ -17,41 +17,41 @@
"""astroid packaging information"""
-distname = 'astroid'
+distname = "astroid"
-modname = 'astroid'
+modname = "astroid"
-version = '2.1.0-dev'
-numversion = tuple(int(elem) for elem in version.split('.') if elem.isdigit())
+version = "2.1.0-dev"
+numversion = tuple(int(elem) for elem in version.split(".") if elem.isdigit())
extras_require = {}
install_requires = [
- 'lazy_object_proxy',
- 'six',
- 'wrapt',
+ "lazy_object_proxy",
+ "six",
+ "wrapt",
'typing;python_version<"3.5"',
- 'typed_ast;python_version<"3.7" and implementation_name== "cpython"'
-
+ 'typed_ast;python_version<"3.7" and implementation_name== "cpython"',
]
# pylint: disable=redefined-builtin; why license is a builtin anyway?
-license = 'LGPL'
+license = "LGPL"
-author = 'Python Code Quality Authority'
-author_email = 'code-quality@python.org'
+author = "Python Code Quality Authority"
+author_email = "code-quality@python.org"
mailinglist = "mailto://%s" % author_email
-web = 'https://github.com/PyCQA/astroid'
+web = "https://github.com/PyCQA/astroid"
description = "An abstract syntax tree for Python with inference support."
-classifiers = ["Topic :: Software Development :: Libraries :: Python Modules",
- "Topic :: Software Development :: Quality Assurance",
- "Programming Language :: Python",
- "Programming Language :: Python :: 3",
- "Programming Language :: Python :: 3.4",
- "Programming Language :: Python :: 3.5",
- "Programming Language :: Python :: 3.6",
- "Programming Language :: Python :: 3.7",
- "Programming Language :: Python :: Implementation :: CPython",
- "Programming Language :: Python :: Implementation :: PyPy",
- ]
+classifiers = [
+ "Topic :: Software Development :: Libraries :: Python Modules",
+ "Topic :: Software Development :: Quality Assurance",
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.4",
+ "Programming Language :: Python :: 3.5",
+ "Programming Language :: Python :: 3.6",
+ "Programming Language :: Python :: 3.7",
+ "Programming Language :: Python :: Implementation :: CPython",
+ "Programming Language :: Python :: Implementation :: PyPy",
+]
diff --git a/astroid/_ast.py b/astroid/_ast.py
index 8fc6472c..7868a7f3 100644
--- a/astroid/_ast.py
+++ b/astroid/_ast.py
@@ -11,7 +11,7 @@ except ImportError:
pass
-FunctionType = namedtuple('FunctionType', ['argtypes', 'returns'])
+FunctionType = namedtuple("FunctionType", ["argtypes", "returns"])
def _get_parser_module(parse_python_two: bool = False):
@@ -26,8 +26,7 @@ def _get_parser_module(parse_python_two: bool = False):
return parser_module or ast
-def _parse(string: str,
- parse_python_two: bool = False):
+def _parse(string: str, parse_python_two: bool = False):
return _get_parser_module(parse_python_two=parse_python_two).parse(string)
@@ -37,7 +36,4 @@ def parse_function_type_comment(type_comment: str) -> Optional[FunctionType]:
return None
func_type = _ast_py3.parse(type_comment, "<type_comment>", "func_type")
- return FunctionType(
- argtypes=func_type.argtypes,
- returns=func_type.returns,
- )
+ return FunctionType(argtypes=func_type.argtypes, returns=func_type.returns)
diff --git a/astroid/arguments.py b/astroid/arguments.py
index 11d430a6..c4bdc6d9 100644
--- a/astroid/arguments.py
+++ b/astroid/arguments.py
@@ -36,19 +36,18 @@ class CallSite:
self._unpacked_kwargs = self._unpack_keywords(keywords)
self.positional_arguments = [
- arg for arg in self._unpacked_args
- if arg is not util.Uninferable
+ arg for arg in self._unpacked_args if arg is not util.Uninferable
]
self.keyword_arguments = {
- key: value for key, value in self._unpacked_kwargs.items()
+ key: value
+ for key, value in self._unpacked_kwargs.items()
if value is not util.Uninferable
}
@classmethod
def from_call(cls, call_node):
"""Get a CallSite object from the given Call node."""
- callcontext = contextmod.CallContext(call_node.args,
- call_node.keywords)
+ callcontext = contextmod.CallContext(call_node.args, call_node.keywords)
return cls(callcontext)
def has_invalid_arguments(self):
@@ -126,7 +125,7 @@ class CallSite:
if inferred is util.Uninferable:
values.append(util.Uninferable)
continue
- if not hasattr(inferred, 'elts'):
+ if not hasattr(inferred, "elts"):
values.append(util.Uninferable)
continue
values.extend(inferred.elts)
@@ -143,10 +142,13 @@ class CallSite:
context: Inference context object
"""
if name in self.duplicated_keywords:
- raise exceptions.InferenceError('The arguments passed to {func!r} '
- ' have duplicate keywords.',
- call_site=self, func=funcnode,
- arg=name, context=context)
+ raise exceptions.InferenceError(
+ "The arguments passed to {func!r} " " have duplicate keywords.",
+ call_site=self,
+ func=funcnode,
+ arg=name,
+ context=context,
+ )
# Look into the keywords first, maybe it's already there.
try:
@@ -157,18 +159,23 @@ class CallSite:
# Too many arguments given and no variable arguments.
if len(self.positional_arguments) > len(funcnode.args.args):
if not funcnode.args.vararg:
- raise exceptions.InferenceError('Too many positional arguments '
- 'passed to {func!r} that does '
- 'not have *args.',
- call_site=self, func=funcnode,
- arg=name, context=context)
+ raise exceptions.InferenceError(
+ "Too many positional arguments "
+ "passed to {func!r} that does "
+ "not have *args.",
+ call_site=self,
+ func=funcnode,
+ arg=name,
+ context=context,
+ )
- positional = self.positional_arguments[:len(funcnode.args.args)]
- vararg = self.positional_arguments[len(funcnode.args.args):]
+ positional = self.positional_arguments[: len(funcnode.args.args)]
+ vararg = self.positional_arguments[len(funcnode.args.args) :]
argindex = funcnode.args.find_argname(name)[0]
kwonlyargs = {arg.name for arg in funcnode.args.kwonlyargs}
kwargs = {
- key: value for key, value in self.keyword_arguments.items()
+ key: value
+ for key, value in self.keyword_arguments.items()
if key not in kwonlyargs
}
# If there are too few positionals compared to
@@ -184,7 +191,7 @@ class CallSite:
if argindex is not None:
# 2. first argument of instance/class method
- if argindex == 0 and funcnode.type in ('method', 'classmethod'):
+ if argindex == 0 and funcnode.type in ("method", "classmethod"):
if context.boundnode is not None:
boundnode = context.boundnode
else:
@@ -198,18 +205,18 @@ class CallSite:
# first argument is always the class.
method_scope = funcnode.parent.scope()
if method_scope is boundnode.metaclass():
- return iter((boundnode, ))
+ return iter((boundnode,))
- if funcnode.type == 'method':
+ if funcnode.type == "method":
if not isinstance(boundnode, bases.Instance):
boundnode = bases.Instance(boundnode)
return iter((boundnode,))
- if funcnode.type == 'classmethod':
+ if funcnode.type == "classmethod":
return iter((boundnode,))
# if we have a method, extract one position
# from the index, so we'll take in account
# the extra parameter represented by `self` or `cls`
- if funcnode.type in ('method', 'classmethod'):
+ if funcnode.type in ("method", "classmethod"):
argindex -= 1
# 2. search arg index
try:
@@ -227,13 +234,20 @@ class CallSite:
"{keyword_arguments!r}.",
keyword_arguments=self.keyword_arguments,
unpacked_kwargs=self._unpacked_kwargs,
- call_site=self, func=funcnode, arg=name, context=context)
- kwarg = nodes.Dict(lineno=funcnode.args.lineno,
- col_offset=funcnode.args.col_offset,
- parent=funcnode.args)
- kwarg.postinit([(nodes.const_factory(key), value)
- for key, value in kwargs.items()])
- return iter((kwarg, ))
+ call_site=self,
+ func=funcnode,
+ arg=name,
+ context=context,
+ )
+ kwarg = nodes.Dict(
+ lineno=funcnode.args.lineno,
+ col_offset=funcnode.args.col_offset,
+ parent=funcnode.args,
+ )
+ kwarg.postinit(
+ [(nodes.const_factory(key), value) for key, value in kwargs.items()]
+ )
+ return iter((kwarg,))
if funcnode.args.vararg == name:
# It wants all the args that were passed into
# the call site.
@@ -244,18 +258,28 @@ class CallSite:
"correspond to {positional_arguments!r}.",
positional_arguments=self.positional_arguments,
unpacked_args=self._unpacked_args,
- call_site=self, func=funcnode, arg=name, context=context)
- args = nodes.Tuple(lineno=funcnode.args.lineno,
- col_offset=funcnode.args.col_offset,
- parent=funcnode.args)
+ call_site=self,
+ func=funcnode,
+ arg=name,
+ context=context,
+ )
+ args = nodes.Tuple(
+ lineno=funcnode.args.lineno,
+ col_offset=funcnode.args.col_offset,
+ parent=funcnode.args,
+ )
args.postinit(vararg)
- return iter((args, ))
+ return iter((args,))
# Check if it's a default parameter.
try:
return funcnode.args.default_value(name).infer(context)
except exceptions.NoDefault:
pass
- raise exceptions.InferenceError('No value found for argument {name} to '
- '{func!r}', call_site=self,
- func=funcnode, arg=name, context=context)
+ raise exceptions.InferenceError(
+ "No value found for argument {name} to " "{func!r}",
+ call_site=self,
+ func=funcnode,
+ arg=name,
+ context=context,
+ )
diff --git a/astroid/as_string.py b/astroid/as_string.py
index 4528bb0b..bd4a8c4b 100644
--- a/astroid/as_string.py
+++ b/astroid/as_string.py
@@ -26,7 +26,7 @@ import sys
# pylint: disable=unused-argument
-DOC_NEWLINE = '\0'
+DOC_NEWLINE = "\0"
class AsStringVisitor:
@@ -37,25 +37,24 @@ class AsStringVisitor:
def __call__(self, node):
"""Makes this visitor behave as a simple function"""
- return node.accept(self).replace(DOC_NEWLINE, '\n')
+ return node.accept(self).replace(DOC_NEWLINE, "\n")
def _docs_dedent(self, doc):
"""Stop newlines in docs being indented by self._stmt_list"""
- return '\n%s"""%s"""' % (self.indent, doc.replace('\n', DOC_NEWLINE))
+ return '\n%s"""%s"""' % (self.indent, doc.replace("\n", DOC_NEWLINE))
def _stmt_list(self, stmts, indent=True):
"""return a list of nodes to string"""
- stmts = '\n'.join(
- [nstr for nstr in [n.accept(self) for n in stmts] if nstr])
+ stmts = "\n".join([nstr for nstr in [n.accept(self) for n in stmts] if nstr])
if indent:
- return self.indent + stmts.replace('\n', '\n' + self.indent)
+ return self.indent + stmts.replace("\n", "\n" + self.indent)
return stmts
def _precedence_parens(self, node, child, is_left=True):
"""Wrap child in parens only if required to keep same semantics"""
if self._should_wrap(node, child, is_left):
- return '(%s)' % child.accept(self)
+ return "(%s)" % child.accept(self)
return child.accept(self)
@@ -71,15 +70,16 @@ class AsStringVisitor:
# 3 * (4 + 5)
return True
- if (node_precedence == child_precedence and
- is_left != node.op_left_associative()):
+ if (
+ node_precedence == child_precedence
+ and is_left != node.op_left_associative()
+ ):
# 3 - (4 - 5)
# (2**3)**4
return True
return False
-
## visit_<node> methods ###########################################
def visit_arguments(self, node):
@@ -93,9 +93,8 @@ class AsStringVisitor:
def visit_assert(self, node):
"""return an astroid.Assert node as string"""
if node.fail:
- return 'assert %s, %s' % (node.test.accept(self),
- node.fail.accept(self))
- return 'assert %s' % node.test.accept(self)
+ return "assert %s, %s" % (node.test.accept(self), node.fail.accept(self))
+ return "assert %s" % node.test.accept(self)
def visit_assignname(self, node):
"""return an astroid.AssName node as string"""
@@ -103,12 +102,12 @@ class AsStringVisitor:
def visit_assign(self, node):
"""return an astroid.Assign node as string"""
- lhs = ' = '.join([n.accept(self) for n in node.targets])
- return '%s = %s' % (lhs, node.value.accept(self))
+ lhs = " = ".join([n.accept(self) for n in node.targets])
+ return "%s = %s" % (lhs, node.value.accept(self))
def visit_augassign(self, node):
"""return an astroid.AugAssign node as string"""
- return '%s %s %s' % (node.target.accept(self), node.op, node.value.accept(self))
+ return "%s %s %s" % (node.target.accept(self), node.op, node.value.accept(self))
def visit_annassign(self, node):
"""Return an astroid.AugAssign node as string"""
@@ -116,30 +115,30 @@ class AsStringVisitor:
target = node.target.accept(self)
annotation = node.annotation.accept(self)
if node.value is None:
- return '%s: %s' % (target, annotation)
- return '%s: %s = %s' % (target, annotation, node.value.accept(self))
+ return "%s: %s" % (target, annotation)
+ return "%s: %s = %s" % (target, annotation, node.value.accept(self))
def visit_repr(self, node):
"""return an astroid.Repr node as string"""
- return '`%s`' % node.value.accept(self)
+ return "`%s`" % node.value.accept(self)
def visit_binop(self, node):
"""return an astroid.BinOp node as string"""
left = self._precedence_parens(node, node.left)
right = self._precedence_parens(node, node.right, is_left=False)
- if node.op == '**':
- return '%s%s%s' % (left, node.op, right)
+ if node.op == "**":
+ return "%s%s%s" % (left, node.op, right)
- return '%s %s %s' % (left, node.op, right)
+ return "%s %s %s" % (left, node.op, right)
def visit_boolop(self, node):
"""return an astroid.BoolOp node as string"""
- values = ['%s' % self._precedence_parens(node, n) for n in node.values]
- return (' %s ' % node.op).join(values)
+ values = ["%s" % self._precedence_parens(node, n) for n in node.values]
+ return (" %s " % node.op).join(values)
def visit_break(self, node):
"""return an astroid.Break node as string"""
- return 'break'
+ return "break"
def visit_call(self, node):
"""return an astroid.Call node as string"""
@@ -151,55 +150,64 @@ class AsStringVisitor:
keywords = []
args.extend(keywords)
- return '%s(%s)' % (expr_str, ', '.join(args))
+ return "%s(%s)" % (expr_str, ", ".join(args))
def visit_classdef(self, node):
"""return an astroid.ClassDef node as string"""
- decorate = node.decorators.accept(self) if node.decorators else ''
- bases = ', '.join([n.accept(self) for n in node.bases])
+ decorate = node.decorators.accept(self) if node.decorators else ""
+ bases = ", ".join([n.accept(self) for n in node.bases])
if sys.version_info[0] == 2:
- bases = '(%s)' % bases if bases else ''
+ bases = "(%s)" % bases if bases else ""
else:
metaclass = node.metaclass()
if metaclass and not node.has_metaclass_hack():
if bases:
- bases = '(%s, metaclass=%s)' % (bases, metaclass.name)
+ bases = "(%s, metaclass=%s)" % (bases, metaclass.name)
else:
- bases = '(metaclass=%s)' % metaclass.name
+ bases = "(metaclass=%s)" % metaclass.name
else:
- bases = '(%s)' % bases if bases else ''
- docs = self._docs_dedent(node.doc) if node.doc else ''
- return '\n\n%sclass %s%s:%s\n%s\n' % (decorate, node.name, bases, docs,
- self._stmt_list(node.body))
+ bases = "(%s)" % bases if bases else ""
+ docs = self._docs_dedent(node.doc) if node.doc else ""
+ return "\n\n%sclass %s%s:%s\n%s\n" % (
+ decorate,
+ node.name,
+ bases,
+ docs,
+ self._stmt_list(node.body),
+ )
def visit_compare(self, node):
"""return an astroid.Compare node as string"""
- rhs_str = ' '.join([
- '%s %s' % (op, self._precedence_parens(node, expr, is_left=False))
- for op, expr in node.ops
- ])
- return '%s %s' % (self._precedence_parens(node, node.left), rhs_str)
+ rhs_str = " ".join(
+ [
+ "%s %s" % (op, self._precedence_parens(node, expr, is_left=False))
+ for op, expr in node.ops
+ ]
+ )
+ return "%s %s" % (self._precedence_parens(node, node.left), rhs_str)
def visit_comprehension(self, node):
"""return an astroid.Comprehension node as string"""
- ifs = ''.join([' if %s' % n.accept(self) for n in node.ifs])
- return 'for %s in %s%s' % (node.target.accept(self),
- node.iter.accept(self), ifs)
+ ifs = "".join([" if %s" % n.accept(self) for n in node.ifs])
+ return "for %s in %s%s" % (
+ node.target.accept(self),
+ node.iter.accept(self),
+ ifs,
+ )
def visit_const(self, node):
"""return an astroid.Const node as string"""
if node.value is Ellipsis:
- return '...'
+ return "..."
return repr(node.value)
def visit_continue(self, node):
"""return an astroid.Continue node as string"""
- return 'continue'
+ return "continue"
- def visit_delete(self, node): # XXX check if correct
+ def visit_delete(self, node): # XXX check if correct
"""return an astroid.Delete node as string"""
- return 'del %s' % ', '.join([child.accept(self)
- for child in node.targets])
+ return "del %s" % ", ".join([child.accept(self) for child in node.targets])
def visit_delattr(self, node):
"""return an astroid.DelAttr node as string"""
@@ -211,29 +219,32 @@ class AsStringVisitor:
def visit_decorators(self, node):
"""return an astroid.Decorators node as string"""
- return '@%s\n' % '\n@'.join([item.accept(self) for item in node.nodes])
+ return "@%s\n" % "\n@".join([item.accept(self) for item in node.nodes])
def visit_dict(self, node):
"""return an astroid.Dict node as string"""
- return '{%s}' % ', '.join(self._visit_dict(node))
+ return "{%s}" % ", ".join(self._visit_dict(node))
def _visit_dict(self, node):
for key, value in node.items:
key = key.accept(self)
value = value.accept(self)
- if key == '**':
+ if key == "**":
# It can only be a DictUnpack node.
yield key + value
else:
- yield '%s: %s' % (key, value)
+ yield "%s: %s" % (key, value)
def visit_dictunpack(self, node):
- return '**'
+ return "**"
def visit_dictcomp(self, node):
"""return an astroid.DictComp node as string"""
- return '{%s: %s %s}' % (node.key.accept(self), node.value.accept(self),
- ' '.join([n.accept(self) for n in node.generators]))
+ return "{%s: %s %s}" % (
+ node.key.accept(self),
+ node.value.accept(self),
+ " ".join([n.accept(self) for n in node.generators]),
+ )
def visit_expr(self, node):
"""return an astroid.Discard node as string"""
@@ -241,131 +252,147 @@ class AsStringVisitor:
def visit_emptynode(self, node):
"""dummy method for visiting an Empty node"""
- return ''
+ return ""
def visit_excepthandler(self, node):
if node.type:
if node.name:
- excs = 'except %s, %s' % (node.type.accept(self),
- node.name.accept(self))
+ excs = "except %s, %s" % (
+ node.type.accept(self),
+ node.name.accept(self),
+ )
else:
- excs = 'except %s' % node.type.accept(self)
+ excs = "except %s" % node.type.accept(self)
else:
- excs = 'except'
- return '%s:\n%s' % (excs, self._stmt_list(node.body))
+ excs = "except"
+ return "%s:\n%s" % (excs, self._stmt_list(node.body))
def visit_ellipsis(self, node):
"""return an astroid.Ellipsis node as string"""
- return '...'
+ return "..."
def visit_empty(self, node):
"""return an Empty node as string"""
- return ''
+ return ""
def visit_exec(self, node):
"""return an astroid.Exec node as string"""
if node.locals:
- return 'exec %s in %s, %s' % (node.expr.accept(self),
- node.locals.accept(self),
- node.globals.accept(self))
+ return "exec %s in %s, %s" % (
+ node.expr.accept(self),
+ node.locals.accept(self),
+ node.globals.accept(self),
+ )
if node.globals:
- return 'exec %s in %s' % (node.expr.accept(self),
- node.globals.accept(self))
- return 'exec %s' % node.expr.accept(self)
+ return "exec %s in %s" % (node.expr.accept(self), node.globals.accept(self))
+ return "exec %s" % node.expr.accept(self)
def visit_extslice(self, node):
"""return an astroid.ExtSlice node as string"""
- return ', '.join([dim.accept(self) for dim in node.dims])
+ return ", ".join([dim.accept(self) for dim in node.dims])
def visit_for(self, node):
"""return an astroid.For node as string"""
- fors = 'for %s in %s:\n%s' % (node.target.accept(self),
- node.iter.accept(self),
- self._stmt_list(node.body))
+ fors = "for %s in %s:\n%s" % (
+ node.target.accept(self),
+ node.iter.accept(self),
+ self._stmt_list(node.body),
+ )
if node.orelse:
- fors = '%s\nelse:\n%s' % (fors, self._stmt_list(node.orelse))
+ fors = "%s\nelse:\n%s" % (fors, self._stmt_list(node.orelse))
return fors
def visit_importfrom(self, node):
"""return an astroid.ImportFrom node as string"""
- return 'from %s import %s' % ('.' * (node.level or 0) + node.modname,
- _import_string(node.names))
+ return "from %s import %s" % (
+ "." * (node.level or 0) + node.modname,
+ _import_string(node.names),
+ )
def visit_functiondef(self, node):
"""return an astroid.Function node as string"""
- decorate = node.decorators.accept(self) if node.decorators else ''
- docs = self._docs_dedent(node.doc) if node.doc else ''
- trailer = ':'
+ decorate = node.decorators.accept(self) if node.decorators else ""
+ docs = self._docs_dedent(node.doc) if node.doc else ""
+ trailer = ":"
if node.returns:
- return_annotation = '->' + node.returns.as_string()
+ return_annotation = "->" + node.returns.as_string()
trailer = return_annotation + ":"
def_format = "\n%sdef %s(%s)%s%s\n%s"
- return def_format % (decorate, node.name,
- node.args.accept(self),
- trailer, docs,
- self._stmt_list(node.body))
+ return def_format % (
+ decorate,
+ node.name,
+ node.args.accept(self),
+ trailer,
+ docs,
+ self._stmt_list(node.body),
+ )
def visit_generatorexp(self, node):
"""return an astroid.GeneratorExp node as string"""
- return '(%s %s)' % (node.elt.accept(self),
- ' '.join([n.accept(self) for n in node.generators]))
+ return "(%s %s)" % (
+ node.elt.accept(self),
+ " ".join([n.accept(self) for n in node.generators]),
+ )
def visit_attribute(self, node):
"""return an astroid.Getattr node as string"""
- return '%s.%s' % (self._precedence_parens(node, node.expr), node.attrname)
+ return "%s.%s" % (self._precedence_parens(node, node.expr), node.attrname)
def visit_global(self, node):
"""return an astroid.Global node as string"""
- return 'global %s' % ', '.join(node.names)
+ return "global %s" % ", ".join(node.names)
def visit_if(self, node):
"""return an astroid.If node as string"""
- ifs = ['if %s:\n%s' % (node.test.accept(self), self._stmt_list(node.body))]
+ ifs = ["if %s:\n%s" % (node.test.accept(self), self._stmt_list(node.body))]
if node.has_elif_block():
- ifs.append('el%s' % self._stmt_list(node.orelse, indent=False))
+ ifs.append("el%s" % self._stmt_list(node.orelse, indent=False))
elif node.orelse:
- ifs.append('else:\n%s' % self._stmt_list(node.orelse))
- return '\n'.join(ifs)
+ ifs.append("else:\n%s" % self._stmt_list(node.orelse))
+ return "\n".join(ifs)
def visit_ifexp(self, node):
"""return an astroid.IfExp node as string"""
- return '%s if %s else %s' % (
+ return "%s if %s else %s" % (
self._precedence_parens(node, node.body, is_left=True),
self._precedence_parens(node, node.test, is_left=True),
- self._precedence_parens(node, node.orelse, is_left=False))
+ self._precedence_parens(node, node.orelse, is_left=False),
+ )
def visit_import(self, node):
"""return an astroid.Import node as string"""
- return 'import %s' % _import_string(node.names)
+ return "import %s" % _import_string(node.names)
def visit_keyword(self, node):
"""return an astroid.Keyword node as string"""
if node.arg is None:
- return '**%s' % node.value.accept(self)
- return '%s=%s' % (node.arg, node.value.accept(self))
+ return "**%s" % node.value.accept(self)
+ return "%s=%s" % (node.arg, node.value.accept(self))
def visit_lambda(self, node):
"""return an astroid.Lambda node as string"""
args = node.args.accept(self)
body = node.body.accept(self)
if args:
- return 'lambda %s: %s' % (args, body)
+ return "lambda %s: %s" % (args, body)
- return 'lambda: %s' % body
+ return "lambda: %s" % body
def visit_list(self, node):
"""return an astroid.List node as string"""
- return '[%s]' % ', '.join([child.accept(self) for child in node.elts])
+ return "[%s]" % ", ".join([child.accept(self) for child in node.elts])
def visit_listcomp(self, node):
"""return an astroid.ListComp node as string"""
- return '[%s %s]' % (node.elt.accept(self),
- ' '.join([n.accept(self) for n in node.generators]))
+ return "[%s %s]" % (
+ node.elt.accept(self),
+ " ".join([n.accept(self) for n in node.generators]),
+ )
def visit_module(self, node):
"""return an astroid.Module node as string"""
- docs = '"""%s"""\n\n' % node.doc if node.doc else ''
- return docs + '\n'.join([n.accept(self) for n in node.body]) + '\n\n'
+ docs = '"""%s"""\n\n' % node.doc if node.doc else ""
+ return docs + "\n".join([n.accept(self) for n in node.body]) + "\n\n"
def visit_name(self, node):
"""return an astroid.Name node as string"""
@@ -373,40 +400,41 @@ class AsStringVisitor:
def visit_pass(self, node):
"""return an astroid.Pass node as string"""
- return 'pass'
+ return "pass"
def visit_print(self, node):
"""return an astroid.Print node as string"""
- nodes = ', '.join([n.accept(self) for n in node.values])
+ nodes = ", ".join([n.accept(self) for n in node.values])
if not node.nl:
- nodes = '%s,' % nodes
+ nodes = "%s," % nodes
if node.dest:
- return 'print >> %s, %s' % (node.dest.accept(self), nodes)
- return 'print %s' % nodes
+ return "print >> %s, %s" % (node.dest.accept(self), nodes)
+ return "print %s" % nodes
def visit_raise(self, node):
"""return an astroid.Raise node as string"""
if node.exc:
if node.inst:
if node.tback:
- return 'raise %s, %s, %s' % (node.exc.accept(self),
- node.inst.accept(self),
- node.tback.accept(self))
- return 'raise %s, %s' % (node.exc.accept(self),
- node.inst.accept(self))
- return 'raise %s' % node.exc.accept(self)
- return 'raise'
+ return "raise %s, %s, %s" % (
+ node.exc.accept(self),
+ node.inst.accept(self),
+ node.tback.accept(self),
+ )
+ return "raise %s, %s" % (node.exc.accept(self), node.inst.accept(self))
+ return "raise %s" % node.exc.accept(self)
+ return "raise"
def visit_return(self, node):
"""return an astroid.Return node as string"""
if node.is_tuple_return() and len(node.value.elts) > 1:
elts = [child.accept(self) for child in node.value.elts]
- return 'return %s' % ', '.join(elts)
+ return "return %s" % ", ".join(elts)
if node.value:
- return 'return %s' % node.value.accept(self)
+ return "return %s" % node.value.accept(self)
- return 'return'
+ return "return"
def visit_index(self, node):
"""return an astroid.Index node as string"""
@@ -414,81 +442,85 @@ class AsStringVisitor:
def visit_set(self, node):
"""return an astroid.Set node as string"""
- return '{%s}' % ', '.join([child.accept(self) for child in node.elts])
+ return "{%s}" % ", ".join([child.accept(self) for child in node.elts])
def visit_setcomp(self, node):
"""return an astroid.SetComp node as string"""
- return '{%s %s}' % (node.elt.accept(self),
- ' '.join([n.accept(self) for n in node.generators]))
+ return "{%s %s}" % (
+ node.elt.accept(self),
+ " ".join([n.accept(self) for n in node.generators]),
+ )
def visit_slice(self, node):
"""return an astroid.Slice node as string"""
- lower = node.lower.accept(self) if node.lower else ''
- upper = node.upper.accept(self) if node.upper else ''
- step = node.step.accept(self) if node.step else ''
+ lower = node.lower.accept(self) if node.lower else ""
+ upper = node.upper.accept(self) if node.upper else ""
+ step = node.step.accept(self) if node.step else ""
if step:
- return '%s:%s:%s' % (lower, upper, step)
- return '%s:%s' % (lower, upper)
+ return "%s:%s:%s" % (lower, upper, step)
+ return "%s:%s" % (lower, upper)
def visit_subscript(self, node):
"""return an astroid.Subscript node as string"""
idx = node.slice
- if idx.__class__.__name__.lower() == 'index':
+ if idx.__class__.__name__.lower() == "index":
idx = idx.value
idxstr = idx.accept(self)
- if idx.__class__.__name__.lower() == 'tuple' and idx.elts:
+ if idx.__class__.__name__.lower() == "tuple" and idx.elts:
# Remove parenthesis in tuple and extended slice.
# a[(::1, 1:)] is not valid syntax.
idxstr = idxstr[1:-1]
- return '%s[%s]' % (self._precedence_parens(node, node.value), idxstr)
+ return "%s[%s]" % (self._precedence_parens(node, node.value), idxstr)
def visit_tryexcept(self, node):
"""return an astroid.TryExcept node as string"""
- trys = ['try:\n%s' % self._stmt_list(node.body)]
+ trys = ["try:\n%s" % self._stmt_list(node.body)]
for handler in node.handlers:
trys.append(handler.accept(self))
if node.orelse:
- trys.append('else:\n%s' % self._stmt_list(node.orelse))
- return '\n'.join(trys)
+ trys.append("else:\n%s" % self._stmt_list(node.orelse))
+ return "\n".join(trys)
def visit_tryfinally(self, node):
"""return an astroid.TryFinally node as string"""
- return 'try:\n%s\nfinally:\n%s' % (self._stmt_list(node.body),
- self._stmt_list(node.finalbody))
+ return "try:\n%s\nfinally:\n%s" % (
+ self._stmt_list(node.body),
+ self._stmt_list(node.finalbody),
+ )
def visit_tuple(self, node):
"""return an astroid.Tuple node as string"""
if len(node.elts) == 1:
- return '(%s, )' % node.elts[0].accept(self)
- return '(%s)' % ', '.join([child.accept(self) for child in node.elts])
+ return "(%s, )" % node.elts[0].accept(self)
+ return "(%s)" % ", ".join([child.accept(self) for child in node.elts])
def visit_unaryop(self, node):
"""return an astroid.UnaryOp node as string"""
- if node.op == 'not':
- operator = 'not '
+ if node.op == "not":
+ operator = "not "
else:
operator = node.op
- return '%s%s' % (operator, self._precedence_parens(node, node.operand))
+ return "%s%s" % (operator, self._precedence_parens(node, node.operand))
def visit_while(self, node):
"""return an astroid.While node as string"""
- whiles = 'while %s:\n%s' % (node.test.accept(self),
- self._stmt_list(node.body))
+ whiles = "while %s:\n%s" % (node.test.accept(self), self._stmt_list(node.body))
if node.orelse:
- whiles = '%s\nelse:\n%s' % (whiles, self._stmt_list(node.orelse))
+ whiles = "%s\nelse:\n%s" % (whiles, self._stmt_list(node.orelse))
return whiles
- def visit_with(self, node): # 'with' without 'as' is possible
+ def visit_with(self, node): # 'with' without 'as' is possible
"""return an astroid.With node as string"""
- items = ', '.join(('%s' % expr.accept(self)) +
- (vars and ' as %s' % (vars.accept(self)) or '')
- for expr, vars in node.items)
- return 'with %s:\n%s' % (items, self._stmt_list(node.body))
+ items = ", ".join(
+ ("%s" % expr.accept(self)) + (vars and " as %s" % (vars.accept(self)) or "")
+ for expr, vars in node.items
+ )
+ return "with %s:\n%s" % (items, self._stmt_list(node.body))
def visit_yield(self, node):
"""yield an ast.Yield node as string"""
yi_val = (" " + node.value.accept(self)) if node.value else ""
- expr = 'yield' + yi_val
+ expr = "yield" + yi_val
if node.parent.is_statement:
return expr
@@ -516,31 +548,35 @@ class AsStringVisitor3(AsStringVisitor):
def visit_excepthandler(self, node):
if node.type:
if node.name:
- excs = 'except %s as %s' % (node.type.accept(self),
- node.name.accept(self))
+ excs = "except %s as %s" % (
+ node.type.accept(self),
+ node.name.accept(self),
+ )
else:
- excs = 'except %s' % node.type.accept(self)
+ excs = "except %s" % node.type.accept(self)
else:
- excs = 'except'
- return '%s:\n%s' % (excs, self._stmt_list(node.body))
+ excs = "except"
+ return "%s:\n%s" % (excs, self._stmt_list(node.body))
def visit_nonlocal(self, node):
"""return an astroid.Nonlocal node as string"""
- return 'nonlocal %s' % ', '.join(node.names)
+ return "nonlocal %s" % ", ".join(node.names)
def visit_raise(self, node):
"""return an astroid.Raise node as string"""
if node.exc:
if node.cause:
- return 'raise %s from %s' % (node.exc.accept(self),
- node.cause.accept(self))
- return 'raise %s' % node.exc.accept(self)
- return 'raise'
+ return "raise %s from %s" % (
+ node.exc.accept(self),
+ node.cause.accept(self),
+ )
+ return "raise %s" % node.exc.accept(self)
+ return "raise"
def visit_yieldfrom(self, node):
""" Return an astroid.YieldFrom node as string. """
yi_val = (" " + node.value.accept(self)) if node.value else ""
- expr = 'yield from' + yi_val
+ expr = "yield from" + yi_val
if node.parent.is_statement:
return expr
@@ -548,34 +584,35 @@ class AsStringVisitor3(AsStringVisitor):
def visit_asyncfunctiondef(self, node):
function = super(AsStringVisitor3, self).visit_functiondef(node)
- return 'async ' + function.strip()
+ return "async " + function.strip()
def visit_await(self, node):
- return 'await %s' % node.value.accept(self)
+ return "await %s" % node.value.accept(self)
def visit_asyncwith(self, node):
- return 'async %s' % self.visit_with(node)
+ return "async %s" % self.visit_with(node)
def visit_asyncfor(self, node):
- return 'async %s' % self.visit_for(node)
+ return "async %s" % self.visit_for(node)
def visit_joinedstr(self, node):
# Special treatment for constants,
# as we want to join literals not reprs
- string = ''.join(
- value.value if type(value).__name__ == 'Const'
- else value.accept(self)
+ string = "".join(
+ value.value if type(value).__name__ == "Const" else value.accept(self)
for value in node.values
)
return "f'%s'" % string
def visit_formattedvalue(self, node):
- return '{%s}' % node.value.accept(self)
+ return "{%s}" % node.value.accept(self)
def visit_comprehension(self, node):
"""return an astroid.Comprehension node as string"""
- return '%s%s' % ('async ' if node.is_async else '',
- super(AsStringVisitor3, self).visit_comprehension(node))
+ return "%s%s" % (
+ "async " if node.is_async else "",
+ super(AsStringVisitor3, self).visit_comprehension(node),
+ )
def _import_string(names):
@@ -583,14 +620,14 @@ def _import_string(names):
_names = []
for name, asname in names:
if asname is not None:
- _names.append('%s as %s' % (name, asname))
+ _names.append("%s as %s" % (name, asname))
else:
_names.append(name)
- return ', '.join(_names)
+ return ", ".join(_names)
if sys.version_info >= (3, 0):
AsStringVisitor = AsStringVisitor3
# This sets the default indent to 4 spaces.
-to_code = AsStringVisitor(' ')
+to_code = AsStringVisitor(" ")
diff --git a/astroid/bases.py b/astroid/bases.py
index 6f941cd8..e783fe01 100644
--- a/astroid/bases.py
+++ b/astroid/bases.py
@@ -26,20 +26,20 @@ from astroid import context as contextmod
from astroid import exceptions
from astroid import util
-objectmodel = util.lazy_import('interpreter.objectmodel')
-helpers = util.lazy_import('helpers')
+objectmodel = util.lazy_import("interpreter.objectmodel")
+helpers = util.lazy_import("helpers")
BUILTINS = builtins.__name__
-manager = util.lazy_import('manager')
+manager = util.lazy_import("manager")
MANAGER = manager.AstroidManager()
if sys.version_info >= (3, 0):
# TODO: check if needs special treatment
- BUILTINS = 'builtins'
- BOOL_SPECIAL_METHOD = '__bool__'
+ BUILTINS = "builtins"
+ BOOL_SPECIAL_METHOD = "__bool__"
else:
- BUILTINS = '__builtin__'
- BOOL_SPECIAL_METHOD = '__nonzero__'
-PROPERTIES = {BUILTINS + '.property', 'abc.abstractproperty'}
+ BUILTINS = "__builtin__"
+ BOOL_SPECIAL_METHOD = "__nonzero__"
+PROPERTIES = {BUILTINS + ".property", "abc.abstractproperty"}
# List of possible property names. We use this list in order
# to see if a method is a property or not. This should be
# pretty reliable and fast, the alternative being to check each
@@ -48,17 +48,28 @@ PROPERTIES = {BUILTINS + '.property', 'abc.abstractproperty'}
# Also, these aren't qualified, because each project can
# define them, we shouldn't expect to know every possible
# property-like decorator!
-POSSIBLE_PROPERTIES = {"cached_property", "cachedproperty",
- "lazyproperty", "lazy_property", "reify",
- "lazyattribute", "lazy_attribute",
- "LazyProperty", "lazy", "cache_readonly"}
+POSSIBLE_PROPERTIES = {
+ "cached_property",
+ "cachedproperty",
+ "lazyproperty",
+ "lazy_property",
+ "reify",
+ "lazyattribute",
+ "lazy_attribute",
+ "LazyProperty",
+ "lazy",
+ "cache_readonly",
+}
def _is_property(meth):
if PROPERTIES.intersection(meth.decoratornames()):
return True
- stripped = {name.split(".")[-1] for name in meth.decoratornames()
- if name is not util.Uninferable}
+ stripped = {
+ name.split(".")[-1]
+ for name in meth.decoratornames()
+ if name is not util.Uninferable
+ }
if any(name in stripped for name in POSSIBLE_PROPERTIES):
return True
@@ -69,10 +80,10 @@ def _is_property(meth):
inferred = helpers.safe_infer(decorator)
if inferred is None or inferred is util.Uninferable:
continue
- if inferred.__class__.__name__ == 'ClassDef':
+ if inferred.__class__.__name__ == "ClassDef":
for base_class in inferred.bases:
module, _ = base_class.lookup(base_class.name)
- if module.name == BUILTINS and base_class.name == 'property':
+ if module.name == BUILTINS and base_class.name == "property":
return True
return False
@@ -87,15 +98,15 @@ class Proxy:
if new instance attributes are created. See the Const class
"""
- _proxied = None # proxied object may be set by class or by instance
+ _proxied = None # proxied object may be set by class or by instance
def __init__(self, proxied=None):
if proxied is not None:
self._proxied = proxied
def __getattr__(self, name):
- if name == '_proxied':
- return getattr(self.__class__, '_proxied')
+ if name == "_proxied":
+ return getattr(self.__class__, "_proxied")
if name in self.__dict__:
return self.__dict__[name]
return getattr(self._proxied, name)
@@ -132,15 +143,18 @@ def _infer_stmts(stmts, context, frame=None):
inferred = True
if not inferred:
raise exceptions.InferenceError(
- 'Inference failed for all members of {stmts!r}.',
- stmts=stmts, frame=frame, context=context)
+ "Inference failed for all members of {stmts!r}.",
+ stmts=stmts,
+ frame=frame,
+ context=context,
+ )
def _infer_method_result_truth(instance, method_name, context):
# Get the method from the instance and try to infer
# its return's truth value.
meth = next(instance.igetattr(method_name, context=context), None)
- if meth and hasattr(meth, 'infer_call_result'):
+ if meth and hasattr(meth, "infer_call_result"):
if not meth.callable():
return util.Uninferable
try:
@@ -161,7 +175,7 @@ class BaseInstance(Proxy):
special_attributes = None
def display_type(self):
- return 'Instance of'
+ return "Instance of"
def getattr(self, name, context=None, lookupclass=True):
try:
@@ -173,20 +187,18 @@ class BaseInstance(Proxy):
if lookupclass:
# Class attributes not available through the instance
# unless they are explicitly defined.
- return self._proxied.getattr(name, context,
- class_context=False)
+ return self._proxied.getattr(name, context, class_context=False)
raise exceptions.AttributeInferenceError(
- target=self,
- attribute=name,
- context=context,
+ target=self, attribute=name, context=context
) from exc
# since we've no context information, return matching class members as
# well
if lookupclass:
try:
- return values + self._proxied.getattr(name, context,
- class_context=False)
+ return values + self._proxied.getattr(
+ name, context, class_context=False
+ )
except exceptions.AttributeInferenceError:
pass
return values
@@ -202,13 +214,15 @@ class BaseInstance(Proxy):
# XXX frame should be self._proxied, or not ?
get_attr = self.getattr(name, context, lookupclass=False)
- yield from _infer_stmts(self._wrap_attr(get_attr, context), context, frame=self)
+ yield from _infer_stmts(
+ self._wrap_attr(get_attr, context), context, frame=self
+ )
except exceptions.AttributeInferenceError as error:
try:
# fallback to class.igetattr since it has some logic to handle
# descriptors
# But only if the _proxied is the Class.
- if self._proxied.__class__.__name__ != 'ClassDef':
+ if self._proxied.__class__.__name__ != "ClassDef":
raise exceptions.InferenceError(**vars(error)) from error
attrs = self._proxied.igetattr(name, context, class_context=False)
yield from self._wrap_attr(attrs, context)
@@ -223,14 +237,14 @@ class BaseInstance(Proxy):
yield from attr.infer_call_result(self, context)
else:
yield BoundMethod(attr, self)
- elif hasattr(attr, 'name') and attr.name == '<lambda>':
+ elif hasattr(attr, "name") and attr.name == "<lambda>":
# This is a lambda function defined at class level,
# since its scope is the underlying _proxied class.
# Unfortunately, we can't do an isinstance check here,
# because of the circular dependency between astroid.bases
# and astroid.scoped_nodes.
if attr.statement().scope() == self._proxied:
- if attr.args.args and attr.args.args[0].name == 'self':
+ if attr.args.args and attr.args.args[0].name == "self":
yield BoundMethod(attr, self)
continue
yield attr
@@ -241,15 +255,14 @@ class BaseInstance(Proxy):
"""infer what a class instance is returning when called"""
context = contextmod.bind_context_to_node(context, self)
inferred = False
- for node in self._proxied.igetattr('__call__', context):
+ for node in self._proxied.igetattr("__call__", context):
if node is util.Uninferable or not node.callable():
continue
for res in node.infer_call_result(caller, context):
inferred = True
yield res
if not inferred:
- raise exceptions.InferenceError(node=self, caller=caller,
- context=context)
+ raise exceptions.InferenceError(node=self, caller=caller, context=context)
class Instance(BaseInstance):
@@ -259,16 +272,18 @@ class Instance(BaseInstance):
special_attributes = util.lazy_descriptor(lambda: objectmodel.InstanceModel())
def __repr__(self):
- return '<Instance of %s.%s at 0x%s>' % (self._proxied.root().name,
- self._proxied.name,
- id(self))
+ return "<Instance of %s.%s at 0x%s>" % (
+ self._proxied.root().name,
+ self._proxied.name,
+ id(self),
+ )
+
def __str__(self):
- return 'Instance of %s.%s' % (self._proxied.root().name,
- self._proxied.name)
+ return "Instance of %s.%s" % (self._proxied.root().name, self._proxied.name)
def callable(self):
try:
- self._proxied.getattr('__call__', class_context=False)
+ self._proxied.getattr("__call__", class_context=False)
return True
except exceptions.AttributeInferenceError:
return False
@@ -277,7 +292,7 @@ class Instance(BaseInstance):
return self._proxied.qname()
def display_type(self):
- return 'Instance of'
+ return "Instance of"
def bool_value(self):
"""Infer the truth value for an Instance
@@ -301,7 +316,7 @@ class Instance(BaseInstance):
except (exceptions.InferenceError, exceptions.AttributeInferenceError):
# Fallback to __len__.
try:
- result = _infer_method_result_truth(self, '__len__', context)
+ result = _infer_method_result_truth(self, "__len__", context)
except (exceptions.AttributeInferenceError, exceptions.InferenceError):
return True
return result
@@ -319,9 +334,12 @@ class UnboundMethod(Proxy):
def __repr__(self):
frame = self._proxied.parent.frame()
- return '<%s %s of %s at 0x%s' % (self.__class__.__name__,
- self._proxied.name,
- frame.qname(), id(self))
+ return "<%s %s of %s at 0x%s" % (
+ self.__class__.__name__,
+ self._proxied.name,
+ frame.qname(),
+ id(self),
+ )
def implicit_parameters(self):
return 0
@@ -336,7 +354,7 @@ class UnboundMethod(Proxy):
def igetattr(self, name, context=None):
if name in self.special_attributes:
- return iter((self.special_attributes.lookup(name), ))
+ return iter((self.special_attributes.lookup(name),))
return self._proxied.igetattr(name, context)
def infer_call_result(self, caller, context):
@@ -352,8 +370,10 @@ class UnboundMethod(Proxy):
# If we're unbound method __new__ of builtin object, the result is an
# instance of the class given as first argument.
- if (self._proxied.name == '__new__' and
- self._proxied.parent.frame().qname() == '%s.object' % BUILTINS):
+ if (
+ self._proxied.name == "__new__"
+ and self._proxied.parent.frame().qname() == "%s.object" % BUILTINS
+ ):
if caller.args:
node_context = context.extra_context.get(caller.args[0])
infer = caller.args[0].infer(context=node_context)
@@ -390,9 +410,10 @@ class BoundMethod(UnboundMethod):
needs to be a tuple of classes
"""
from astroid import node_classes
+
# Verify the metaclass
mcs = next(caller.args[0].infer(context=context))
- if mcs.__class__.__name__ != 'ClassDef':
+ if mcs.__class__.__name__ != "ClassDef":
# Not a valid first argument.
return None
if not mcs.is_subtype_of("%s.type" % BUILTINS):
@@ -401,7 +422,7 @@ class BoundMethod(UnboundMethod):
# Verify the name
name = next(caller.args[1].infer(context=context))
- if name.__class__.__name__ != 'Const':
+ if name.__class__.__name__ != "Const":
# Not a valid name, needs to be a const.
return None
if not isinstance(name.value, str):
@@ -410,19 +431,17 @@ class BoundMethod(UnboundMethod):
# Verify the bases
bases = next(caller.args[2].infer(context=context))
- if bases.__class__.__name__ != 'Tuple':
+ if bases.__class__.__name__ != "Tuple":
# Needs to be a tuple.
return None
- inferred_bases = [next(elt.infer(context=context))
- for elt in bases.elts]
- if any(base.__class__.__name__ != 'ClassDef'
- for base in inferred_bases):
+ inferred_bases = [next(elt.infer(context=context)) for elt in bases.elts]
+ if any(base.__class__.__name__ != "ClassDef" for base in inferred_bases):
# All the bases needs to be Classes
return None
# Verify the attributes.
attrs = next(caller.args[3].infer(context=context))
- if attrs.__class__.__name__ != 'Dict':
+ if attrs.__class__.__name__ != "Dict":
# Needs to be a dictionary.
return None
cls_locals = collections.defaultdict(list)
@@ -430,30 +449,40 @@ class BoundMethod(UnboundMethod):
key = next(key.infer(context=context))
value = next(value.infer(context=context))
# Ignore non string keys
- if (key.__class__.__name__ == 'Const' and
- isinstance(key.value, str)):
+ if key.__class__.__name__ == "Const" and isinstance(key.value, str):
cls_locals[key.value].append(value)
# Build the class from now.
- cls = mcs.__class__(name=name.value, lineno=caller.lineno,
- col_offset=caller.col_offset,
- parent=caller)
+ cls = mcs.__class__(
+ name=name.value,
+ lineno=caller.lineno,
+ col_offset=caller.col_offset,
+ parent=caller,
+ )
empty = node_classes.Pass()
- cls.postinit(bases=bases.elts, body=[empty], decorators=[],
- newstyle=True, metaclass=mcs, keywords=[])
+ cls.postinit(
+ bases=bases.elts,
+ body=[empty],
+ decorators=[],
+ newstyle=True,
+ metaclass=mcs,
+ keywords=[],
+ )
cls.locals = cls_locals
return cls
def infer_call_result(self, caller, context=None):
context = contextmod.bind_context_to_node(context, self.bound)
- if (self.bound.__class__.__name__ == 'ClassDef'
- and self.bound.name == 'type'
- and self.name == '__new__'
- and len(caller.args) == 4):
+ if (
+ self.bound.__class__.__name__ == "ClassDef"
+ and self.bound.name == "type"
+ and self.name == "__new__"
+ and len(caller.args) == 4
+ ):
# Check if we have a ``type.__new__(mcs, name, bases, attrs)`` call.
new_cls = self._infer_type_new_call(caller, context)
if new_cls:
- return iter((new_cls, ))
+ return iter((new_cls,))
return super(BoundMethod, self).infer_call_result(caller, context)
@@ -478,32 +507,40 @@ class Generator(BaseInstance):
return False
def pytype(self):
- return '%s.generator' % BUILTINS
+ return "%s.generator" % BUILTINS
def display_type(self):
- return 'Generator'
+ return "Generator"
def bool_value(self):
return True
def __repr__(self):
- return '<Generator(%s) l.%s at 0x%s>' % (self._proxied.name, self.lineno, id(self))
+ return "<Generator(%s) l.%s at 0x%s>" % (
+ self._proxied.name,
+ self.lineno,
+ id(self),
+ )
def __str__(self):
- return 'Generator(%s)' % (self._proxied.name)
+ return "Generator(%s)" % (self._proxied.name)
class AsyncGenerator(Generator):
"""Special node representing an async generator"""
def pytype(self):
- return '%s.async_generator' % BUILTINS
+ return "%s.async_generator" % BUILTINS
def display_type(self):
- return 'AsyncGenerator'
+ return "AsyncGenerator"
def __repr__(self):
- return '<AsyncGenerator(%s) l.%s at 0x%s>' % (self._proxied.name, self.lineno, id(self))
+ return "<AsyncGenerator(%s) l.%s at 0x%s>" % (
+ self._proxied.name,
+ self.lineno,
+ id(self),
+ )
def __str__(self):
- return 'AsyncGenerator(%s)' % (self._proxied.name)
+ return "AsyncGenerator(%s)" % (self._proxied.name)
diff --git a/astroid/brain/brain_argparse.py b/astroid/brain/brain_argparse.py
index 1b120b4e..d4899117 100644
--- a/astroid/brain/brain_argparse.py
+++ b/astroid/brain/brain_argparse.py
@@ -1,10 +1,4 @@
-from astroid import (
- MANAGER,
- arguments,
- nodes,
- inference_tip,
- UseInferenceDefault,
-)
+from astroid import MANAGER, arguments, nodes, inference_tip, UseInferenceDefault
def infer_namespace(node, context=None):
@@ -13,28 +7,27 @@ def infer_namespace(node, context=None):
# Cannot make sense of it.
raise UseInferenceDefault()
- class_node = nodes.ClassDef('Namespace', 'docstring')
+ class_node = nodes.ClassDef("Namespace", "docstring")
class_node.parent = node.parent
for attr in set(callsite.keyword_arguments):
fake_node = nodes.EmptyNode()
fake_node.parent = class_node
fake_node.attrname = attr
class_node.instance_attrs[attr] = [fake_node]
- return iter((class_node.instantiate_class(), ))
+ return iter((class_node.instantiate_class(),))
def _looks_like_namespace(node):
func = node.func
if isinstance(func, nodes.Attribute):
return (
- func.attrname == 'Namespace'
+ func.attrname == "Namespace"
and isinstance(func.expr, nodes.Name)
- and func.expr.name == 'argparse'
+ and func.expr.name == "argparse"
)
return False
MANAGER.register_transform(
- nodes.Call, inference_tip(infer_namespace),
- _looks_like_namespace,
+ nodes.Call, inference_tip(infer_namespace), _looks_like_namespace
)
diff --git a/astroid/brain/brain_attrs.py b/astroid/brain/brain_attrs.py
index 06dc912f..74d1aa34 100644
--- a/astroid/brain/brain_attrs.py
+++ b/astroid/brain/brain_attrs.py
@@ -11,11 +11,12 @@ import astroid
from astroid import MANAGER
-ATTR_IB = 'attr.ib'
+ATTR_IB = "attr.ib"
def is_decorated_with_attrs(
- node, decorator_names=('attr.s', 'attr.attrs', 'attr.attributes')):
+ node, decorator_names=("attr.s", "attr.attrs", "attr.attributes")
+):
"""Return True if a decorated node has
an attr decorator applied."""
if not node.decorators:
@@ -49,12 +50,11 @@ def attr_attributes_transform(node):
rhs_node = astroid.Unknown(
lineno=cdefbodynode.lineno,
col_offset=cdefbodynode.col_offset,
- parent=cdefbodynode
+ parent=cdefbodynode,
)
node.locals[target.name] = [rhs_node]
MANAGER.register_transform(
- astroid.ClassDef,
- attr_attributes_transform,
- is_decorated_with_attrs)
+ astroid.ClassDef, attr_attributes_transform, is_decorated_with_attrs
+)
diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py
index e6def5c7..44a2efb3 100644
--- a/astroid/brain/brain_builtin_inference.py
+++ b/astroid/brain/brain_builtin_inference.py
@@ -34,12 +34,13 @@ from astroid import scoped_nodes
from astroid import util
-OBJECT_DUNDER_NEW = 'object.__new__'
+OBJECT_DUNDER_NEW = "object.__new__"
def _extend_str(class_node, rvalue):
"""function to extend builtin str/unicode class"""
- code = dedent('''
+ code = dedent(
+ """
class whatever(object):
def join(self, iterable):
return {rvalue}
@@ -79,41 +80,53 @@ def _extend_str(class_node, rvalue):
return {rvalue}
def ljust(self, width, fillchar=None):
return {rvalue}
- ''')
+ """
+ )
code = code.format(rvalue=rvalue)
- fake = AstroidBuilder(MANAGER).string_build(code)['whatever']
+ fake = AstroidBuilder(MANAGER).string_build(code)["whatever"]
for method in fake.mymethods():
method.parent = class_node
method.lineno = None
method.col_offset = None
- if '__class__' in method.locals:
- method.locals['__class__'] = [class_node]
+ if "__class__" in method.locals:
+ method.locals["__class__"] = [class_node]
class_node.locals[method.name] = [method]
method.parent = class_node
def extend_builtins(class_transforms):
from astroid.bases import BUILTINS
+
builtin_ast = MANAGER.astroid_cache[BUILTINS]
for class_name, transform in class_transforms.items():
transform(builtin_ast[class_name])
if sys.version_info > (3, 0):
- extend_builtins({'bytes': partial(_extend_str, rvalue="b''"),
- 'str': partial(_extend_str, rvalue="''")})
+ extend_builtins(
+ {
+ "bytes": partial(_extend_str, rvalue="b''"),
+ "str": partial(_extend_str, rvalue="''"),
+ }
+ )
else:
- extend_builtins({'str': partial(_extend_str, rvalue="''"),
- 'unicode': partial(_extend_str, rvalue="u''")})
+ extend_builtins(
+ {
+ "str": partial(_extend_str, rvalue="''"),
+ "unicode": partial(_extend_str, rvalue="u''"),
+ }
+ )
def _builtin_filter_predicate(node, builtin_name):
if isinstance(node.func, nodes.Name) and node.func.name == builtin_name:
return True
if isinstance(node.func, nodes.Attribute):
- return (node.func.attrname == 'fromkeys'
- and isinstance(node.func.expr, nodes.Name)
- and node.func.expr.name == 'dict')
+ return (
+ node.func.attrname == "fromkeys"
+ and isinstance(node.func.expr, nodes.Name)
+ and node.func.expr.name == "dict"
+ )
return False
@@ -123,6 +136,7 @@ def register_builtin_transform(transform, builtin_name):
The transform function must accept two parameters, a node and
an optional context.
"""
+
def _transform_wrapper(node, context=None):
result = transform(node, context=context)
if result:
@@ -175,64 +189,72 @@ def _generic_transform(arg, klass, iterables, build_elts):
raise UseInferenceDefault()
elts = [elt.value for elt in arg.elts]
elif isinstance(arg, nodes.Dict):
- if not all(isinstance(elt[0], nodes.Const)
- for elt in arg.items):
+ if not all(isinstance(elt[0], nodes.Const) for elt in arg.items):
raise UseInferenceDefault()
elts = [item[0].value for item in arg.items]
- elif (isinstance(arg, nodes.Const) and
- isinstance(arg.value, (six.string_types, six.binary_type))):
+ elif isinstance(arg, nodes.Const) and isinstance(
+ arg.value, (six.string_types, six.binary_type)
+ ):
elts = arg.value
else:
return
return klass.from_constants(elts=build_elts(elts))
-def _infer_builtin(node, context,
- klass=None, iterables=None,
- build_elts=None):
+def _infer_builtin(node, context, klass=None, iterables=None, build_elts=None):
transform_func = partial(
- _generic_transform,
- klass=klass,
- iterables=iterables,
- build_elts=build_elts)
+ _generic_transform, klass=klass, iterables=iterables, build_elts=build_elts
+ )
return _generic_inference(node, context, klass, transform_func)
+
# pylint: disable=invalid-name
infer_tuple = partial(
_infer_builtin,
klass=nodes.Tuple,
- iterables=(nodes.List, nodes.Set, objects.FrozenSet,
- objects.DictItems, objects.DictKeys,
- objects.DictValues),
- build_elts=tuple)
+ iterables=(
+ nodes.List,
+ nodes.Set,
+ objects.FrozenSet,
+ objects.DictItems,
+ objects.DictKeys,
+ objects.DictValues,
+ ),
+ build_elts=tuple,
+)
infer_list = partial(
_infer_builtin,
klass=nodes.List,
- iterables=(nodes.Tuple, nodes.Set, objects.FrozenSet,
- objects.DictItems, objects.DictKeys,
- objects.DictValues),
- build_elts=list)
+ iterables=(
+ nodes.Tuple,
+ nodes.Set,
+ objects.FrozenSet,
+ objects.DictItems,
+ objects.DictKeys,
+ objects.DictValues,
+ ),
+ build_elts=list,
+)
infer_set = partial(
_infer_builtin,
klass=nodes.Set,
- iterables=(nodes.List, nodes.Tuple, objects.FrozenSet,
- objects.DictKeys),
- build_elts=set)
+ iterables=(nodes.List, nodes.Tuple, objects.FrozenSet, objects.DictKeys),
+ build_elts=set,
+)
infer_frozenset = partial(
_infer_builtin,
klass=objects.FrozenSet,
- iterables=(nodes.List, nodes.Tuple, nodes.Set, objects.FrozenSet,
- objects.DictKeys),
- build_elts=frozenset)
+ iterables=(nodes.List, nodes.Tuple, nodes.Set, objects.FrozenSet, objects.DictKeys),
+ build_elts=frozenset,
+)
def _get_elts(arg, context):
- is_iterable = lambda n: isinstance(n,
- (nodes.List, nodes.Tuple, nodes.Set))
+ is_iterable = lambda n: isinstance(n, (nodes.List, nodes.Tuple, nodes.Set))
try:
inferred = next(arg.infer(context))
except (InferenceError, NameInferenceError):
@@ -250,14 +272,14 @@ def _get_elts(arg, context):
raise UseInferenceDefault()
if len(elt.elts) != 2:
raise UseInferenceDefault()
- if not isinstance(elt.elts[0],
- (nodes.Tuple, nodes.Const, nodes.Name)):
+ if not isinstance(elt.elts[0], (nodes.Tuple, nodes.Const, nodes.Name)):
raise UseInferenceDefault()
items.append(tuple(elt.elts))
else:
raise UseInferenceDefault()
return items
+
def infer_dict(node, context=None):
"""Try to infer a dict call to a Dict node.
@@ -295,9 +317,9 @@ def infer_dict(node, context=None):
else:
raise UseInferenceDefault()
- value = nodes.Dict(col_offset=node.col_offset,
- lineno=node.lineno,
- parent=node.parent)
+ value = nodes.Dict(
+ col_offset=node.col_offset, lineno=node.lineno, parent=node.parent
+ )
value.postinit(items)
return value
@@ -323,7 +345,7 @@ def infer_super(node, context=None):
if not isinstance(scope, nodes.FunctionDef):
# Ignore non-method uses of super.
raise UseInferenceDefault
- if scope.type not in ('classmethod', 'method'):
+ if scope.type not in ("classmethod", "method"):
# Not interested in staticmethods.
raise UseInferenceDefault
@@ -332,7 +354,7 @@ def infer_super(node, context=None):
mro_pointer = cls
# In we are in a classmethod, the interpreter will fill
# automatically the class as the second argument, not an instance.
- if scope.type == 'classmethod':
+ if scope.type == "classmethod":
mro_type = cls
else:
mro_type = cls.instantiate_class()
@@ -350,10 +372,9 @@ def infer_super(node, context=None):
# No way we could understand this.
raise UseInferenceDefault
- super_obj = objects.Super(mro_pointer=mro_pointer,
- mro_type=mro_type,
- self_class=cls,
- scope=scope)
+ super_obj = objects.Super(
+ mro_pointer=mro_pointer, mro_type=mro_type, self_class=cls, scope=scope
+ )
super_obj.parent = node
return super_obj
@@ -375,8 +396,9 @@ def _infer_getattr_args(node, context):
# which is unknown.
return util.Uninferable, util.Uninferable
- is_string = (isinstance(attr, nodes.Const) and
- isinstance(attr.value, six.string_types))
+ is_string = isinstance(attr, nodes.Const) and isinstance(
+ attr.value, six.string_types
+ )
if not is_string:
raise UseInferenceDefault
@@ -391,7 +413,11 @@ def infer_getattr(node, context=None):
lookup will be done.
"""
obj, attr = _infer_getattr_args(node, context)
- if obj is util.Uninferable or attr is util.Uninferable or not hasattr(obj, 'igetattr'):
+ if (
+ obj is util.Uninferable
+ or attr is util.Uninferable
+ or not hasattr(obj, "igetattr")
+ ):
return util.Uninferable
try:
@@ -418,7 +444,11 @@ def infer_hasattr(node, context=None):
"""
try:
obj, attr = _infer_getattr_args(node, context)
- if obj is util.Uninferable or attr is util.Uninferable or not hasattr(obj, 'getattr'):
+ if (
+ obj is util.Uninferable
+ or attr is util.Uninferable
+ or not hasattr(obj, "getattr")
+ ):
return util.Uninferable
obj.getattr(attr, context=context)
except UseInferenceDefault:
@@ -502,9 +532,9 @@ def infer_slice(node, context=None):
# Make sure we have 3 arguments.
args.extend([None] * (3 - len(args)))
- slice_node = nodes.Slice(lineno=node.lineno,
- col_offset=node.col_offset,
- parent=node.parent)
+ slice_node = nodes.Slice(
+ lineno=node.lineno, col_offset=node.col_offset, parent=node.parent
+ )
slice_node.postinit(*args)
return slice_node
@@ -544,8 +574,10 @@ def infer_issubclass(callnode, context=None):
raise UseInferenceDefault("TypeError: issubclass() takes no keyword arguments")
if len(call.positional_arguments) != 2:
raise UseInferenceDefault(
- "Expected two arguments, got {count}"
- .format(count=len(call.positional_arguments)))
+ "Expected two arguments, got {count}".format(
+ count=len(call.positional_arguments)
+ )
+ )
# The left hand argument is the obj to be checked
obj_node, class_or_tuple_node = call.positional_arguments
@@ -560,7 +592,8 @@ def infer_issubclass(callnode, context=None):
# object is to be checked against.
try:
class_container = _class_or_tuple_to_container(
- class_or_tuple_node, context=context)
+ class_or_tuple_node, context=context
+ )
except InferenceError as exc:
raise UseInferenceDefault from exc
try:
@@ -588,20 +621,22 @@ def infer_isinstance(callnode, context=None):
raise UseInferenceDefault("TypeError: isinstance() takes no keyword arguments")
if len(call.positional_arguments) != 2:
raise UseInferenceDefault(
- "Expected two arguments, got {count}"
- .format(count=len(call.positional_arguments)))
+ "Expected two arguments, got {count}".format(
+ count=len(call.positional_arguments)
+ )
+ )
# The left hand argument is the obj to be checked
obj_node, class_or_tuple_node = call.positional_arguments
# The right hand argument is the class(es) that the given
# obj is to be check is an instance of
try:
class_container = _class_or_tuple_to_container(
- class_or_tuple_node, context=context)
+ class_or_tuple_node, context=context
+ )
except InferenceError:
raise UseInferenceDefault
try:
- isinstance_bool = helpers.object_isinstance(
- obj_node, class_container, context)
+ isinstance_bool = helpers.object_isinstance(obj_node, class_container, context)
except AstroidTypeError as exc:
raise UseInferenceDefault("TypeError: " + str(exc))
except MroError as exc:
@@ -620,12 +655,10 @@ def _class_or_tuple_to_container(node, context=None):
# for isinstance
if isinstance(node_infer, nodes.Tuple):
class_container = [
- next(node.infer(context=context))
- for node in node_infer.elts
+ next(node.infer(context=context)) for node in node_infer.elts
]
class_container = [
- klass_node for klass_node
- in class_container if klass_node is not None
+ klass_node for klass_node in class_container if klass_node is not None
]
else:
class_container = [node_infer]
@@ -641,9 +674,7 @@ def infer_len(node, context=None):
"""
call = arguments.CallSite.from_call(node)
if call.keyword_arguments:
- raise UseInferenceDefault(
- "TypeError: len() must take no keyword arguments"
- )
+ raise UseInferenceDefault("TypeError: len() must take no keyword arguments")
if len(call.positional_arguments) != 1:
raise UseInferenceDefault(
"TypeError: len() must take exactly one argument "
@@ -665,10 +696,9 @@ def infer_str(node, context=None):
"""
call = arguments.CallSite.from_call(node)
if call.keyword_arguments:
- raise UseInferenceDefault(
- "TypeError: str() must take no keyword arguments")
+ raise UseInferenceDefault("TypeError: str() must take no keyword arguments")
try:
- return nodes.Const('')
+ return nodes.Const("")
except (AstroidTypeError, InferenceError) as exc:
raise UseInferenceDefault(str(exc)) from exc
@@ -682,9 +712,7 @@ def infer_int(node, context=None):
"""
call = arguments.CallSite.from_call(node)
if call.keyword_arguments:
- raise UseInferenceDefault(
- "TypeError: int() must take no keyword arguments"
- )
+ raise UseInferenceDefault("TypeError: int() must take no keyword arguments")
if call.positional_arguments:
try:
@@ -695,7 +723,9 @@ def infer_int(node, context=None):
if first_value is util.Uninferable:
raise UseInferenceDefault
- if isinstance(first_value, nodes.Const) and isinstance(first_value.value, (int, str)):
+ if isinstance(first_value, nodes.Const) and isinstance(
+ first_value.value, (int, str)
+ ):
try:
actual_value = int(first_value.value)
except ValueError:
@@ -717,19 +747,19 @@ def infer_dict_fromkeys(node, context=None):
"""
def _build_dict_with_elements(elements):
- new_node = nodes.Dict(col_offset=node.col_offset,
- lineno=node.lineno,
- parent=node.parent)
+ new_node = nodes.Dict(
+ col_offset=node.col_offset, lineno=node.lineno, parent=node.parent
+ )
new_node.postinit(elements)
return new_node
call = arguments.CallSite.from_call(node)
if call.keyword_arguments:
+ raise UseInferenceDefault("TypeError: int() must take no keyword arguments")
+ if len(call.positional_arguments) not in {1, 2}:
raise UseInferenceDefault(
- "TypeError: int() must take no keyword arguments"
+ "TypeError: Needs between 1 and 2 positional arguments"
)
- if len(call.positional_arguments) not in {1, 2}:
- raise UseInferenceDefault("TypeError: Needs between 1 and 2 positional arguments")
default = nodes.Const(None)
values = call.positional_arguments[0]
@@ -741,9 +771,7 @@ def infer_dict_fromkeys(node, context=None):
return _build_dict_with_elements([])
# Limit to a couple of potential values, as this can become pretty complicated
- accepted_iterable_elements = (
- nodes.Const,
- )
+ accepted_iterable_elements = (nodes.Const,)
if isinstance(inferred_values, (nodes.List, nodes.Set, nodes.Tuple)):
elements = inferred_values.elts
for element in elements:
@@ -754,8 +782,9 @@ def infer_dict_fromkeys(node, context=None):
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(inferred_values.value, (str, bytes))):
+ elif isinstance(inferred_values, nodes.Const) and isinstance(
+ inferred_values.value, (str, bytes)
+ ):
elements = [
(nodes.Const(element), default) for element in inferred_values.value
]
@@ -775,29 +804,29 @@ def infer_dict_fromkeys(node, context=None):
# Builtins inference
-register_builtin_transform(infer_bool, 'bool')
-register_builtin_transform(infer_super, 'super')
-register_builtin_transform(infer_callable, 'callable')
-register_builtin_transform(infer_getattr, 'getattr')
-register_builtin_transform(infer_hasattr, 'hasattr')
-register_builtin_transform(infer_tuple, 'tuple')
-register_builtin_transform(infer_set, 'set')
-register_builtin_transform(infer_list, 'list')
-register_builtin_transform(infer_dict, 'dict')
-register_builtin_transform(infer_frozenset, 'frozenset')
-register_builtin_transform(infer_type, 'type')
-register_builtin_transform(infer_slice, 'slice')
-register_builtin_transform(infer_isinstance, 'isinstance')
-register_builtin_transform(infer_issubclass, 'issubclass')
-register_builtin_transform(infer_len, 'len')
-register_builtin_transform(infer_str, 'str')
-register_builtin_transform(infer_int, 'int')
-register_builtin_transform(infer_dict_fromkeys, 'dict.fromkeys')
+register_builtin_transform(infer_bool, "bool")
+register_builtin_transform(infer_super, "super")
+register_builtin_transform(infer_callable, "callable")
+register_builtin_transform(infer_getattr, "getattr")
+register_builtin_transform(infer_hasattr, "hasattr")
+register_builtin_transform(infer_tuple, "tuple")
+register_builtin_transform(infer_set, "set")
+register_builtin_transform(infer_list, "list")
+register_builtin_transform(infer_dict, "dict")
+register_builtin_transform(infer_frozenset, "frozenset")
+register_builtin_transform(infer_type, "type")
+register_builtin_transform(infer_slice, "slice")
+register_builtin_transform(infer_isinstance, "isinstance")
+register_builtin_transform(infer_issubclass, "issubclass")
+register_builtin_transform(infer_len, "len")
+register_builtin_transform(infer_str, "str")
+register_builtin_transform(infer_int, "int")
+register_builtin_transform(infer_dict_fromkeys, "dict.fromkeys")
# Infer object.__new__ calls
MANAGER.register_transform(
nodes.ClassDef,
inference_tip(_infer_object__new__decorator),
- _infer_object__new__decorator_check
+ _infer_object__new__decorator_check,
)
diff --git a/astroid/brain/brain_collections.py b/astroid/brain/brain_collections.py
index c255bf44..b9eb9b96 100644
--- a/astroid/brain/brain_collections.py
+++ b/astroid/brain/brain_collections.py
@@ -15,17 +15,21 @@ PY35 = sys.version_info >= (3, 5)
def _collections_transform():
- return astroid.parse('''
+ return astroid.parse(
+ """
class defaultdict(dict):
default_factory = None
def __missing__(self, key): pass
def __getitem__(self, key): return default_factory
- ''' + _deque_mock() + _ordered_dict_mock())
+ """
+ + _deque_mock()
+ + _ordered_dict_mock()
+ )
def _deque_mock():
- base_deque_class = '''
+ base_deque_class = """
class deque(object):
maxlen = 0
def __init__(self, iterable=None, maxlen=None):
@@ -50,9 +54,9 @@ def _deque_mock():
def __nonzero__(self): return bool(self.iterable)
def __contains__(self, o): return o in self.iterable
def __len__(self): return len(self.iterable)
- def __copy__(self): return deque(self.iterable)'''
+ def __copy__(self): return deque(self.iterable)"""
if PY35:
- base_deque_class += '''
+ base_deque_class += """
def copy(self): return deque(self.iterable)
def index(self, x, start=0, end=0): return 0
def insert(self, x, i): pass
@@ -60,19 +64,19 @@ def _deque_mock():
def __iadd__(self, other): pass
def __mul__(self, other): pass
def __imul__(self, other): pass
- def __rmul__(self, other): pass'''
+ def __rmul__(self, other): pass"""
return base_deque_class
def _ordered_dict_mock():
- base_ordered_dict_class = '''
+ base_ordered_dict_class = """
class OrderedDict(dict):
def __reversed__(self): return self[::-1]
- '''
+ """
if PY34:
- base_ordered_dict_class += '''
- def move_to_end(self, key, last=False): pass'''
+ base_ordered_dict_class += """
+ def move_to_end(self, key, last=False): pass"""
return base_ordered_dict_class
-astroid.register_module_extender(astroid.MANAGER, 'collections', _collections_transform)
+astroid.register_module_extender(astroid.MANAGER, "collections", _collections_transform)
diff --git a/astroid/brain/brain_curses.py b/astroid/brain/brain_curses.py
index f1954835..68e88b90 100644
--- a/astroid/brain/brain_curses.py
+++ b/astroid/brain/brain_curses.py
@@ -4,7 +4,8 @@ import astroid
def _curses_transform():
- return astroid.parse('''
+ return astroid.parse(
+ """
A_ALTCHARSET = 1
A_BLINK = 1
A_BOLD = 1
@@ -171,7 +172,8 @@ def _curses_transform():
COLOR_RED = 1
COLOR_WHITE = 1
COLOR_YELLOW = 1
- ''')
+ """
+ )
-astroid.register_module_extender(astroid.MANAGER, 'curses', _curses_transform)
+astroid.register_module_extender(astroid.MANAGER, "curses", _curses_transform)
diff --git a/astroid/brain/brain_dateutil.py b/astroid/brain/brain_dateutil.py
index 0c641ac6..a1c270fe 100644
--- a/astroid/brain/brain_dateutil.py
+++ b/astroid/brain/brain_dateutil.py
@@ -12,11 +12,17 @@ import textwrap
from astroid import MANAGER, register_module_extender
from astroid.builder import AstroidBuilder
+
def dateutil_transform():
- return AstroidBuilder(MANAGER).string_build(textwrap.dedent('''
+ return AstroidBuilder(MANAGER).string_build(
+ textwrap.dedent(
+ """
import datetime
def parse(timestr, parserinfo=None, **kwargs):
return datetime.datetime()
- '''))
+ """
+ )
+ )
+
-register_module_extender(MANAGER, 'dateutil.parser', dateutil_transform)
+register_module_extender(MANAGER, "dateutil.parser", dateutil_transform)
diff --git a/astroid/brain/brain_fstrings.py b/astroid/brain/brain_fstrings.py
index 5c2d17b8..7d8c7b68 100644
--- a/astroid/brain/brain_fstrings.py
+++ b/astroid/brain/brain_fstrings.py
@@ -12,28 +12,16 @@ def _clone_node_with_lineno(node, parent, lineno):
cls = node.__class__
other_fields = node._other_fields
_astroid_fields = node._astroid_fields
- init_params = {
- 'lineno': lineno,
- 'col_offset': node.col_offset,
- 'parent': parent
- }
- postinit_params = {
- param: getattr(node, param)
- for param in _astroid_fields
- }
+ init_params = {"lineno": lineno, "col_offset": node.col_offset, "parent": parent}
+ postinit_params = {param: getattr(node, param) for param in _astroid_fields}
if other_fields:
- init_params.update({
- param: getattr(node, param)
- for param in other_fields
- })
+ init_params.update({param: getattr(node, param) for param in other_fields})
new_node = cls(**init_params)
- if hasattr(node, 'postinit') and _astroid_fields:
+ if hasattr(node, "postinit") and _astroid_fields:
for param, child in postinit_params.items():
if child and not isinstance(child, collections.Sequence):
cloned_child = _clone_node_with_lineno(
- node=child,
- lineno=new_node.lineno,
- parent=new_node,
+ node=child, lineno=new_node.lineno, parent=new_node
)
postinit_params[param] = cloned_child
new_node.postinit(**postinit_params)
@@ -44,17 +32,12 @@ def _transform_formatted_value(node):
if node.value and node.value.lineno == 1:
if node.lineno != node.value.lineno:
new_node = astroid.FormattedValue(
- lineno=node.lineno,
- col_offset=node.col_offset,
- parent=node.parent
+ lineno=node.lineno, col_offset=node.col_offset, parent=node.parent
)
new_value = _clone_node_with_lineno(
- node=node.value,
- lineno=node.lineno,
- parent=new_node
+ node=node.value, lineno=node.lineno, parent=new_node
)
- new_node.postinit(value=new_value,
- format_spec=node.format_spec)
+ new_node.postinit(value=new_value, format_spec=node.format_spec)
return new_node
@@ -64,5 +47,5 @@ if sys.version_info[:2] >= (3, 6):
# has wrong line numbers, usually 1. This creates problems for pylint,
# which expects correct line numbers for things such as message control.
astroid.MANAGER.register_transform(
- astroid.FormattedValue,
- _transform_formatted_value)
+ astroid.FormattedValue, _transform_formatted_value
+ )
diff --git a/astroid/brain/brain_functools.py b/astroid/brain/brain_functools.py
index b70dd4dc..ff307dfe 100644
--- a/astroid/brain/brain_functools.py
+++ b/astroid/brain/brain_functools.py
@@ -13,7 +13,7 @@ from astroid.interpreter import objectmodel
from astroid import MANAGER
-LRU_CACHE = 'functools.lru_cache'
+LRU_CACHE = "functools.lru_cache"
class LruWrappedModel(objectmodel.FunctionModel):
@@ -29,10 +29,13 @@ class LruWrappedModel(objectmodel.FunctionModel):
@property
def pycache_info(self):
- cache_info = extract_node('''
+ cache_info = extract_node(
+ """
from functools import _CacheInfo
_CacheInfo(0, 0, 0, 0)
- ''')
+ """
+ )
+
class CacheInfoBoundMethod(BoundMethod):
def infer_call_result(self, caller, context=None):
yield helpers.safe_infer(cache_info)
@@ -41,7 +44,7 @@ class LruWrappedModel(objectmodel.FunctionModel):
@property
def pycache_clear(self):
- node = extract_node('''def cache_clear(self): pass''')
+ node = extract_node("""def cache_clear(self): pass""")
return BoundMethod(proxy=node, bound=self._instance.parent.scope())
@@ -60,10 +63,12 @@ def _functools_partial_inference(node, context=None):
call = arguments.CallSite.from_call(node)
number_of_positional = len(call.positional_arguments)
if number_of_positional < 1:
- raise astroid.UseInferenceDefault('functools.partial takes at least one argument')
+ raise astroid.UseInferenceDefault(
+ "functools.partial takes at least one argument"
+ )
if number_of_positional == 1 and not call.keyword_arguments:
raise astroid.UseInferenceDefault(
- 'functools.partial needs at least to have some filled arguments'
+ "functools.partial needs at least to have some filled arguments"
)
partial_function = call.positional_arguments[0]
@@ -72,22 +77,25 @@ def _functools_partial_inference(node, context=None):
except astroid.InferenceError as exc:
raise astroid.UseInferenceDefault from exc
if inferred_wrapped_function is astroid.Uninferable:
- raise astroid.UseInferenceDefault('Cannot infer the wrapped function')
+ raise astroid.UseInferenceDefault("Cannot infer the wrapped function")
if not isinstance(inferred_wrapped_function, astroid.FunctionDef):
- raise astroid.UseInferenceDefault('The wrapped function is not a function')
+ raise astroid.UseInferenceDefault("The wrapped function is not a function")
# Determine if the passed keywords into the callsite are supported
# by the wrapped function.
function_parameters = chain(
inferred_wrapped_function.args.args or (),
- inferred_wrapped_function.args.kwonlyargs or ()
+ inferred_wrapped_function.args.kwonlyargs or (),
)
parameter_names = set(
- param.name for param in function_parameters
+ param.name
+ for param in function_parameters
if isinstance(param, astroid.AssignName)
)
if set(call.keyword_arguments) - parameter_names:
- raise astroid.UseInferenceDefault('wrapped function received unknown parameters')
+ raise astroid.UseInferenceDefault(
+ "wrapped function received unknown parameters"
+ )
# Return a wrapped() object that can be used further for inference
class PartialFunction(astroid.FunctionDef):
@@ -111,10 +119,7 @@ def _functools_partial_inference(node, context=None):
call_context_args = context.callcontext.args or []
context.callcontext.args = filled_args + call_context_args
- return super().infer_call_result(
- caller=caller,
- context=context,
- )
+ return super().infer_call_result(caller=caller, context=context)
partial_function = PartialFunction(
name=inferred_wrapped_function.name,
@@ -155,17 +160,17 @@ def _looks_like_lru_cache(node):
def _looks_like_functools_partial(node):
"""Check if the given Call node is a functools.partial call"""
if isinstance(node.func, astroid.Name):
- return node.func.name == 'partial'
+ return node.func.name == "partial"
elif isinstance(node.func, astroid.Attribute):
- return (node.func.attrname == 'partial'
- and isinstance(node.func.expr, astroid.Name)
- and node.func.expr.name == 'functools')
+ return (
+ node.func.attrname == "partial"
+ and isinstance(node.func.expr, astroid.Name)
+ and node.func.expr.name == "functools"
+ )
MANAGER.register_transform(
- astroid.FunctionDef,
- _transform_lru_cache,
- _looks_like_lru_cache,
+ astroid.FunctionDef, _transform_lru_cache, _looks_like_lru_cache
)
diff --git a/astroid/brain/brain_gi.py b/astroid/brain/brain_gi.py
index 82b923df..09706107 100644
--- a/astroid/brain/brain_gi.py
+++ b/astroid/brain/brain_gi.py
@@ -27,7 +27,8 @@ from astroid.builder import AstroidBuilder
_inspected_modules = {}
-_identifier_re = r'^[A-Za-z_]\w*$'
+_identifier_re = r"^[A-Za-z_]\w*$"
+
def _gi_build_stub(parent):
"""
@@ -53,16 +54,16 @@ def _gi_build_stub(parent):
if inspect.isclass(obj):
classes[name] = obj
- elif (inspect.isfunction(obj) or
- inspect.isbuiltin(obj)):
+ elif inspect.isfunction(obj) or inspect.isbuiltin(obj):
functions[name] = obj
- elif (inspect.ismethod(obj) or
- inspect.ismethoddescriptor(obj)):
+ elif inspect.ismethod(obj) or inspect.ismethoddescriptor(obj):
methods[name] = obj
- elif (str(obj).startswith("<flags") or
- str(obj).startswith("<enum ") or
- str(obj).startswith("<GType ") or
- inspect.isdatadescriptor(obj)):
+ elif (
+ str(obj).startswith("<flags")
+ or str(obj).startswith("<enum ")
+ or str(obj).startswith("<GType ")
+ or inspect.isdatadescriptor(obj)
+ ):
constants[name] = 0
elif isinstance(obj, (int, str)):
constants[name] = obj
@@ -126,9 +127,10 @@ def _gi_build_stub(parent):
return ret
+
def _import_gi_module(modname):
# we only consider gi.repository submodules
- if not modname.startswith('gi.repository.'):
+ if not modname.startswith("gi.repository."):
raise AstroidBuildingError(modname=modname)
# build astroid representation unless we already tried so
if modname not in _inspected_modules:
@@ -139,13 +141,13 @@ def _import_gi_module(modname):
# in pygobject that we need to cope with. However at
# least as of pygobject3-3.13.91 the _glib module doesn't
# exist anymore, so if treat these modules as optional.
- if modname == 'gi.repository.GLib':
- optional_modnames.append('gi._glib')
- elif modname == 'gi.repository.GObject':
- optional_modnames.append('gi._gobject')
+ if modname == "gi.repository.GLib":
+ optional_modnames.append("gi._glib")
+ elif modname == "gi.repository.GObject":
+ optional_modnames.append("gi._gobject")
try:
- modcode = ''
+ modcode = ""
for m in itertools.chain(modnames, optional_modnames):
try:
with warnings.catch_warnings():
@@ -153,6 +155,7 @@ def _import_gi_module(modname):
# warnings, so ignore them.
try:
from gi import PyGIDeprecationWarning, PyGIWarning
+
warnings.simplefilter("ignore", PyGIDeprecationWarning)
warnings.simplefilter("ignore", PyGIWarning)
except Exception:
@@ -174,6 +177,7 @@ def _import_gi_module(modname):
raise AstroidBuildingError(modname=modname)
return astng
+
def _looks_like_require_version(node):
# Return whether this looks like a call to gi.require_version(<name>, <version>)
# Only accept function calls with two constant arguments
@@ -185,27 +189,32 @@ def _looks_like_require_version(node):
func = node.func
if isinstance(func, nodes.Attribute):
- if func.attrname != 'require_version':
+ if func.attrname != "require_version":
return False
- if isinstance(func.expr, nodes.Name) and func.expr.name == 'gi':
+ if isinstance(func.expr, nodes.Name) and func.expr.name == "gi":
return True
return False
if isinstance(func, nodes.Name):
- return func.name == 'require_version'
+ return func.name == "require_version"
return False
+
def _register_require_version(node):
# Load the gi.require_version locally
try:
import gi
+
gi.require_version(node.args[0].value, node.args[1].value)
except Exception:
pass
return node
+
MANAGER.register_failed_import_hook(_import_gi_module)
-MANAGER.register_transform(nodes.Call, _register_require_version, _looks_like_require_version)
+MANAGER.register_transform(
+ nodes.Call, _register_require_version, _looks_like_require_version
+)
diff --git a/astroid/brain/brain_hashlib.py b/astroid/brain/brain_hashlib.py
index e2b8c535..8b83ebed 100644
--- a/astroid/brain/brain_hashlib.py
+++ b/astroid/brain/brain_hashlib.py
@@ -14,7 +14,7 @@ PY36 = sys.version_info >= (3, 6)
def _hashlib_transform():
signature = "value=''"
- template = '''
+ template = """
class %(name)s(object):
def __init__(self, %(signature)s): pass
def digest(self):
@@ -33,31 +33,30 @@ def _hashlib_transform():
@property
def digest_size(self):
return 1
- '''
+ """
algorithms_with_signature = dict.fromkeys(
- ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'],
- signature,
+ ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"], signature
)
if PY36:
blake_signature = "value='', digest_size=None"
new_algorithms = dict.fromkeys(
- ['sha3_224', 'sha3_256', 'sha3_384', 'sha3_512', 'shake_128', 'shake_256'],
- signature
+ ["sha3_224", "sha3_256", "sha3_384", "sha3_512", "shake_128", "shake_256"],
+ signature,
)
algorithms_with_signature.update(new_algorithms)
- algorithms_with_signature.update({
- 'blake2b': blake_signature,
- 'blake2s': blake_signature,
- })
+ algorithms_with_signature.update(
+ {"blake2b": blake_signature, "blake2s": blake_signature}
+ )
classes = "".join(
- template % {
- 'name': hashfunc,
- 'digest': 'b""' if six.PY3 else '""',
- 'signature': signature
+ template
+ % {
+ "name": hashfunc,
+ "digest": 'b""' if six.PY3 else '""',
+ "signature": signature,
}
for hashfunc, signature in algorithms_with_signature.items()
)
return astroid.parse(classes)
-astroid.register_module_extender(astroid.MANAGER, 'hashlib', _hashlib_transform)
+astroid.register_module_extender(astroid.MANAGER, "hashlib", _hashlib_transform)
diff --git a/astroid/brain/brain_io.py b/astroid/brain/brain_io.py
index be8d30c8..4c689225 100644
--- a/astroid/brain/brain_io.py
+++ b/astroid/brain/brain_io.py
@@ -3,21 +3,21 @@
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER
-'''Astroid brain hints for some of the _io C objects.'''
+"""Astroid brain hints for some of the _io C objects."""
import astroid
-BUFFERED = {'BufferedWriter', 'BufferedReader'}
-TextIOWrapper = 'TextIOWrapper'
-FileIO = 'FileIO'
-BufferedWriter = 'BufferedWriter'
+BUFFERED = {"BufferedWriter", "BufferedReader"}
+TextIOWrapper = "TextIOWrapper"
+FileIO = "FileIO"
+BufferedWriter = "BufferedWriter"
def _generic_io_transform(node, name, cls):
- '''Transform the given name, by adding the given *class* as a member of the node.'''
+ """Transform the given name, by adding the given *class* as a member of the node."""
- io_module = astroid.MANAGER.ast_from_module_name('_io')
+ io_module = astroid.MANAGER.ast_from_module_name("_io")
attribute_object = io_module[cls]
instance = attribute_object.instantiate_class()
node.locals[name] = [instance]
@@ -28,16 +28,18 @@ def _transform_text_io_wrapper(node):
# being stdout, stderr or stdin. But we cannot get access to the name of the
# stream, which is why we are using the BufferedWriter class as a default
# value
- return _generic_io_transform(node, name='buffer', cls=BufferedWriter)
+ return _generic_io_transform(node, name="buffer", cls=BufferedWriter)
def _transform_buffered(node):
- return _generic_io_transform(node, name='raw', cls=FileIO)
+ return _generic_io_transform(node, name="raw", cls=FileIO)
-astroid.MANAGER.register_transform(astroid.ClassDef,
- _transform_buffered,
- lambda node: node.name in BUFFERED)
-astroid.MANAGER.register_transform(astroid.ClassDef,
- _transform_text_io_wrapper,
- lambda node: node.name == TextIOWrapper)
+astroid.MANAGER.register_transform(
+ astroid.ClassDef, _transform_buffered, lambda node: node.name in BUFFERED
+)
+astroid.MANAGER.register_transform(
+ astroid.ClassDef,
+ _transform_text_io_wrapper,
+ lambda node: node.name == TextIOWrapper,
+)
diff --git a/astroid/brain/brain_mechanize.py b/astroid/brain/brain_mechanize.py
index 3b921807..93f282ec 100644
--- a/astroid/brain/brain_mechanize.py
+++ b/astroid/brain/brain_mechanize.py
@@ -9,8 +9,10 @@
from astroid import MANAGER, register_module_extender
from astroid.builder import AstroidBuilder
+
def mechanize_transform():
- return AstroidBuilder(MANAGER).string_build('''
+ return AstroidBuilder(MANAGER).string_build(
+ """
class Browser(object):
def open(self, url, data=None, timeout=None):
@@ -20,7 +22,8 @@ class Browser(object):
def open_local_file(self, filename):
return None
-''')
+"""
+ )
-register_module_extender(MANAGER, 'mechanize', mechanize_transform)
+register_module_extender(MANAGER, "mechanize", mechanize_transform)
diff --git a/astroid/brain/brain_multiprocessing.py b/astroid/brain/brain_multiprocessing.py
index a19bac69..be575e94 100644
--- a/astroid/brain/brain_multiprocessing.py
+++ b/astroid/brain/brain_multiprocessing.py
@@ -13,25 +13,29 @@ PY34 = sys.version_info >= (3, 4)
def _multiprocessing_transform():
- module = astroid.parse('''
+ module = astroid.parse(
+ """
from multiprocessing.managers import SyncManager
def Manager():
return SyncManager()
- ''')
+ """
+ )
if not PY34:
return module
# On Python 3.4, multiprocessing uses a getattr lookup inside contexts,
# in order to get the attributes they need. Since it's extremely
# dynamic, we use this approach to fake it.
- node = astroid.parse('''
+ node = astroid.parse(
+ """
from multiprocessing.context import DefaultContext, BaseContext
default = DefaultContext()
base = BaseContext()
- ''')
+ """
+ )
try:
- context = next(node['default'].infer())
- base = next(node['base'].infer())
+ context = next(node["default"].infer())
+ base = next(node["base"].infer())
except exceptions.InferenceError:
return module
@@ -50,7 +54,8 @@ def _multiprocessing_transform():
def _multiprocessing_managers_transform():
- return astroid.parse('''
+ return astroid.parse(
+ """
import array
import threading
import multiprocessing.pool as pool
@@ -90,15 +95,18 @@ def _multiprocessing_managers_transform():
Namespace = Namespace
__enter__ = lambda self: self
__exit__ = lambda *args: args
-
+
def start(self, initializer=None, initargs=None):
pass
def shutdown(self):
pass
- ''')
+ """
+ )
-astroid.register_module_extender(astroid.MANAGER, 'multiprocessing.managers',
- _multiprocessing_managers_transform)
-astroid.register_module_extender(astroid.MANAGER, 'multiprocessing',
- _multiprocessing_transform)
+astroid.register_module_extender(
+ astroid.MANAGER, "multiprocessing.managers", _multiprocessing_managers_transform
+)
+astroid.register_module_extender(
+ astroid.MANAGER, "multiprocessing", _multiprocessing_transform
+)
diff --git a/astroid/brain/brain_namedtuple_enum.py b/astroid/brain/brain_namedtuple_enum.py
index cc399246..85390a82 100644
--- a/astroid/brain/brain_namedtuple_enum.py
+++ b/astroid/brain/brain_namedtuple_enum.py
@@ -21,9 +21,7 @@ import functools
import keyword
from textwrap import dedent
-from astroid import (
- MANAGER, UseInferenceDefault, inference_tip,
- InferenceError)
+from astroid import MANAGER, UseInferenceDefault, inference_tip, InferenceError
from astroid import arguments
from astroid import exceptions
from astroid import nodes
@@ -31,11 +29,8 @@ from astroid.builder import AstroidBuilder, extract_node
from astroid import util
-TYPING_NAMEDTUPLE_BASENAMES = {
- 'NamedTuple',
- 'typing.NamedTuple'
-}
-ENUM_BASE_NAMES = {'Enum', 'IntEnum', 'enum.Enum', 'enum.IntEnum'}
+TYPING_NAMEDTUPLE_BASENAMES = {"NamedTuple", "typing.NamedTuple"}
+ENUM_BASE_NAMES = {"Enum", "IntEnum", "enum.Enum", "enum.IntEnum"}
def _infer_first(node, context):
@@ -52,7 +47,6 @@ def _infer_first(node, context):
def _find_func_form_arguments(node, context):
-
def _extract_namedtuple_arg_or_keyword(position, key_name=None):
if len(args) > position:
@@ -62,18 +56,12 @@ def _find_func_form_arguments(node, context):
args = node.args
keywords = node.keywords
- found_keywords = {
- keyword.arg: keyword.value for keyword in keywords
- } if keywords else {}
-
- name = _extract_namedtuple_arg_or_keyword(
- position=0,
- key_name='typename'
- )
- names = _extract_namedtuple_arg_or_keyword(
- position=1,
- key_name='field_names'
+ found_keywords = (
+ {keyword.arg: keyword.value for keyword in keywords} if keywords else {}
)
+
+ name = _extract_namedtuple_arg_or_keyword(position=0, key_name="typename")
+ names = _extract_namedtuple_arg_or_keyword(position=1, key_name="field_names")
if name and names:
return name.value, names
@@ -90,30 +78,35 @@ def infer_func_form(node, base_type, context=None, enum=False):
try:
name, names = _find_func_form_arguments(node, context)
try:
- attributes = names.value.replace(',', ' ').split()
+ attributes = names.value.replace(",", " ").split()
except AttributeError:
if not enum:
- attributes = [_infer_first(const, context).value
- for const in names.elts]
+ attributes = [
+ _infer_first(const, context).value for const in names.elts
+ ]
else:
# Enums supports either iterator of (name, value) pairs
# or mappings.
- if hasattr(names, 'items') and isinstance(names.items, list):
- attributes = [_infer_first(const[0], context).value
- for const in names.items
- if isinstance(const[0], nodes.Const)]
- elif hasattr(names, 'elts'):
+ if hasattr(names, "items") and isinstance(names.items, list):
+ attributes = [
+ _infer_first(const[0], context).value
+ for const in names.items
+ if isinstance(const[0], nodes.Const)
+ ]
+ elif hasattr(names, "elts"):
# Enums can support either ["a", "b", "c"]
# or [("a", 1), ("b", 2), ...], but they can't
# be mixed.
- if all(isinstance(const, nodes.Tuple)
- for const in names.elts):
- attributes = [_infer_first(const.elts[0], context).value
- for const in names.elts
- if isinstance(const, nodes.Tuple)]
+ if all(isinstance(const, nodes.Tuple) for const in names.elts):
+ attributes = [
+ _infer_first(const.elts[0], context).value
+ for const in names.elts
+ if isinstance(const, nodes.Tuple)
+ ]
else:
- attributes = [_infer_first(const, context).value
- for const in names.elts]
+ attributes = [
+ _infer_first(const, context).value for const in names.elts
+ ]
else:
raise AttributeError
if not attributes:
@@ -123,9 +116,9 @@ def infer_func_form(node, base_type, context=None, enum=False):
# If we can't infer the name of the class, don't crash, up to this point
# we know it is a namedtuple anyway.
- name = name or 'Uninferable'
+ name = name or "Uninferable"
# we want to return a Class node instance with proper attributes set
- class_node = nodes.ClassDef(name, 'docstring')
+ class_node = nodes.ClassDef(name, "docstring")
class_node.parent = node.parent
# set base class=tuple
class_node.bases.append(base_type)
@@ -156,39 +149,39 @@ def _looks_like(node, name):
return False
-_looks_like_namedtuple = functools.partial(_looks_like, name='namedtuple')
-_looks_like_enum = functools.partial(_looks_like, name='Enum')
-_looks_like_typing_namedtuple = functools.partial(_looks_like, name='NamedTuple')
+_looks_like_namedtuple = functools.partial(_looks_like, name="namedtuple")
+_looks_like_enum = functools.partial(_looks_like, name="Enum")
+_looks_like_typing_namedtuple = functools.partial(_looks_like, name="NamedTuple")
def infer_named_tuple(node, context=None):
"""Specific inference function for namedtuple Call node"""
- tuple_base_name = nodes.Name(name='tuple', parent=node.root())
+ tuple_base_name = nodes.Name(name="tuple", parent=node.root())
class_node, name, attributes = infer_func_form(
- node,
- tuple_base_name,
- context=context,
+ node, tuple_base_name, context=context
)
call_site = arguments.CallSite.from_call(node)
- func = next(extract_node('import collections; collections.namedtuple').infer())
+ func = next(extract_node("import collections; collections.namedtuple").infer())
try:
- rename = next(call_site.infer_argument(func, 'rename', context)).bool_value()
+ rename = next(call_site.infer_argument(func, "rename", context)).bool_value()
except InferenceError:
rename = False
if rename:
attributes = _get_renamed_namedtuple_attributes(attributes)
- replace_args = ', '.join(
- '{arg}=None'.format(arg=arg)
- for arg in attributes
- )
+ replace_args = ", ".join("{arg}=None".format(arg=arg) for arg in attributes)
- field_def = (" {name} = property(lambda self: self[{index:d}], "
- "doc='Alias for field number {index:d}')")
- field_defs = '\n'.join(field_def.format(name=name, index=index)
- for index, name in enumerate(attributes))
- fake = AstroidBuilder(MANAGER).string_build('''
+ field_def = (
+ " {name} = property(lambda self: self[{index:d}], "
+ "doc='Alias for field number {index:d}')"
+ )
+ field_defs = "\n".join(
+ field_def.format(name=name, index=index)
+ for index, name in enumerate(attributes)
+ )
+ fake = AstroidBuilder(MANAGER).string_build(
+ """
class %(name)s(tuple):
__slots__ = ()
_fields = %(fields)r
@@ -202,14 +195,18 @@ class %(name)s(tuple):
def __getnewargs__(self):
return tuple(self)
%(field_defs)s
- ''' % {'name': name,
- 'fields': attributes,
- 'field_defs': field_defs,
- 'replace_args': replace_args})
- class_node.locals['_asdict'] = fake.body[0].locals['_asdict']
- class_node.locals['_make'] = fake.body[0].locals['_make']
- class_node.locals['_replace'] = fake.body[0].locals['_replace']
- class_node.locals['_fields'] = fake.body[0].locals['_fields']
+ """
+ % {
+ "name": name,
+ "fields": attributes,
+ "field_defs": field_defs,
+ "replace_args": replace_args,
+ }
+ )
+ class_node.locals["_asdict"] = fake.body[0].locals["_asdict"]
+ class_node.locals["_make"] = fake.body[0].locals["_make"]
+ class_node.locals["_replace"] = fake.body[0].locals["_replace"]
+ class_node.locals["_fields"] = fake.body[0].locals["_fields"]
for attr in attributes:
class_node.locals[attr] = fake.body[0].locals[attr]
# we use UseInferenceDefault, we can't be a generator so return an iterator
@@ -220,16 +217,23 @@ def _get_renamed_namedtuple_attributes(field_names):
names = list(field_names)
seen = set()
for i, name in enumerate(field_names):
- if (not all(c.isalnum() or c == '_' for c in name) or keyword.iskeyword(name)
- or not name or name[0].isdigit() or name.startswith('_') or name in seen):
- names[i] = '_%d' % i
+ if (
+ not all(c.isalnum() or c == "_" for c in name)
+ or keyword.iskeyword(name)
+ or not name
+ or name[0].isdigit()
+ or name.startswith("_")
+ or name in seen
+ ):
+ names[i] = "_%d" % i
seen.add(name)
return tuple(names)
def infer_enum(node, context=None):
""" Specific inference function for enum Call node. """
- enum_meta = extract_node('''
+ enum_meta = extract_node(
+ """
class EnumMeta(object):
'docstring'
def __call__(self, node):
@@ -255,9 +259,9 @@ def infer_enum(node, context=None):
return Value()
__members__ = ['']
- ''')
- class_node = infer_func_form(node, enum_meta,
- context=context, enum=True)[0]
+ """
+ )
+ class_node = infer_func_form(node, enum_meta, context=context, enum=True)[0]
return iter([class_node.instantiate_class()])
@@ -268,12 +272,11 @@ def infer_enum_class(node):
# is a hack to support enums.
if basename not in ENUM_BASE_NAMES:
continue
- if node.root().name == 'enum':
+ if node.root().name == "enum":
# Skip if the class is directly from enum module.
break
for local, values in node.locals.items():
- if any(not isinstance(value, nodes.AssignName)
- for value in values):
+ if any(not isinstance(value, nodes.AssignName) for value in values):
continue
targets = []
@@ -296,7 +299,8 @@ def infer_enum_class(node):
new_targets = []
for target in targets:
# Replace all the assignments with our mocked class.
- classdef = dedent('''
+ classdef = dedent(
+ """
class {name}({types}):
@property
def value(self):
@@ -304,11 +308,12 @@ def infer_enum_class(node):
@property
def name(self):
return {name}
- '''.format(
- name=target.name,
- types=', '.join(node.basenames),
- return_value=inferred_return_value,
- ))
+ """.format(
+ name=target.name,
+ types=", ".join(node.basenames),
+ return_value=inferred_return_value,
+ )
+ )
fake = AstroidBuilder(MANAGER).string_build(classdef)[target.name]
fake.parent = target.parent
for method in node.mymethods():
@@ -323,21 +328,21 @@ def infer_typing_namedtuple_class(class_node, context=None):
"""Infer a subclass of typing.NamedTuple"""
# Check if it has the corresponding bases
annassigns_fields = [
- annassign.target.name for annassign in class_node.body
+ annassign.target.name
+ for annassign in class_node.body
if isinstance(annassign, nodes.AnnAssign)
]
- code = dedent('''
+ code = dedent(
+ """
from collections import namedtuple
namedtuple({typename!r}, {fields!r})
- ''').format(
- typename=class_node.name,
- fields=",".join(annassigns_fields)
- )
+ """
+ ).format(typename=class_node.name, fields=",".join(annassigns_fields))
node = extract_node(code)
generated_class_node = next(infer_named_tuple(node, context))
for method in class_node.mymethods():
generated_class_node.locals[method.name] = [method]
- return iter((generated_class_node, ))
+ return iter((generated_class_node,))
def infer_typing_namedtuple(node, context=None):
@@ -349,7 +354,7 @@ def infer_typing_namedtuple(node, context=None):
except InferenceError:
raise UseInferenceDefault
- if func.qname() != 'typing.NamedTuple':
+ if func.qname() != "typing.NamedTuple":
raise UseInferenceDefault
if len(node.args) != 2:
@@ -367,31 +372,27 @@ def infer_typing_namedtuple(node, context=None):
names.append(elt.elts[0].as_string())
typename = node.args[0].as_string()
- node = extract_node('namedtuple(%(typename)s, (%(fields)s,)) ' %
- {'typename': typename, 'fields': ",".join(names)})
+ node = extract_node(
+ "namedtuple(%(typename)s, (%(fields)s,)) "
+ % {"typename": typename, "fields": ",".join(names)}
+ )
return infer_named_tuple(node, context)
MANAGER.register_transform(
- nodes.Call, inference_tip(infer_named_tuple),
- _looks_like_namedtuple,
+ nodes.Call, inference_tip(infer_named_tuple), _looks_like_namedtuple
)
+MANAGER.register_transform(nodes.Call, inference_tip(infer_enum), _looks_like_enum)
MANAGER.register_transform(
- nodes.Call, inference_tip(infer_enum),
- _looks_like_enum,
-)
-MANAGER.register_transform(
- nodes.ClassDef, infer_enum_class,
- predicate=lambda cls: any(basename for basename in cls.basenames
- if basename in ENUM_BASE_NAMES)
+ nodes.ClassDef,
+ infer_enum_class,
+ predicate=lambda cls: any(
+ basename for basename in cls.basenames if basename in ENUM_BASE_NAMES
+ ),
)
MANAGER.register_transform(
- nodes.ClassDef,
- inference_tip(infer_typing_namedtuple_class),
- _has_namedtuple_base,
+ nodes.ClassDef, inference_tip(infer_typing_namedtuple_class), _has_namedtuple_base
)
MANAGER.register_transform(
- nodes.Call,
- inference_tip(infer_typing_namedtuple),
- _looks_like_typing_namedtuple,
+ nodes.Call, inference_tip(infer_typing_namedtuple), _looks_like_typing_namedtuple
)
diff --git a/astroid/brain/brain_nose.py b/astroid/brain/brain_nose.py
index 6aec041b..7b12d760 100644
--- a/astroid/brain/brain_nose.py
+++ b/astroid/brain/brain_nose.py
@@ -16,30 +16,34 @@ import astroid.builder
_BUILDER = astroid.builder.AstroidBuilder(astroid.MANAGER)
-def _pep8(name, caps=re.compile('([A-Z])')):
- return caps.sub(lambda m: '_' + m.groups()[0].lower(), name)
+def _pep8(name, caps=re.compile("([A-Z])")):
+ return caps.sub(lambda m: "_" + m.groups()[0].lower(), name)
def _nose_tools_functions():
"""Get an iterator of names and bound methods."""
- module = _BUILDER.string_build(textwrap.dedent('''
+ module = _BUILDER.string_build(
+ textwrap.dedent(
+ """
import unittest
class Test(unittest.TestCase):
pass
a = Test()
- '''))
+ """
+ )
+ )
try:
- case = next(module['a'].infer())
+ case = next(module["a"].infer())
except astroid.InferenceError:
return
for method in case.methods():
- if method.name.startswith('assert') and '_' not in method.name:
+ if method.name.startswith("assert") and "_" not in method.name:
pep8_name = _pep8(method.name)
yield pep8_name, astroid.BoundMethod(method, case)
- if method.name == 'assertEqual':
+ if method.name == "assertEqual":
# nose also exports assert_equals.
- yield 'assert_equals', astroid.BoundMethod(method, case)
+ yield "assert_equals", astroid.BoundMethod(method, case)
def _nose_tools_transform(node):
@@ -49,8 +53,8 @@ def _nose_tools_transform(node):
def _nose_tools_trivial_transform():
"""Custom transform for the nose.tools module."""
- stub = _BUILDER.string_build('''__all__ = []''')
- all_entries = ['ok_', 'eq_']
+ stub = _BUILDER.string_build("""__all__ = []""")
+ all_entries = ["ok_", "eq_"]
for pep8_name, method in _nose_tools_functions():
all_entries.append(pep8_name)
@@ -58,14 +62,16 @@ def _nose_tools_trivial_transform():
# Update the __all__ variable, since nose.tools
# does this manually with .append.
- all_assign = stub['__all__'].parent
+ all_assign = stub["__all__"].parent
all_object = astroid.List(all_entries)
all_object.parent = all_assign
all_assign.value = all_object
return stub
-astroid.register_module_extender(astroid.MANAGER, 'nose.tools.trivial',
- _nose_tools_trivial_transform)
-astroid.MANAGER.register_transform(astroid.Module, _nose_tools_transform,
- lambda n: n.name == 'nose.tools')
+astroid.register_module_extender(
+ astroid.MANAGER, "nose.tools.trivial", _nose_tools_trivial_transform
+)
+astroid.MANAGER.register_transform(
+ astroid.Module, _nose_tools_transform, lambda n: n.name == "nose.tools"
+)
diff --git a/astroid/brain/brain_numpy.py b/astroid/brain/brain_numpy.py
index e32e3401..9d31a476 100644
--- a/astroid/brain/brain_numpy.py
+++ b/astroid/brain/brain_numpy.py
@@ -12,7 +12,8 @@ import astroid
def numpy_random_mtrand_transform():
- return astroid.parse('''
+ return astroid.parse(
+ """
def beta(a, b, size=None): pass
def binomial(n, p, size=None): pass
def bytes(length): pass
@@ -60,13 +61,17 @@ def numpy_random_mtrand_transform():
def wald(mean, scale, size=None): pass
def weibull(a, size=None): pass
def zipf(a, size=None): pass
- ''')
+ """
+ )
def numpy_core_umath_transform():
- ufunc_optional_keyword_arguments = ("""out=None, where=True, casting='same_kind', order='K', """
- """dtype=None, subok=True""")
- return astroid.parse('''
+ ufunc_optional_keyword_arguments = (
+ """out=None, where=True, casting='same_kind', order='K', """
+ """dtype=None, subok=True"""
+ )
+ return astroid.parse(
+ """
# Constants
e = 2.718281828459045
euler_gamma = 0.5772156649015329
@@ -114,7 +119,7 @@ def numpy_core_umath_transform():
def tan(x, {opt_args:s}): pass
def tanh(x, {opt_args:s}): pass
def trunc(x, {opt_args:s}): pass
-
+
# Two args functions with optional kwargs
def bitwise_and(x1, x2, {opt_args:s}): pass
def bitwise_or(x1, x2, {opt_args:s}): pass
@@ -146,11 +151,15 @@ def numpy_core_umath_transform():
def right_shift(x1, x2, {opt_args:s}): pass
def subtract(x1, x2, {opt_args:s}): pass
def true_divide(x1, x2, {opt_args:s}): pass
- '''.format(opt_args=ufunc_optional_keyword_arguments))
+ """.format(
+ opt_args=ufunc_optional_keyword_arguments
+ )
+ )
def numpy_core_numerictypes_transform():
- return astroid.parse('''
+ return astroid.parse(
+ """
# different types defined in numerictypes.py
class generic(object):
def __init__(self, value):
@@ -349,7 +358,7 @@ def numpy_core_numerictypes_transform():
class bool_(generic): pass
class number(generic): pass
class datetime64(generic): pass
-
+
class void(flexible):
def __init__(self, *args, **kwargs):
@@ -375,7 +384,7 @@ def numpy_core_numerictypes_transform():
class str_(str, character):
def maketrans(self, x, y=None, z=None): pass
-
+
class bytes_(bytes, character):
def fromhex(self, string): pass
def maketrans(self, frm, to): pass
@@ -394,9 +403,9 @@ def numpy_core_numerictypes_transform():
class float64(floating, float):
- def fromhex(self, string): pass
+ def fromhex(self, string): pass
+
-
class uint64(unsignedinteger): pass
class complex64(complexfloating): pass
class int16(signedinteger): pass
@@ -453,20 +462,27 @@ def numpy_core_numerictypes_transform():
unicode_ = str_
ushort = uint16
void0 = void
- ''')
+ """
+ )
def numpy_funcs():
- return astroid.parse('''
+ return astroid.parse(
+ """
import builtins
def sum(a, axis=None, dtype=None, out=None, keepdims=None):
return builtins.sum(a)
- ''')
-
-
-astroid.register_module_extender(astroid.MANAGER, 'numpy.core.umath', numpy_core_umath_transform)
-astroid.register_module_extender(astroid.MANAGER, 'numpy.random.mtrand',
- numpy_random_mtrand_transform)
-astroid.register_module_extender(astroid.MANAGER, 'numpy.core.numerictypes',
- numpy_core_numerictypes_transform)
-astroid.register_module_extender(astroid.MANAGER, 'numpy', numpy_funcs)
+ """
+ )
+
+
+astroid.register_module_extender(
+ astroid.MANAGER, "numpy.core.umath", numpy_core_umath_transform
+)
+astroid.register_module_extender(
+ astroid.MANAGER, "numpy.random.mtrand", numpy_random_mtrand_transform
+)
+astroid.register_module_extender(
+ astroid.MANAGER, "numpy.core.numerictypes", numpy_core_numerictypes_transform
+)
+astroid.register_module_extender(astroid.MANAGER, "numpy", numpy_funcs)
diff --git a/astroid/brain/brain_pkg_resources.py b/astroid/brain/brain_pkg_resources.py
index 7863105c..25e76495 100644
--- a/astroid/brain/brain_pkg_resources.py
+++ b/astroid/brain/brain_pkg_resources.py
@@ -13,7 +13,8 @@ from astroid import MANAGER
def pkg_resources_transform():
- return parse('''
+ return parse(
+ """
def require(*requirements):
return pkg_resources.working_set.require(*requirements)
@@ -67,6 +68,8 @@ def get_distribution(dist):
return Distribution(dist)
_namespace_packages = {}
-''')
+"""
+ )
-register_module_extender(MANAGER, 'pkg_resources', pkg_resources_transform)
+
+register_module_extender(MANAGER, "pkg_resources", pkg_resources_transform)
diff --git a/astroid/brain/brain_pytest.py b/astroid/brain/brain_pytest.py
index 01132f89..d7e3ac8a 100644
--- a/astroid/brain/brain_pytest.py
+++ b/astroid/brain/brain_pytest.py
@@ -14,7 +14,8 @@ from astroid.builder import AstroidBuilder
def pytest_transform():
- return AstroidBuilder(MANAGER).string_build('''
+ return AstroidBuilder(MANAGER).string_build(
+ """
try:
import _pytest.mark
@@ -79,7 +80,9 @@ except ImportError:
yield_fixture = _pytest.python.yield_fixture
except ImportError:
pass
-''')
+"""
+ )
-register_module_extender(MANAGER, 'pytest', pytest_transform)
-register_module_extender(MANAGER, 'py.test', pytest_transform)
+
+register_module_extender(MANAGER, "pytest", pytest_transform)
+register_module_extender(MANAGER, "py.test", pytest_transform)
diff --git a/astroid/brain/brain_qt.py b/astroid/brain/brain_qt.py
index d8fcc0b4..d65f2185 100644
--- a/astroid/brain/brain_qt.py
+++ b/astroid/brain/brain_qt.py
@@ -14,10 +14,10 @@ from astroid import nodes
from astroid import parse
-def _looks_like_signal(node, signal_name='pyqtSignal'):
- if '__class__' in node.instance_attrs:
+def _looks_like_signal(node, signal_name="pyqtSignal"):
+ if "__class__" in node.instance_attrs:
try:
- cls = node.instance_attrs['__class__'][0]
+ cls = node.instance_attrs["__class__"][0]
return cls.name == signal_name
except AttributeError:
# return False if the cls does not have a name attribute
@@ -26,7 +26,8 @@ def _looks_like_signal(node, signal_name='pyqtSignal'):
def transform_pyqt_signal(node):
- module = parse('''
+ module = parse(
+ """
class pyqtSignal(object):
def connect(self, slot, type=None, no_receiver_check=False):
pass
@@ -34,15 +35,17 @@ def transform_pyqt_signal(node):
pass
def emit(self, *args):
pass
- ''')
- signal_cls = module['pyqtSignal']
- node.instance_attrs['emit'] = signal_cls['emit']
- node.instance_attrs['disconnect'] = signal_cls['disconnect']
- node.instance_attrs['connect'] = signal_cls['connect']
+ """
+ )
+ signal_cls = module["pyqtSignal"]
+ node.instance_attrs["emit"] = signal_cls["emit"]
+ node.instance_attrs["disconnect"] = signal_cls["disconnect"]
+ node.instance_attrs["connect"] = signal_cls["connect"]
def transform_pyside_signal(node):
- module = parse('''
+ module = parse(
+ """
class NotPySideSignal(object):
def connect(self, receiver, type=None):
pass
@@ -50,25 +53,30 @@ def transform_pyside_signal(node):
pass
def emit(self, *args):
pass
- ''')
- signal_cls = module['NotPySideSignal']
- node.instance_attrs['connect'] = signal_cls['connect']
- node.instance_attrs['disconnect'] = signal_cls['disconnect']
- node.instance_attrs['emit'] = signal_cls['emit']
+ """
+ )
+ signal_cls = module["NotPySideSignal"]
+ node.instance_attrs["connect"] = signal_cls["connect"]
+ node.instance_attrs["disconnect"] = signal_cls["disconnect"]
+ node.instance_attrs["emit"] = signal_cls["emit"]
def pyqt4_qtcore_transform():
- return AstroidBuilder(MANAGER).string_build('''
+ return AstroidBuilder(MANAGER).string_build(
+ """
def SIGNAL(signal_name): pass
class QObject(object):
def emit(self, signal): pass
-''')
+"""
+ )
-register_module_extender(MANAGER, 'PyQt4.QtCore', pyqt4_qtcore_transform)
-MANAGER.register_transform(nodes.FunctionDef, transform_pyqt_signal,
- _looks_like_signal)
-MANAGER.register_transform(nodes.ClassDef, transform_pyside_signal,
- lambda node: node.qname() == 'PySide.QtCore.Signal')
+register_module_extender(MANAGER, "PyQt4.QtCore", pyqt4_qtcore_transform)
+MANAGER.register_transform(nodes.FunctionDef, transform_pyqt_signal, _looks_like_signal)
+MANAGER.register_transform(
+ nodes.ClassDef,
+ transform_pyside_signal,
+ lambda node: node.qname() == "PySide.QtCore.Signal",
+)
diff --git a/astroid/brain/brain_random.py b/astroid/brain/brain_random.py
index c76798d2..678f6001 100644
--- a/astroid/brain/brain_random.py
+++ b/astroid/brain/brain_random.py
@@ -7,33 +7,19 @@ from astroid import helpers
from astroid import MANAGER
-ACCEPTED_ITERABLES_FOR_SAMPLE = (
- astroid.List,
- astroid.Set,
- astroid.Tuple,
-)
+ACCEPTED_ITERABLES_FOR_SAMPLE = (astroid.List, astroid.Set, astroid.Tuple)
def _clone_node_with_lineno(node, parent, lineno):
cls = node.__class__
other_fields = node._other_fields
_astroid_fields = node._astroid_fields
- init_params = {
- 'lineno': lineno,
- 'col_offset': node.col_offset,
- 'parent': parent
- }
- postinit_params = {
- param: getattr(node, param)
- for param in _astroid_fields
- }
+ init_params = {"lineno": lineno, "col_offset": node.col_offset, "parent": parent}
+ postinit_params = {param: getattr(node, param) for param in _astroid_fields}
if other_fields:
- init_params.update({
- param: getattr(node, param)
- for param in other_fields
- })
+ init_params.update({param: getattr(node, param) for param in other_fields})
new_node = cls(**init_params)
- if hasattr(node, 'postinit') and _astroid_fields:
+ if hasattr(node, "postinit") and _astroid_fields:
new_node.postinit(**postinit_params)
return new_node
@@ -65,33 +51,25 @@ def infer_random_sample(node, context=None):
raise astroid.UseInferenceDefault
new_node = astroid.List(
- lineno=node.lineno,
- col_offset=node.col_offset,
- parent=node.scope(),
+ lineno=node.lineno, col_offset=node.col_offset, parent=node.scope()
)
new_elts = [
- _clone_node_with_lineno(
- elt,
- parent=new_node,
- lineno=new_node.lineno
- )
+ _clone_node_with_lineno(elt, parent=new_node, lineno=new_node.lineno)
for elt in elts
]
new_node.postinit(new_elts)
- return iter((new_node, ))
+ return iter((new_node,))
def _looks_like_random_sample(node):
func = node.func
if isinstance(func, astroid.Attribute):
- return func.attrname == 'sample'
+ return func.attrname == "sample"
if isinstance(func, astroid.Name):
- return func.name == 'sample'
+ return func.name == "sample"
return False
MANAGER.register_transform(
- astroid.Call,
- astroid.inference_tip(infer_random_sample),
- _looks_like_random_sample,
+ astroid.Call, astroid.inference_tip(infer_random_sample), _looks_like_random_sample
)
diff --git a/astroid/brain/brain_re.py b/astroid/brain/brain_re.py
index f6e1befd..c7ee51a5 100644
--- a/astroid/brain/brain_re.py
+++ b/astroid/brain/brain_re.py
@@ -10,7 +10,8 @@ if PY36:
# where every entry will be exposed via updating globals()
def _re_transform():
- return astroid.parse('''
+ return astroid.parse(
+ """
import sre_compile
ASCII = sre_compile.SRE_FLAG_ASCII
IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE
@@ -29,6 +30,7 @@ if PY36:
TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE
T = TEMPLATE
DEBUG = sre_compile.SRE_FLAG_DEBUG
- ''')
+ """
+ )
- astroid.register_module_extender(astroid.MANAGER, 're', _re_transform)
+ astroid.register_module_extender(astroid.MANAGER, "re", _re_transform)
diff --git a/astroid/brain/brain_six.py b/astroid/brain/brain_six.py
index 30ecca35..b342fbf5 100644
--- a/astroid/brain/brain_six.py
+++ b/astroid/brain/brain_six.py
@@ -12,11 +12,15 @@ from textwrap import dedent
from astroid import MANAGER, register_module_extender
from astroid.builder import AstroidBuilder
-from astroid.exceptions import AstroidBuildingError, InferenceError, AttributeInferenceError
+from astroid.exceptions import (
+ AstroidBuildingError,
+ InferenceError,
+ AttributeInferenceError,
+)
from astroid import nodes
-SIX_ADD_METACLASS = 'six.add_metaclass'
+SIX_ADD_METACLASS = "six.add_metaclass"
def _indent(text, prefix, predicate=None):
@@ -33,7 +37,8 @@ def _indent(text, prefix, predicate=None):
def prefixed_lines():
for line in text.splitlines(True):
yield prefix + line if predicate(line) else line
- return ''.join(prefixed_lines())
+
+ return "".join(prefixed_lines())
_IMPORTS = """
@@ -102,13 +107,15 @@ import urllib.error as urllib_error
def six_moves_transform():
- code = dedent('''
+ code = dedent(
+ """
class Moves(object):
{}
moves = Moves()
- ''').format(_indent(_IMPORTS, " "))
+ """
+ ).format(_indent(_IMPORTS, " "))
module = AstroidBuilder(MANAGER).string_build(code)
- module.name = 'six.moves'
+ module.name = "six.moves"
return module
@@ -126,12 +133,11 @@ def _six_fail_hook(modname):
:rtype: nodes.Module
"""
- attribute_of = (modname != "six.moves" and
- modname.startswith("six.moves"))
- if modname != 'six.moves' and not attribute_of:
+ attribute_of = modname != "six.moves" and modname.startswith("six.moves")
+ if modname != "six.moves" and not attribute_of:
raise AstroidBuildingError(modname=modname)
module = AstroidBuilder(MANAGER).string_build(_IMPORTS)
- module.name = 'six.moves'
+ module.name = "six.moves"
if attribute_of:
# Facilitate import of submodules in Moves
start_index = len(module.name)
@@ -182,9 +188,10 @@ def transform_six_add_metaclass(node):
return node
-register_module_extender(MANAGER, 'six', six_moves_transform)
-register_module_extender(MANAGER, 'requests.packages.urllib3.packages.six',
- six_moves_transform)
+register_module_extender(MANAGER, "six", six_moves_transform)
+register_module_extender(
+ MANAGER, "requests.packages.urllib3.packages.six", six_moves_transform
+)
MANAGER.register_failed_import_hook(_six_fail_hook)
MANAGER.register_transform(
nodes.ClassDef,
diff --git a/astroid/brain/brain_ssl.py b/astroid/brain/brain_ssl.py
index 132e827d..a42e04c7 100644
--- a/astroid/brain/brain_ssl.py
+++ b/astroid/brain/brain_ssl.py
@@ -13,7 +13,8 @@ from astroid import parse
def ssl_transform():
- return parse('''
+ return parse(
+ """
from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
from _ssl import _SSLContext, MemoryBIO
from _ssl import (
@@ -65,7 +66,8 @@ def ssl_transform():
from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN
from _ssl import _OPENSSL_API_VERSION
from _ssl import PROTOCOL_SSLv23, PROTOCOL_TLSv1, PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2
- ''')
+ """
+ )
-register_module_extender(MANAGER, 'ssl', ssl_transform)
+register_module_extender(MANAGER, "ssl", ssl_transform)
diff --git a/astroid/brain/brain_subprocess.py b/astroid/brain/brain_subprocess.py
index 8d654705..bba7ff3f 100644
--- a/astroid/brain/brain_subprocess.py
+++ b/astroid/brain/brain_subprocess.py
@@ -20,8 +20,8 @@ PY33 = sys.version_info >= (3, 3)
def _subprocess_transform():
if six.PY3:
- communicate = (bytes('string', 'ascii'), bytes('string', 'ascii'))
- communicate_signature = 'def communicate(self, input=None, timeout=None)'
+ communicate = (bytes("string", "ascii"), bytes("string", "ascii"))
+ communicate_signature = "def communicate(self, input=None, timeout=None)"
if PY36:
init = """
def __init__(self, args, bufsize=0, executable=None,
@@ -44,8 +44,8 @@ def _subprocess_transform():
pass
"""
else:
- communicate = ('string', 'string')
- communicate_signature = 'def communicate(self, input=None)'
+ communicate = ("string", "string")
+ communicate_signature = "def communicate(self, input=None)"
init = """
def __init__(self, args, bufsize=0, executable=None,
stdin=None, stdout=None, stderr=None,
@@ -55,20 +55,21 @@ def _subprocess_transform():
pass
"""
if PY34:
- wait_signature = 'def wait(self, timeout=None)'
+ wait_signature = "def wait(self, timeout=None)"
else:
- wait_signature = 'def wait(self)'
+ wait_signature = "def wait(self)"
if six.PY3:
- ctx_manager = '''
+ ctx_manager = """
def __enter__(self): return self
def __exit__(self, *args): pass
- '''
+ """
else:
- ctx_manager = ''
+ ctx_manager = ""
py3_args = ""
if PY33:
py3_args = "args = []"
- code = textwrap.dedent('''
+ code = textwrap.dedent(
+ """
class Popen(object):
returncode = pid = 0
stdin = stdout = stderr = file()
@@ -87,17 +88,20 @@ def _subprocess_transform():
def kill(self):
pass
%(ctx_manager)s
- ''' % {'communicate': communicate,
- 'communicate_signature': communicate_signature,
- 'wait_signature': wait_signature,
- 'ctx_manager': ctx_manager,
- 'py3_args': py3_args,
- })
+ """
+ % {
+ "communicate": communicate,
+ "communicate_signature": communicate_signature,
+ "wait_signature": wait_signature,
+ "ctx_manager": ctx_manager,
+ "py3_args": py3_args,
+ }
+ )
init_lines = textwrap.dedent(init).splitlines()
- indented_init = '\n'.join([' ' * 4 + line for line in init_lines])
+ indented_init = "\n".join([" " * 4 + line for line in init_lines])
code += indented_init
return astroid.parse(code)
-astroid.register_module_extender(astroid.MANAGER, 'subprocess', _subprocess_transform)
+astroid.register_module_extender(astroid.MANAGER, "subprocess", _subprocess_transform)
diff --git a/astroid/brain/brain_threading.py b/astroid/brain/brain_threading.py
index 2313fbe4..77f5bde2 100644
--- a/astroid/brain/brain_threading.py
+++ b/astroid/brain/brain_threading.py
@@ -8,7 +8,8 @@ import astroid
def _thread_transform():
- return astroid.parse('''
+ return astroid.parse(
+ """
class lock(object):
def acquire(self, blocking=True, timeout=-1):
pass
@@ -21,7 +22,8 @@ def _thread_transform():
def Lock():
return lock()
- ''')
+ """
+ )
-astroid.register_module_extender(astroid.MANAGER, 'threading', _thread_transform)
+astroid.register_module_extender(astroid.MANAGER, "threading", _thread_transform)
diff --git a/astroid/brain/brain_typing.py b/astroid/brain/brain_typing.py
index 5aa7bee5..cd9a2f40 100644
--- a/astroid/brain/brain_typing.py
+++ b/astroid/brain/brain_typing.py
@@ -17,12 +17,9 @@ from astroid import (
)
-TYPING_NAMEDTUPLE_BASENAMES = {
- 'NamedTuple',
- 'typing.NamedTuple'
-}
-TYPING_TYPEVARS = {'TypeVar', 'NewType'}
-TYPING_TYPEVARS_QUALIFIED = {'typing.TypeVar', 'typing.NewType'}
+TYPING_NAMEDTUPLE_BASENAMES = {"NamedTuple", "typing.NamedTuple"}
+TYPING_TYPEVARS = {"TypeVar", "NewType"}
+TYPING_TYPEVARS_QUALIFIED = {"typing.TypeVar", "typing.NewType"}
TYPING_TYPE_TEMPLATE = """
class Meta(type):
def __getitem__(self, item):
@@ -78,20 +75,18 @@ def infer_typing_attr(node, context=None):
except InferenceError as exc:
raise UseInferenceDefault from exc
- if not value.qname().startswith('typing.'):
+ if not value.qname().startswith("typing."):
raise UseInferenceDefault
- node = extract_node(TYPING_TYPE_TEMPLATE.format(value.qname().split('.')[-1]))
+ node = extract_node(TYPING_TYPE_TEMPLATE.format(value.qname().split(".")[-1]))
return node.infer(context=context)
MANAGER.register_transform(
nodes.Call,
inference_tip(infer_typing_typevar_or_newtype),
- looks_like_typing_typevar_or_newtype
+ looks_like_typing_typevar_or_newtype,
)
MANAGER.register_transform(
- nodes.Subscript,
- inference_tip(infer_typing_attr),
- _looks_like_typing_subscript,
+ nodes.Subscript, inference_tip(infer_typing_attr), _looks_like_typing_subscript
)
diff --git a/astroid/brain/brain_uuid.py b/astroid/brain/brain_uuid.py
index ea3b277a..8bda631d 100644
--- a/astroid/brain/brain_uuid.py
+++ b/astroid/brain/brain_uuid.py
@@ -12,11 +12,9 @@ from astroid import nodes
def _patch_uuid_class(node):
# The .int member is patched using __dict__
- node.locals['int'] = [nodes.Const(0, parent=node)]
+ node.locals["int"] = [nodes.Const(0, parent=node)]
MANAGER.register_transform(
- nodes.ClassDef,
- _patch_uuid_class,
- lambda node: node.qname() == 'uuid.UUID'
+ nodes.ClassDef, _patch_uuid_class, lambda node: node.qname() == "uuid.UUID"
)
diff --git a/astroid/builder.py b/astroid/builder.py
index 0715b186..ac71093d 100644
--- a/astroid/builder.py
+++ b/astroid/builder.py
@@ -35,19 +35,19 @@ from astroid import util
# The name of the transient function that is used to
# wrap expressions to be extracted when calling
# extract_node.
-_TRANSIENT_FUNCTION = '__'
+_TRANSIENT_FUNCTION = "__"
# The comment used to select a statement to be extracted
# when calling extract_node.
-_STATEMENT_SELECTOR = '#@'
+_STATEMENT_SELECTOR = "#@"
MANAGER = manager.AstroidManager()
def open_source_file(filename):
- with open(filename, 'rb') as byte_stream:
+ with open(filename, "rb") as byte_stream:
encoding = detect_encoding(byte_stream.readline)[0]
- stream = open(filename, 'r', newline=None, encoding=encoding)
+ stream = open(filename, "r", newline=None, encoding=encoding)
data = stream.read()
return stream, encoding, data
@@ -72,6 +72,7 @@ class AstroidBuilder(raw_building.InspectBuilder):
applied after the tree was built from source or from a live object,
by default being True.
"""
+
# pylint: disable=redefined-outer-name
def __init__(self, manager=None, apply_transforms=True):
super(AstroidBuilder, self).__init__()
@@ -81,11 +82,11 @@ class AstroidBuilder(raw_building.InspectBuilder):
def module_build(self, module, modname=None):
"""Build an astroid from a living module instance."""
node = None
- path = getattr(module, '__file__', None)
+ path = getattr(module, "__file__", None)
if path is not None:
path_, ext = os.path.splitext(modutils._path_from_filename(path))
- if ext in ('.py', '.pyc', '.pyo') and os.path.exists(path_ + '.py'):
- node = self.file_build(path_ + '.py', modname)
+ if ext in (".py", ".pyc", ".pyo") and os.path.exists(path_ + ".py"):
+ node = self.file_build(path_ + ".py", modname)
if node is None:
# this is a built-in module
# get a partial representation by introspection
@@ -105,33 +106,40 @@ class AstroidBuilder(raw_building.InspectBuilder):
stream, encoding, data = open_source_file(path)
except IOError as exc:
raise exceptions.AstroidBuildingError(
- 'Unable to load file {path}:\n{error}',
- modname=modname, path=path, error=exc) from exc
+ "Unable to load file {path}:\n{error}",
+ modname=modname,
+ path=path,
+ error=exc,
+ ) from exc
except (SyntaxError, LookupError) as exc:
raise exceptions.AstroidSyntaxError(
- 'Python 3 encoding specification error or unknown encoding:\n'
- '{error}', modname=modname, path=path, error=exc) from exc
+ "Python 3 encoding specification error or unknown encoding:\n"
+ "{error}",
+ modname=modname,
+ path=path,
+ error=exc,
+ ) from exc
except UnicodeError as exc: # wrong encoding
# detect_encoding returns utf-8 if no encoding specified
raise exceptions.AstroidBuildingError(
- 'Wrong or no encoding specified for {filename}.',
- filename=path) from exc
+ "Wrong or no encoding specified for {filename}.", filename=path
+ ) from exc
with stream:
# get module name if necessary
if modname is None:
try:
- modname = '.'.join(modutils.modpath_from_file(path))
+ modname = ".".join(modutils.modpath_from_file(path))
except ImportError:
modname = os.path.splitext(os.path.basename(path))[0]
# build astroid representation
module = self._data_build(data, modname, path)
return self._post_build(module, encoding)
- def string_build(self, data, modname='', path=None):
+ def string_build(self, data, modname="", path=None):
"""Build astroid from source code string."""
module = self._data_build(data, modname, path)
- module.file_bytes = data.encode('utf-8')
- return self._post_build(module, 'utf-8')
+ module.file_bytes = data.encode("utf-8")
+ return self._post_build(module, "utf-8")
def _post_build(self, module, encoding):
"""Handles encoding and delayed nodes after a module has been built"""
@@ -139,7 +147,7 @@ class AstroidBuilder(raw_building.InspectBuilder):
self._manager.cache_module(module)
# post tree building steps after we stored the module in the cache:
for from_node in module._import_from_nodes:
- if from_node.modname == '__future__':
+ if from_node.modname == "__future__":
for symbol, _ in from_node.names:
module.future_imports.add(symbol)
self.add_from_names_to_locals(from_node)
@@ -155,20 +163,27 @@ class AstroidBuilder(raw_building.InspectBuilder):
def _data_build(self, data, modname, path):
"""Build tree node from data and add some informations"""
try:
- node = _parse(data + '\n')
+ node = _parse(data + "\n")
except (TypeError, ValueError, SyntaxError) as exc:
raise exceptions.AstroidSyntaxError(
- 'Parsing Python code failed:\n{error}',
- source=data, modname=modname, path=path, error=exc) from exc
+ "Parsing Python code failed:\n{error}",
+ source=data,
+ modname=modname,
+ path=path,
+ error=exc,
+ ) from exc
if path is not None:
node_file = os.path.abspath(path)
else:
- node_file = '<?>'
- if modname.endswith('.__init__'):
+ node_file = "<?>"
+ if modname.endswith(".__init__"):
modname = modname[:-9]
package = True
else:
- package = path is not None and os.path.splitext(os.path.basename(path))[0] == '__init__'
+ package = (
+ path is not None
+ and os.path.splitext(os.path.basename(path))[0] == "__init__"
+ )
builder = rebuilder.TreeRebuilder(self._manager)
module = builder.visit_module(node, modname, node_file, package)
module._import_from_nodes = builder._import_from_nodes
@@ -181,11 +196,12 @@ class AstroidBuilder(raw_building.InspectBuilder):
Resort the locals if coming from a delayed node
"""
_key_func = lambda node: node.fromlineno
+
def sort_locals(my_list):
my_list.sort(key=_key_func)
for (name, asname) in node.names:
- if name == '*':
+ if name == "*":
try:
imported = node.do_import_module()
except exceptions.AstroidBuildingError:
@@ -228,8 +244,11 @@ class AstroidBuilder(raw_building.InspectBuilder):
if node in values:
continue
# get assign in __init__ first XXX useful ?
- if (frame.name == '__init__' and values and
- values[0].frame().name != '__init__'):
+ if (
+ frame.name == "__init__"
+ and values
+ and values[0].frame().name != "__init__"
+ ):
values.insert(0, node)
else:
values.append(node)
@@ -238,10 +257,10 @@ class AstroidBuilder(raw_building.InspectBuilder):
def build_namespace_package_module(name, path):
- return nodes.Module(name, doc='', path=path, package=True)
+ return nodes.Module(name, doc="", path=path, package=True)
-def parse(code, module_name='', path=None, apply_transforms=True):
+def parse(code, module_name="", path=None, apply_transforms=True):
"""Parses a source string in order to obtain an astroid AST from it
:param str code: The code for the module.
@@ -252,8 +271,7 @@ def parse(code, module_name='', path=None, apply_transforms=True):
don't want the default transforms to be applied.
"""
code = textwrap.dedent(code)
- builder = AstroidBuilder(manager=MANAGER,
- apply_transforms=apply_transforms)
+ builder = AstroidBuilder(manager=MANAGER, apply_transforms=apply_transforms)
return builder.string_build(code, modname=module_name, path=path)
@@ -270,9 +288,11 @@ def _extract_expressions(node):
:yields: The sequence of wrapped expressions on the modified tree
expression can be found.
"""
- if (isinstance(node, nodes.Call)
- and isinstance(node.func, nodes.Name)
- and node.func.name == _TRANSIENT_FUNCTION):
+ if (
+ isinstance(node, nodes.Call)
+ and isinstance(node.func, nodes.Name)
+ and node.func.name == _TRANSIENT_FUNCTION
+ ):
real_expr = node.args[0]
real_expr.parent = node.parent
# Search for node in all _astng_fields (the fields checked when
@@ -329,7 +349,7 @@ def _find_statement_by_line(node, line):
return None
-def extract_node(code, module_name=''):
+def extract_node(code, module_name=""):
"""Parses some Python code as a module and extracts a designated AST node.
Statements:
@@ -383,6 +403,7 @@ def extract_node(code, module_name=''):
:returns: The designated node from the parse tree, or a list of nodes.
:rtype: astroid.bases.NodeNG, or a list of nodes.
"""
+
def _extract(node):
if isinstance(node, nodes.Expr):
return node.value
@@ -396,7 +417,7 @@ def extract_node(code, module_name=''):
tree = parse(code, module_name=module_name)
if not tree.body:
- raise ValueError('Empty tree, cannot extract from it')
+ raise ValueError("Empty tree, cannot extract from it")
extracted = []
if requested_lines:
diff --git a/astroid/context.py b/astroid/context.py
index 3b50d99d..1d6dab5c 100644
--- a/astroid/context.py
+++ b/astroid/context.py
@@ -20,7 +20,14 @@ class InferenceContext:
Account for already visited nodes to infinite stop infinite recursion
"""
- __slots__ = ('path', 'lookupname', 'callcontext', 'boundnode', 'inferred', 'extra_context')
+ __slots__ = (
+ "path",
+ "lookupname",
+ "callcontext",
+ "boundnode",
+ "inferred",
+ "extra_context",
+ )
def __init__(self, path=None, inferred=None):
self.path = path or set()
@@ -117,16 +124,18 @@ class InferenceContext:
self.path = path
def __str__(self):
- state = ('%s=%s' % (field, pprint.pformat(getattr(self, field),
- width=80 - len(field)))
- for field in self.__slots__)
- return '%s(%s)' % (type(self).__name__, ',\n '.join(state))
+ state = (
+ "%s=%s"
+ % (field, pprint.pformat(getattr(self, field), width=80 - len(field)))
+ for field in self.__slots__
+ )
+ return "%s(%s)" % (type(self).__name__, ",\n ".join(state))
class CallContext:
"""Holds information for a call site."""
- __slots__ = ('args', 'keywords')
+ __slots__ = ("args", "keywords")
def __init__(self, args, keywords=None):
"""
diff --git a/astroid/decorators.py b/astroid/decorators.py
index ef5a7a8e..433c230e 100644
--- a/astroid/decorators.py
+++ b/astroid/decorators.py
@@ -24,7 +24,7 @@ from astroid import util
@wrapt.decorator
def cached(func, instance, args, kwargs):
"""Simple decorator to cache result of method calls without args."""
- cache = getattr(instance, '__cache', None)
+ cache = getattr(instance, "__cache", None)
if cache is None:
instance.__cache = cache = {}
try:
@@ -48,20 +48,22 @@ class cachedproperty:
.. _pyramid: http://pypi.python.org/pypi/pyramid
.. _mercurial: http://pypi.python.org/pypi/Mercurial
"""
- __slots__ = ('wrapped',)
+
+ __slots__ = ("wrapped",)
def __init__(self, wrapped):
try:
wrapped.__name__
except AttributeError as exc:
- raise TypeError('%s must have a __name__ attribute' % wrapped) from exc
+ raise TypeError("%s must have a __name__ attribute" % wrapped) from exc
self.wrapped = wrapped
@property
def __doc__(self):
- doc = getattr(self.wrapped, '__doc__', None)
- return ('<wrapped by the cachedproperty decorator>%s'
- % ('\n%s' % doc if doc else ''))
+ doc = getattr(self.wrapped, "__doc__", None)
+ return "<wrapped by the cachedproperty decorator>%s" % (
+ "\n%s" % doc if doc else ""
+ )
def __get__(self, inst, objtype=None):
if inst is None:
@@ -77,6 +79,7 @@ def path_wrapper(func):
Used to stop inference if the node has already been looked
at for a given `InferenceContext` to prevent infinite recursion
"""
+
@functools.wraps(func)
def wrapped(node, context=None, _func=func, **kwargs):
"""wrapper function handling context"""
@@ -91,7 +94,7 @@ def path_wrapper(func):
while True:
res = next(generator)
# unproxy only true instance, not const, tuple, dict...
- if res.__class__.__name__ == 'Instance':
+ if res.__class__.__name__ == "Instance":
ares = res._proxied
else:
ares = res
@@ -131,4 +134,5 @@ def raise_if_nothing_inferred(func, instance, args, kwargs):
raise exceptions.InferenceError(**error.args[0])
else:
raise exceptions.InferenceError(
- 'StopIteration raised without any error information.')
+ "StopIteration raised without any error information."
+ )
diff --git a/astroid/exceptions.py b/astroid/exceptions.py
index ad3705a7..7e9d655e 100644
--- a/astroid/exceptions.py
+++ b/astroid/exceptions.py
@@ -26,7 +26,8 @@ class AstroidError(Exception):
will be called with the field names and values supplied as keyword
arguments.
"""
- def __init__(self, message='', **kws):
+
+ def __init__(self, message="", **kws):
super(AstroidError, self).__init__(message)
self.message = message
for key, value in kws.items():
@@ -44,7 +45,7 @@ class AstroidBuildingError(AstroidError):
error: Exception raised during construction.
"""
- def __init__(self, message='Failed to import module {modname}.', **kws):
+ def __init__(self, message="Failed to import module {modname}.", **kws):
super(AstroidBuildingError, self).__init__(message, **kws)
@@ -59,11 +60,15 @@ class TooManyLevelsError(AstroidImportError):
level: The level which was attempted.
name: the name of the module on which the relative import was attempted.
"""
+
level = None
name = None
- def __init__(self, message='Relative import with too many levels '
- '({level}) for module {name!r}', **kws):
+ def __init__(
+ self,
+ message="Relative import with too many levels " "({level}) for module {name!r}",
+ **kws
+ ):
super(TooManyLevelsError, self).__init__(message, **kws)
@@ -79,10 +84,11 @@ class NoDefault(AstroidError):
func: Function node.
name: Name of argument without a default.
"""
+
func = None
name = None
- def __init__(self, message='{func!r} has no default for {name!r}.', **kws):
+ def __init__(self, message="{func!r} has no default for {name!r}.", **kws):
super(NoDefault, self).__init__(message, **kws)
@@ -94,6 +100,7 @@ class ResolveError(AstroidError):
Standard attributes:
context: InferenceContext object.
"""
+
context = None
@@ -105,12 +112,14 @@ class MroError(ResolveError):
cls: ClassDef node whose MRO resolution failed.
context: InferenceContext object.
"""
+
mros = ()
cls = None
def __str__(self):
- mro_names = ", ".join("({})".format(", ".join(b.name for b in m))
- for m in self.mros)
+ mro_names = ", ".join(
+ "({})".format(", ".join(b.name for b in m)) for m in self.mros
+ )
return self.message.format(mros=mro_names, cls=self.cls)
@@ -129,6 +138,7 @@ class SuperError(ResolveError):
*super_*: The Super instance that raised the exception.
context: InferenceContext object.
"""
+
super_ = None
def __str__(self):
@@ -142,10 +152,11 @@ class InferenceError(ResolveError):
node: The node inference was called on.
context: InferenceContext object.
"""
+
node = None
context = None
- def __init__(self, message='Inference failed for {node!r}.', **kws):
+ def __init__(self, message="Inference failed for {node!r}.", **kws):
super(InferenceError, self).__init__(message, **kws)
@@ -159,10 +170,11 @@ class NameInferenceError(InferenceError):
scope: The node representing the scope in which the lookup occurred.
context: InferenceContext object.
"""
+
name = None
scope = None
- def __init__(self, message='{name!r} not found in {scope!r}.', **kws):
+ def __init__(self, message="{name!r} not found in {scope!r}.", **kws):
super(NameInferenceError, self).__init__(message, **kws)
@@ -174,10 +186,11 @@ class AttributeInferenceError(ResolveError):
attribute: The attribute for which lookup failed, as a string.
context: InferenceContext object.
"""
+
target = None
attribute = None
- def __init__(self, message='{attribute!r} not found on {target!r}.', **kws):
+ def __init__(self, message="{attribute!r} not found on {target!r}.", **kws):
super(AttributeInferenceError, self).__init__(message, **kws)
diff --git a/astroid/helpers.py b/astroid/helpers.py
index d7a72338..e58d1919 100644
--- a/astroid/helpers.py
+++ b/astroid/helpers.py
@@ -34,13 +34,13 @@ def _build_proxy_class(cls_name, builtins):
def _function_type(function, builtins):
if isinstance(function, scoped_nodes.Lambda):
if function.root().name == BUILTINS:
- cls_name = 'builtin_function_or_method'
+ cls_name = "builtin_function_or_method"
else:
- cls_name = 'function'
+ cls_name = "function"
elif isinstance(function, bases.BoundMethod):
- cls_name = 'method'
+ cls_name = "method"
elif isinstance(function, bases.UnboundMethod):
- cls_name = 'function'
+ cls_name = "function"
return _build_proxy_class(cls_name, builtins)
@@ -56,11 +56,11 @@ def _object_type(node, context=None):
if metaclass:
yield metaclass
continue
- yield builtins.getattr('type')[0]
+ yield builtins.getattr("type")[0]
elif isinstance(inferred, (scoped_nodes.Lambda, bases.UnboundMethod)):
yield _function_type(inferred, builtins)
elif isinstance(inferred, scoped_nodes.Module):
- yield _build_proxy_class('module', builtins)
+ yield _build_proxy_class("module", builtins)
else:
yield inferred._proxied
@@ -94,8 +94,10 @@ def _object_type_is_subclass(obj_type, class_or_seq, context=None):
return util.Uninferable
# Instances are not types
- class_seq = [item if not isinstance(item, bases.Instance)
- else util.Uninferable for item in class_seq]
+ class_seq = [
+ item if not isinstance(item, bases.Instance) else util.Uninferable
+ for item in class_seq
+ ]
# strict compatibility with issubclass
# issubclass(type, (object, 1)) evaluates to true
# issubclass(object, (1, type)) raises TypeError
@@ -153,9 +155,9 @@ def safe_infer(node, context=None):
return None
try:
next(inferit)
- return None # None if there is ambiguity on the inferred node
+ return None # None if there is ambiguity on the inferred node
except exceptions.InferenceError:
- return None# there is some kind of ambiguity
+ return None # there is some kind of ambiguity
except StopIteration:
return value
@@ -169,9 +171,11 @@ def has_known_bases(klass, context=None):
for base in klass.bases:
result = safe_infer(base, context=context)
# TODO: check for A->B->A->B pattern in class structure too?
- if (not isinstance(result, scoped_nodes.ClassDef) or
- result is klass or
- not has_known_bases(result, context=context)):
+ if (
+ not isinstance(result, scoped_nodes.ClassDef)
+ or result is klass
+ or not has_known_bases(result, context=context)
+ ):
klass._all_bases_known = False
return False
klass._all_bases_known = True
@@ -212,13 +216,12 @@ def class_instance_as_index(node):
context.callcontext = contextmod.CallContext(args=[node])
try:
- for inferred in node.igetattr('__index__', context=context):
+ for inferred in node.igetattr("__index__", context=context):
if not isinstance(inferred, bases.BoundMethod):
continue
for result in inferred.infer_call_result(node, context=context):
- if (isinstance(result, nodes.Const)
- and isinstance(result.value, int)):
+ if isinstance(result, nodes.Const) and isinstance(result.value, int):
return result
except exceptions.InferenceError:
pass
@@ -238,11 +241,13 @@ def object_len(node, context=None):
:rtype int: Integer length of node
"""
from astroid.objects import FrozenSet
+
inferred_node = safe_infer(node, context=context)
if inferred_node is None or inferred_node is util.Uninferable:
raise exceptions.InferenceError(node=node)
- if (isinstance(inferred_node, nodes.Const) and
- isinstance(inferred_node.value, (bytes, str))):
+ if isinstance(inferred_node, nodes.Const) and isinstance(
+ inferred_node.value, (bytes, str)
+ ):
return len(inferred_node.value)
if isinstance(inferred_node, (nodes.List, nodes.Set, nodes.Tuple, FrozenSet)):
return len(inferred_node.elts)
@@ -253,12 +258,15 @@ def object_len(node, context=None):
len_call = next(node_type.igetattr("__len__", context=context))
except exceptions.AttributeInferenceError:
raise exceptions.AstroidTypeError(
- "object of type '{}' has no len()"
- .format(len_call.pytype()))
+ "object of type '{}' has no len()".format(len_call.pytype())
+ )
result_of_len = next(len_call.infer_call_result(node, context))
- if isinstance(result_of_len, nodes.Const) and result_of_len.pytype() == "builtins.int":
+ if (
+ isinstance(result_of_len, nodes.Const)
+ and result_of_len.pytype() == "builtins.int"
+ ):
return result_of_len.value
raise exceptions.AstroidTypeError(
- "'{}' object cannot be interpreted as an integer"
- .format(result_of_len))
+ "'{}' object cannot be interpreted as an integer".format(result_of_len)
+ )
diff --git a/astroid/inference.py b/astroid/inference.py
index b5403f5b..62c06e65 100644
--- a/astroid/inference.py
+++ b/astroid/inference.py
@@ -49,6 +49,8 @@ def infer_end(self, context=None):
"""
yield self
+
+
nodes.Module._infer = infer_end
nodes.ClassDef._infer = infer_end
nodes.FunctionDef._infer = infer_end
@@ -65,11 +67,9 @@ def _infer_sequence_helper(node, context=None):
if isinstance(elt, nodes.Starred):
starred = helpers.safe_infer(elt.value, context)
if starred in (None, util.Uninferable):
- raise exceptions.InferenceError(node=node,
- context=context)
- if not hasattr(starred, 'elts'):
- raise exceptions.InferenceError(node=node,
- context=context)
+ raise exceptions.InferenceError(node=node, context=context)
+ if not hasattr(starred, "elts"):
+ raise exceptions.InferenceError(node=node, context=context)
values.extend(_infer_sequence_helper(starred))
else:
values.append(elt)
@@ -83,7 +83,9 @@ def infer_sequence(self, context=None):
yield self
else:
values = _infer_sequence_helper(self, context)
- new_seq = type(self)(lineno=self.lineno, col_offset=self.col_offset, parent=self.parent)
+ new_seq = type(self)(
+ lineno=self.lineno, col_offset=self.col_offset, parent=self.parent
+ )
new_seq.postinit(values)
yield new_seq
@@ -136,16 +138,14 @@ def _infer_map(node, context):
if double_starred in (None, util.Uninferable):
raise exceptions.InferenceError
if not isinstance(double_starred, nodes.Dict):
- raise exceptions.InferenceError(node=node,
- context=context)
+ raise exceptions.InferenceError(node=node, context=context)
unpack_items = _infer_map(double_starred, context)
values = _update_with_replacement(values, unpack_items)
else:
key = helpers.safe_infer(name, context=context)
value = helpers.safe_infer(value, context=context)
if any(elem in (None, util.Uninferable) for elem in (key, value)):
- raise exceptions.InferenceError(node=node,
- context=context)
+ raise exceptions.InferenceError(node=node, context=context)
values = _update_with_replacement(values, {key: value})
return values
@@ -172,6 +172,7 @@ def _higher_function_scope(node):
return current.parent
return None
+
def infer_name(self, context=None):
"""infer a Name: use name lookup rules"""
frame, stmts = self.lookup(self.name)
@@ -183,18 +184,19 @@ def infer_name(self, context=None):
_, stmts = parent_function.lookup(self.name)
if not stmts:
- raise exceptions.NameInferenceError(name=self.name,
- scope=self.scope(),
- context=context)
+ raise exceptions.NameInferenceError(
+ name=self.name, scope=self.scope(), context=context
+ )
context = context.clone()
context.lookupname = self.name
return bases._infer_stmts(stmts, context, frame)
+
# pylint: disable=no-value-for-parameter
nodes.Name._infer = decorators.raise_if_nothing_inferred(
decorators.path_wrapper(infer_name)
)
-nodes.AssignName.infer_lhs = infer_name # won't work with a path wrapper
+nodes.AssignName.infer_lhs = infer_name # won't work with a path wrapper
@decorators.raise_if_nothing_inferred
@@ -202,8 +204,9 @@ nodes.AssignName.infer_lhs = infer_name # won't work with a path wrapper
def infer_call(self, context=None):
"""infer a Call node by trying to guess what the function returns"""
callcontext = context.clone()
- callcontext.callcontext = contextmod.CallContext(args=self.args,
- keywords=self.keywords)
+ callcontext.callcontext = contextmod.CallContext(
+ args=self.args, keywords=self.keywords
+ )
callcontext.boundnode = None
extra_context = {}
if context is not None:
@@ -214,14 +217,13 @@ def infer_call(self, context=None):
yield callee
continue
try:
- if hasattr(callee, 'infer_call_result'):
- yield from callee.infer_call_result(
- caller=self,
- context=callcontext,
- )
+ if hasattr(callee, "infer_call_result"):
+ yield from callee.infer_call_result(caller=self, context=callcontext)
except exceptions.InferenceError:
continue
return dict(node=self, context=context)
+
+
nodes.Call._infer = infer_call
@@ -239,10 +241,7 @@ def infer_import(self, context=None, asname=True):
else:
yield self.do_import_module(name)
except exceptions.AstroidBuildingError as exc:
- raise exceptions.InferenceError(
- node=self,
- context=context,
- ) from exc
+ raise exceptions.InferenceError(node=self, context=context) from exc
nodes.Import._infer = infer_import
@@ -252,6 +251,8 @@ def infer_name_module(self, name):
context = contextmod.InferenceContext()
context.lookupname = name
return self.infer(context, asname=False)
+
+
nodes.Import.infer_name_module = infer_name_module
@@ -268,10 +269,7 @@ def infer_import_from(self, context=None, asname=True):
try:
module = self.do_import_module()
except exceptions.AstroidBuildingError as exc:
- raise exceptions.InferenceError(
- node=self,
- context=context,
- ) from exc
+ raise exceptions.InferenceError(node=self, context=context) from exc
try:
context = contextmod.copy_context(context)
@@ -280,11 +278,10 @@ def infer_import_from(self, context=None, asname=True):
return bases._infer_stmts(stmts, context)
except exceptions.AttributeInferenceError as error:
raise exceptions.InferenceError(
- error.message,
- target=self,
- attribute=name,
- context=context,
+ error.message, target=self, attribute=name, context=context
) from error
+
+
nodes.ImportFrom._infer = infer_import_from
@@ -300,11 +297,14 @@ def infer_attribute(self, context=None):
# This handles the situation where the attribute is accessed through a subclass
# of a base class and the attribute is defined at the base class's level,
# by taking in consideration a redefinition in the subclass.
- if (isinstance(owner, bases.Instance)
- and isinstance(context.boundnode, bases.Instance)):
+ if isinstance(owner, bases.Instance) and isinstance(
+ context.boundnode, bases.Instance
+ ):
try:
- if helpers.is_subtype(helpers.object_type(context.boundnode),
- helpers.object_type(owner)):
+ if helpers.is_subtype(
+ helpers.object_type(context.boundnode),
+ helpers.object_type(owner),
+ ):
owner = context.boundnode
except exceptions._NonDeducibleTypeHierarchy:
# Can't determine anything useful.
@@ -320,8 +320,10 @@ def infer_attribute(self, context=None):
# XXX method / function
context.boundnode = None
return dict(node=self, context=context)
+
+
nodes.Attribute._infer = decorators.path_wrapper(infer_attribute)
-nodes.AssignAttr.infer_lhs = infer_attribute # # won't work with a path wrapper
+nodes.AssignAttr.infer_lhs = infer_attribute # # won't work with a path wrapper
@decorators.raise_if_nothing_inferred
@@ -330,15 +332,13 @@ def infer_global(self, context=None):
if context.lookupname is None:
raise exceptions.InferenceError(node=self, context=context)
try:
- return bases._infer_stmts(self.root().getattr(context.lookupname),
- context)
+ return bases._infer_stmts(self.root().getattr(context.lookupname), context)
except exceptions.AttributeInferenceError as error:
raise exceptions.InferenceError(
- error.message,
- target=self,
- attribute=context.lookupname,
- context=context,
+ error.message, target=self, attribute=context.lookupname, context=context
) from error
+
+
nodes.Global._infer = infer_global
@@ -387,10 +387,12 @@ def infer_subscript(self, context=None):
try:
assigned = value.getitem(index_value, context)
- except (exceptions.AstroidTypeError,
- exceptions.AstroidIndexError,
- exceptions.AttributeInferenceError,
- AttributeError) as exc:
+ except (
+ exceptions.AstroidTypeError,
+ exceptions.AstroidIndexError,
+ exceptions.AttributeInferenceError,
+ AttributeError,
+ ) as exc:
raise exceptions.InferenceError(node=self, context=context) from exc
# Prevent inferring if the inferred subscript
@@ -402,6 +404,7 @@ def infer_subscript(self, context=None):
return dict(node=self, context=context)
+
nodes.Subscript._infer = decorators.path_wrapper(infer_subscript)
nodes.Subscript.infer_lhs = infer_subscript
@@ -416,7 +419,7 @@ def _infer_boolop(self, context=None):
node.
"""
values = self.values
- if self.op == 'or':
+ if self.op == "or":
predicate = operator.truth
else:
predicate = operator.not_
@@ -458,11 +461,13 @@ def _infer_boolop(self, context=None):
return dict(node=self, context=context)
+
nodes.BoolOp._infer = _infer_boolop
# UnaryOp, BinOp and AugAssign inferences
+
def _filter_operation_errors(self, infer_callable, context, error):
for result in infer_callable(self, context):
if isinstance(result, error):
@@ -532,10 +537,12 @@ def _infer_unaryop(self, context=None):
@decorators.path_wrapper
def infer_unaryop(self, context=None):
"""Infer what an UnaryOp should return when evaluated."""
- yield from _filter_operation_errors(self, _infer_unaryop, context,
- util.BadUnaryOperationMessage)
+ yield from _filter_operation_errors(
+ self, _infer_unaryop, context, util.BadUnaryOperationMessage
+ )
return dict(node=self, context=context)
+
nodes.UnaryOp._infer_unaryop = _infer_unaryop
nodes.UnaryOp._infer = infer_unaryop
@@ -559,11 +566,15 @@ def _invoke_binop_inference(instance, opnode, op, other, context, method_name):
def _aug_op(instance, opnode, op, other, context, reverse=False):
"""Get an inference callable for an augmented binary operation."""
method_name = protocols.AUGMENTED_OP_METHOD[op]
- return functools.partial(_invoke_binop_inference,
- instance=instance,
- op=op, opnode=opnode, other=other,
- context=context,
- method_name=method_name)
+ return functools.partial(
+ _invoke_binop_inference,
+ instance=instance,
+ op=op,
+ opnode=opnode,
+ other=other,
+ context=context,
+ method_name=method_name,
+ )
def _bin_op(instance, opnode, op, other, context, reverse=False):
@@ -575,11 +586,15 @@ def _bin_op(instance, opnode, op, other, context, reverse=False):
method_name = protocols.REFLECTED_BIN_OP_METHOD[op]
else:
method_name = protocols.BIN_OP_METHOD[op]
- return functools.partial(_invoke_binop_inference,
- instance=instance,
- op=op, opnode=opnode, other=other,
- context=context,
- method_name=method_name)
+ return functools.partial(
+ _invoke_binop_inference,
+ instance=instance,
+ op=op,
+ opnode=opnode,
+ other=other,
+ context=context,
+ method_name=method_name,
+ )
def _get_binop_contexts(context, left, right):
@@ -603,8 +618,9 @@ def _same_type(type1, type2):
return type1.qname() == type2.qname()
-def _get_binop_flow(left, left_type, binary_opnode, right, right_type,
- context, reverse_context):
+def _get_binop_flow(
+ left, left_type, binary_opnode, right, right_type, context, reverse_context
+):
"""Get the flow for binary operations.
The rules are a bit messy:
@@ -625,16 +641,21 @@ def _get_binop_flow(left, left_type, binary_opnode, right, right_type,
elif helpers.is_subtype(left_type, right_type):
methods = [_bin_op(left, binary_opnode, op, right, context)]
elif helpers.is_supertype(left_type, right_type):
- methods = [_bin_op(right, binary_opnode, op, left, reverse_context, reverse=True),
- _bin_op(left, binary_opnode, op, right, context)]
+ methods = [
+ _bin_op(right, binary_opnode, op, left, reverse_context, reverse=True),
+ _bin_op(left, binary_opnode, op, right, context),
+ ]
else:
- methods = [_bin_op(left, binary_opnode, op, right, context),
- _bin_op(right, binary_opnode, op, left, reverse_context, reverse=True)]
+ methods = [
+ _bin_op(left, binary_opnode, op, right, context),
+ _bin_op(right, binary_opnode, op, left, reverse_context, reverse=True),
+ ]
return methods
-def _get_aug_flow(left, left_type, aug_opnode, right, right_type,
- context, reverse_context):
+def _get_aug_flow(
+ left, left_type, aug_opnode, right, right_type, context, reverse_context
+):
"""Get the flow for augmented binary operations.
The rules are a bit messy:
@@ -653,19 +674,27 @@ def _get_aug_flow(left, left_type, aug_opnode, right, right_type,
bin_op = aug_opnode.op.strip("=")
aug_op = aug_opnode.op
if _same_type(left_type, right_type):
- methods = [_aug_op(left, aug_opnode, aug_op, right, context),
- _bin_op(left, aug_opnode, bin_op, right, context)]
+ methods = [
+ _aug_op(left, aug_opnode, aug_op, right, context),
+ _bin_op(left, aug_opnode, bin_op, right, context),
+ ]
elif helpers.is_subtype(left_type, right_type):
- methods = [_aug_op(left, aug_opnode, aug_op, right, context),
- _bin_op(left, aug_opnode, bin_op, right, context)]
+ methods = [
+ _aug_op(left, aug_opnode, aug_op, right, context),
+ _bin_op(left, aug_opnode, bin_op, right, context),
+ ]
elif helpers.is_supertype(left_type, right_type):
- methods = [_aug_op(left, aug_opnode, aug_op, right, context),
- _bin_op(right, aug_opnode, bin_op, left, reverse_context, reverse=True),
- _bin_op(left, aug_opnode, bin_op, right, context)]
+ methods = [
+ _aug_op(left, aug_opnode, aug_op, right, context),
+ _bin_op(right, aug_opnode, bin_op, left, reverse_context, reverse=True),
+ _bin_op(left, aug_opnode, bin_op, right, context),
+ ]
else:
- methods = [_aug_op(left, aug_opnode, aug_op, right, context),
- _bin_op(left, aug_opnode, bin_op, right, context),
- _bin_op(right, aug_opnode, bin_op, left, reverse_context, reverse=True)]
+ methods = [
+ _aug_op(left, aug_opnode, aug_op, right, context),
+ _bin_op(left, aug_opnode, bin_op, right, context),
+ _bin_op(right, aug_opnode, bin_op, left, reverse_context, reverse=True),
+ ]
return methods
@@ -679,8 +708,9 @@ def _infer_binary_operation(left, right, binary_opnode, context, flow_factory):
context, reverse_context = _get_binop_contexts(context, left, right)
left_type = helpers.object_type(left)
right_type = helpers.object_type(right)
- methods = flow_factory(left, left_type, binary_opnode, right, right_type,
- context, reverse_context)
+ methods = flow_factory(
+ left, left_type, binary_opnode, right, right_type, context, reverse_context
+ )
for method in methods:
try:
results = list(method())
@@ -698,8 +728,9 @@ def _infer_binary_operation(left, right, binary_opnode, context, flow_factory):
if all(map(_is_not_implemented, results)):
continue
- not_implemented = sum(1 for result in results
- if _is_not_implemented(result))
+ not_implemented = sum(
+ 1 for result in results if _is_not_implemented(result)
+ )
if not_implemented and not_implemented != len(results):
# Can't infer yet what this is.
yield util.Uninferable
@@ -739,7 +770,8 @@ def _infer_binop(self, context):
try:
yield from _infer_binary_operation(
- lhs, rhs, self, context, _get_binop_flow)
+ lhs, rhs, self, context, _get_binop_flow
+ )
except exceptions._NonDeducibleTypeHierarchy:
yield util.Uninferable
@@ -747,8 +779,10 @@ def _infer_binop(self, context):
@decorators.yes_if_nothing_inferred
@decorators.path_wrapper
def infer_binop(self, context=None):
- return _filter_operation_errors(self, _infer_binop, context,
- util.BadBinaryOperationMessage)
+ return _filter_operation_errors(
+ self, _infer_binop, context, util.BadBinaryOperationMessage
+ )
+
nodes.BinOp._infer_binop = _infer_binop
nodes.BinOp._infer = infer_binop
@@ -773,7 +807,9 @@ def _infer_augassign(self, context=None):
return
try:
- yield from _infer_binary_operation(lhs, rhs, self, context, _get_aug_flow)
+ yield from _infer_binary_operation(
+ lhs, rhs, self, context, _get_aug_flow
+ )
except exceptions._NonDeducibleTypeHierarchy:
yield util.Uninferable
@@ -781,8 +817,10 @@ def _infer_augassign(self, context=None):
@decorators.raise_if_nothing_inferred
@decorators.path_wrapper
def infer_augassign(self, context=None):
- return _filter_operation_errors(self, _infer_augassign, context,
- util.BadBinaryOperationMessage)
+ return _filter_operation_errors(
+ self, _infer_augassign, context, util.BadBinaryOperationMessage
+ )
+
nodes.AugAssign._infer_augassign = _infer_augassign
nodes.AugAssign._infer = infer_augassign
@@ -797,6 +835,8 @@ def infer_arguments(self, context=None):
if name is None:
raise exceptions.InferenceError(node=self, context=context)
return protocols._arguments_infer_argname(self, name, context)
+
+
nodes.Arguments._infer = infer_arguments
@@ -812,12 +852,15 @@ def infer_assign(self, context=None):
stmts = list(self.assigned_stmts(context=context))
return bases._infer_stmts(stmts, context)
+
+
nodes.AssignName._infer = infer_assign
nodes.AssignAttr._infer = infer_assign
# no infer method on DelName and DelAttr (expected InferenceError)
+
@decorators.raise_if_nothing_inferred
@decorators.path_wrapper
def infer_empty_node(self, context=None):
@@ -828,6 +871,8 @@ def infer_empty_node(self, context=None):
yield from MANAGER.infer_ast_from_something(self.object, context=context)
except exceptions.AstroidError:
yield util.Uninferable
+
+
nodes.EmptyNode._infer = infer_empty_node
@@ -835,6 +880,8 @@ nodes.EmptyNode._infer = infer_empty_node
@decorators.path_wrapper
def infer_index(self, context=None):
return self.value.infer(context)
+
+
nodes.Index._infer = infer_index
# TODO: move directly into bases.Instance when the dependency hell
@@ -848,20 +895,22 @@ def instance_getitem(self, index, context=None):
# Create a new callcontext for providing index as an argument.
new_context.callcontext = contextmod.CallContext(args=[index])
- method = next(self.igetattr('__getitem__', context=context), None)
+ method = next(self.igetattr("__getitem__", context=context), None)
if not isinstance(method, bases.BoundMethod):
raise exceptions.InferenceError(
- 'Could not find __getitem__ for {node!r}.',
- node=self, context=context)
+ "Could not find __getitem__ for {node!r}.", node=self, context=context
+ )
try:
return next(method.infer_call_result(self, new_context))
except StopIteration as exc:
raise exceptions.InferenceError(
- message='Inference for {node!r}[{index!s}] failed.',
+ message="Inference for {node!r}[{index!s}] failed.",
node=self,
index=index,
- context=context) from exc
+ context=context,
+ ) from exc
+
bases.Instance.getitem = instance_getitem
diff --git a/astroid/interpreter/_import/spec.py b/astroid/interpreter/_import/spec.py
index 0fb492b2..982f9b6f 100644
--- a/astroid/interpreter/_import/spec.py
+++ b/astroid/interpreter/_import/spec.py
@@ -13,8 +13,10 @@ import imp
import os
import sys
import zipimport
+
try:
import importlib.machinery
+
_HAS_MACHINERY = True
except ImportError:
_HAS_MACHINERY = False
@@ -26,26 +28,34 @@ except ImportError:
from . import util
-ModuleType = enum.Enum('ModuleType', 'C_BUILTIN C_EXTENSION PKG_DIRECTORY '
- 'PY_CODERESOURCE PY_COMPILED PY_FROZEN PY_RESOURCE '
- 'PY_SOURCE PY_ZIPMODULE PY_NAMESPACE')
-_ImpTypes = {imp.C_BUILTIN: ModuleType.C_BUILTIN,
- imp.C_EXTENSION: ModuleType.C_EXTENSION,
- imp.PKG_DIRECTORY: ModuleType.PKG_DIRECTORY,
- imp.PY_COMPILED: ModuleType.PY_COMPILED,
- imp.PY_FROZEN: ModuleType.PY_FROZEN,
- imp.PY_SOURCE: ModuleType.PY_SOURCE,
- }
-if hasattr(imp, 'PY_RESOURCE'):
+ModuleType = enum.Enum(
+ "ModuleType",
+ "C_BUILTIN C_EXTENSION PKG_DIRECTORY "
+ "PY_CODERESOURCE PY_COMPILED PY_FROZEN PY_RESOURCE "
+ "PY_SOURCE PY_ZIPMODULE PY_NAMESPACE",
+)
+_ImpTypes = {
+ imp.C_BUILTIN: ModuleType.C_BUILTIN,
+ imp.C_EXTENSION: ModuleType.C_EXTENSION,
+ imp.PKG_DIRECTORY: ModuleType.PKG_DIRECTORY,
+ imp.PY_COMPILED: ModuleType.PY_COMPILED,
+ imp.PY_FROZEN: ModuleType.PY_FROZEN,
+ imp.PY_SOURCE: ModuleType.PY_SOURCE,
+}
+if hasattr(imp, "PY_RESOURCE"):
_ImpTypes[imp.PY_RESOURCE] = ModuleType.PY_RESOURCE
-if hasattr(imp, 'PY_CODERESOURCE'):
+if hasattr(imp, "PY_CODERESOURCE"):
_ImpTypes[imp.PY_CODERESOURCE] = ModuleType.PY_CODERESOURCE
+
def _imp_type_to_module_type(imp_type):
return _ImpTypes[imp_type]
-_ModuleSpec = collections.namedtuple('_ModuleSpec', 'name type location '
- 'origin submodule_search_locations')
+
+_ModuleSpec = collections.namedtuple(
+ "_ModuleSpec", "name type location " "origin submodule_search_locations"
+)
+
class ModuleSpec(_ModuleSpec):
"""Defines a class similar to PEP 420's ModuleSpec
@@ -54,11 +64,22 @@ class ModuleSpec(_ModuleSpec):
and where submodules can be found, if the module is a package.
"""
- def __new__(cls, name, module_type, location=None, origin=None,
- submodule_search_locations=None):
- return _ModuleSpec.__new__(cls, name=name, type=module_type,
- location=location, origin=origin,
- submodule_search_locations=submodule_search_locations)
+ def __new__(
+ cls,
+ name,
+ module_type,
+ location=None,
+ origin=None,
+ submodule_search_locations=None,
+ ):
+ return _ModuleSpec.__new__(
+ cls,
+ name=name,
+ type=module_type,
+ location=location,
+ origin=origin,
+ submodule_search_locations=submodule_search_locations,
+ )
class Finder:
@@ -105,8 +126,11 @@ class ImpFinder(Finder):
if stream:
stream.close()
- return ModuleSpec(name=modname, location=mp_filename,
- module_type=_imp_type_to_module_type(mp_desc[2]))
+ return ModuleSpec(
+ name=modname,
+ location=mp_filename,
+ module_type=_imp_type_to_module_type(mp_desc[2]),
+ )
def contribute_to_path(self, spec, processed):
if spec.location is None:
@@ -116,8 +140,11 @@ class ImpFinder(Finder):
if _is_setuptools_namespace(spec.location):
# extend_path is called, search sys.path for module/packages
# of this name see pkgutil.extend_path documentation
- path = [os.path.join(p, *processed) for p in sys.path
- if os.path.isdir(os.path.join(p, *processed))]
+ path = [
+ os.path.join(p, *processed)
+ for p in sys.path
+ if os.path.isdir(os.path.join(p, *processed))
+ ]
else:
path = [spec.location]
return path
@@ -128,16 +155,18 @@ class ExplicitNamespacePackageFinder(ImpFinder):
def find_module(self, modname, module_parts, processed, submodule_path):
if processed:
- modname = '.'.join(processed + [modname])
+ modname = ".".join(processed + [modname])
if util.is_namespace(modname) and modname in sys.modules:
submodule_path = sys.modules[modname].__path__
- return ModuleSpec(name=modname, location='',
- origin='namespace',
- module_type=ModuleType.PY_NAMESPACE,
- submodule_search_locations=submodule_path)
+ return ModuleSpec(
+ name=modname,
+ location="",
+ origin="namespace",
+ module_type=ModuleType.PY_NAMESPACE,
+ submodule_search_locations=submodule_path,
+ )
return None
-
def contribute_to_path(self, spec, processed):
return spec.submodule_search_locations
@@ -155,9 +184,13 @@ class ZipFinder(Finder):
except ImportError:
return None
- return ModuleSpec(name=modname, location=filename,
- origin='egg', module_type=file_type,
- submodule_search_locations=path)
+ return ModuleSpec(
+ name=modname,
+ location=filename,
+ origin="egg",
+ module_type=file_type,
+ submodule_search_locations=path,
+ )
class PathSpecFinder(Finder):
@@ -169,13 +202,16 @@ class PathSpecFinder(Finder):
# origin can be either a string on older Python versions
# or None in case it is a namespace package:
# https://github.com/python/cpython/pull/5481
- is_namespace_pkg = spec.origin in ('namespace', None)
+ is_namespace_pkg = spec.origin in ("namespace", None)
location = spec.origin if not is_namespace_pkg else None
module_type = ModuleType.PY_NAMESPACE if is_namespace_pkg else None
- spec = ModuleSpec(name=spec.name, location=location,
- origin=spec.origin, module_type=module_type,
- submodule_search_locations=list(spec.submodule_search_locations
- or []))
+ spec = ModuleSpec(
+ name=spec.name,
+ location=location,
+ origin=spec.origin,
+ module_type=module_type,
+ submodule_search_locations=list(spec.submodule_search_locations or []),
+ )
return spec
def contribute_to_path(self, spec, processed):
@@ -184,26 +220,23 @@ class PathSpecFinder(Finder):
return None
-_SPEC_FINDERS = (
- ImpFinder,
- ZipFinder,
-)
+_SPEC_FINDERS = (ImpFinder, ZipFinder)
if _HAS_MACHINERY and sys.version_info[:2] >= (3, 4):
- _SPEC_FINDERS += (PathSpecFinder, )
-_SPEC_FINDERS += (ExplicitNamespacePackageFinder, )
+ _SPEC_FINDERS += (PathSpecFinder,)
+_SPEC_FINDERS += (ExplicitNamespacePackageFinder,)
def _is_setuptools_namespace(location):
try:
- with open(os.path.join(location, '__init__.py'), 'rb') as stream:
+ with open(os.path.join(location, "__init__.py"), "rb") as stream:
data = stream.read(4096)
except IOError:
pass
else:
- extend_path = b'pkgutil' in data and b'extend_path' in data
+ extend_path = b"pkgutil" in data and b"extend_path" in data
declare_namespace = (
- b"pkg_resources" in data
- and b"declare_namespace(__name__)" in data)
+ b"pkg_resources" in data and b"declare_namespace(__name__)" in data
+ )
return extend_path or declare_namespace
@@ -239,13 +272,17 @@ def _search_zip(modpath, pic):
found = importer.find_module(modpath[0])
if found:
if not importer.find_module(os.path.sep.join(modpath)):
- raise ImportError('No module named %s in %s/%s' % (
- '.'.join(modpath[1:]), filepath, modpath))
- #import code; code.interact(local=locals())
- return (ModuleType.PY_ZIPMODULE,
- os.path.abspath(filepath) + os.path.sep + os.path.sep.join(modpath),
- filepath)
- raise ImportError('No module named %s' % '.'.join(modpath))
+ raise ImportError(
+ "No module named %s in %s/%s"
+ % (".".join(modpath[1:]), filepath, modpath)
+ )
+ # import code; code.interact(local=locals())
+ return (
+ ModuleType.PY_ZIPMODULE,
+ os.path.abspath(filepath) + os.path.sep + os.path.sep.join(modpath),
+ filepath,
+ )
+ raise ImportError("No module named %s" % ".".join(modpath))
def _find_spec_with_path(search_path, modname, module_parts, processed, submodule_path):
@@ -256,7 +293,7 @@ def _find_spec_with_path(search_path, modname, module_parts, processed, submodul
continue
return finder, spec
- raise ImportError('No module named %s' % '.'.join(module_parts))
+ raise ImportError("No module named %s" % ".".join(module_parts))
def find_spec(modpath, path=None):
@@ -287,9 +324,9 @@ def find_spec(modpath, path=None):
while modpath:
modname = modpath.pop(0)
- finder, spec = _find_spec_with_path(_path, modname,
- module_parts, processed,
- submodule_path or path)
+ finder, spec = _find_spec_with_path(
+ _path, modname, module_parts, processed, submodule_path or path
+ )
processed.append(modname)
if modpath:
submodule_path = finder.contribute_to_path(spec, processed)
diff --git a/astroid/interpreter/_import/util.py b/astroid/interpreter/_import/util.py
index 30bfd399..a917bd3d 100644
--- a/astroid/interpreter/_import/util.py
+++ b/astroid/interpreter/_import/util.py
@@ -7,5 +7,4 @@ except ImportError:
def is_namespace(modname):
- return (pkg_resources is not None
- and modname in pkg_resources._namespace_packages)
+ return pkg_resources is not None and modname in pkg_resources._namespace_packages
diff --git a/astroid/interpreter/dunder_lookup.py b/astroid/interpreter/dunder_lookup.py
index 625ec93b..0ae9bc90 100644
--- a/astroid/interpreter/dunder_lookup.py
+++ b/astroid/interpreter/dunder_lookup.py
@@ -22,15 +22,11 @@ def _lookup_in_mro(node, name):
attrs = node.locals.get(name, [])
nodes = itertools.chain.from_iterable(
- ancestor.locals.get(name, [])
- for ancestor in node.ancestors(recurs=True)
+ ancestor.locals.get(name, []) for ancestor in node.ancestors(recurs=True)
)
values = list(itertools.chain(attrs, nodes))
if not values:
- raise exceptions.AttributeInferenceError(
- attribute=name,
- target=node
- )
+ raise exceptions.AttributeInferenceError(attribute=name, target=node)
return values
@@ -42,30 +38,22 @@ def lookup(node, name):
will be returned. Otherwise, `astroid.AttributeInferenceError`
is going to be raised.
"""
- if isinstance(node, (astroid.List,
- astroid.Tuple,
- astroid.Const,
- astroid.Dict,
- astroid.Set)):
+ if isinstance(
+ node, (astroid.List, astroid.Tuple, astroid.Const, astroid.Dict, astroid.Set)
+ ):
return _builtin_lookup(node, name)
if isinstance(node, astroid.Instance):
return _lookup_in_mro(node, name)
if isinstance(node, astroid.ClassDef):
return _class_lookup(node, name)
- raise exceptions.AttributeInferenceError(
- attribute=name,
- target=node
- )
+ raise exceptions.AttributeInferenceError(attribute=name, target=node)
def _class_lookup(node, name):
metaclass = node.metaclass()
if metaclass is None:
- raise exceptions.AttributeInferenceError(
- attribute=name,
- target=node
- )
+ raise exceptions.AttributeInferenceError(attribute=name, target=node)
return _lookup_in_mro(metaclass, name)
@@ -73,9 +61,6 @@ def _class_lookup(node, name):
def _builtin_lookup(node, name):
values = node.locals.get(name, [])
if not values:
- raise exceptions.AttributeInferenceError(
- attribute=name,
- target=node
- )
+ raise exceptions.AttributeInferenceError(attribute=name, target=node)
return values
diff --git a/astroid/interpreter/objectmodel.py b/astroid/interpreter/objectmodel.py
index 9f02a910..65e9c641 100644
--- a/astroid/interpreter/objectmodel.py
+++ b/astroid/interpreter/objectmodel.py
@@ -42,8 +42,9 @@ def _dunder_dict(instance, attributes):
obj = node_classes.Dict(parent=instance)
# Convert the keys to node strings
- keys = [node_classes.Const(value=value, parent=obj)
- for value in list(attributes.keys())]
+ keys = [
+ node_classes.Const(value=value, parent=obj) for value in list(attributes.keys())
+ ]
# The original attribute has a list of elements for each key,
# but that is not useful for retrieving the special attribute's value.
@@ -55,27 +56,27 @@ def _dunder_dict(instance, attributes):
class ObjectModel:
-
def __init__(self):
self._instance = None
def __repr__(self):
result = []
cname = type(self).__name__
- string = '%(cname)s(%(fields)s)'
+ string = "%(cname)s(%(fields)s)"
alignment = len(cname) + 1
for field in sorted(self.attributes()):
width = 80 - len(field) - alignment
- lines = pprint.pformat(field, indent=2,
- width=width).splitlines(True)
+ lines = pprint.pformat(field, indent=2, width=width).splitlines(True)
inner = [lines[0]]
for line in lines[1:]:
- inner.append(' ' * alignment + line)
+ inner.append(" " * alignment + line)
result.append(field)
- return string % {'cname': cname,
- 'fields': (',\n' + ' ' * alignment).join(result)}
+ return string % {
+ "cname": cname,
+ "fields": (",\n" + " " * alignment).join(result),
+ }
def __call__(self, instance):
self._instance = instance
@@ -97,7 +98,7 @@ class ObjectModel:
@lru_cache(maxsize=None)
def attributes(self):
"""Get the attributes which are exported by this object model."""
- return [obj[2:] for obj in dir(self) if obj.startswith('py')]
+ return [obj[2:] for obj in dir(self) if obj.startswith("py")]
def lookup(self, name):
"""Look up the given *name* in the current model
@@ -112,10 +113,9 @@ class ObjectModel:
class ModuleModel(ObjectModel):
-
def _builtins(self):
builtins_ast_module = astroid.MANAGER.astroid_cache[builtins.__name__]
- return builtins_ast_module.special_attributes.lookup('__dict__')
+ return builtins_ast_module.special_attributes.lookup("__dict__")
@property
def pybuiltins(self):
@@ -129,13 +129,16 @@ class ModuleModel(ObjectModel):
@property
def py__path__(self):
if not self._instance.package:
- raise exceptions.AttributeInferenceError(target=self._instance,
- attribute='__path__')
+ raise exceptions.AttributeInferenceError(
+ target=self._instance, attribute="__path__"
+ )
path_objs = [
node_classes.Const(
- value=path if not path.endswith('__init__.py') else os.path.dirname(path),
- parent=self._instance
+ value=path
+ if not path.endswith("__init__.py")
+ else os.path.dirname(path),
+ parent=self._instance,
)
for path in self._instance.path
]
@@ -147,18 +150,15 @@ class ModuleModel(ObjectModel):
@property
def py__name__(self):
- return node_classes.Const(value=self._instance.name,
- parent=self._instance)
+ return node_classes.Const(value=self._instance.name, parent=self._instance)
@property
def py__doc__(self):
- return node_classes.Const(value=self._instance.doc,
- parent=self._instance)
+ return node_classes.Const(value=self._instance.doc, parent=self._instance)
@property
def py__file__(self):
- return node_classes.Const(value=self._instance.file,
- parent=self._instance)
+ return node_classes.Const(value=self._instance.file, parent=self._instance)
@property
def py__dict__(self):
@@ -169,7 +169,7 @@ class ModuleModel(ObjectModel):
@property
def py__package__(self):
if not self._instance.package:
- value = ''
+ value = ""
else:
value = self._instance.name
@@ -196,21 +196,17 @@ class ModuleModel(ObjectModel):
class FunctionModel(ObjectModel):
-
@property
def py__name__(self):
- return node_classes.Const(value=self._instance.name,
- parent=self._instance)
+ return node_classes.Const(value=self._instance.name, parent=self._instance)
@property
def py__doc__(self):
- return node_classes.Const(value=self._instance.doc,
- parent=self._instance)
+ return node_classes.Const(value=self._instance.doc, parent=self._instance)
@property
def py__qualname__(self):
- return node_classes.Const(value=self._instance.qname(),
- parent=self._instance)
+ return node_classes.Const(value=self._instance.qname(), parent=self._instance)
@property
def py__defaults__(self):
@@ -234,23 +230,23 @@ class FunctionModel(ObjectModel):
args = self._instance.args
pair_annotations = itertools.chain(
zip(args.args or [], args.annotations),
- zip(args.kwonlyargs, args.kwonlyargs_annotations)
+ zip(args.kwonlyargs, args.kwonlyargs_annotations),
)
annotations = {
- arg.name: annotation
- for (arg, annotation) in pair_annotations
- if annotation
+ arg.name: annotation for (arg, annotation) in pair_annotations if annotation
}
if args.varargannotation:
annotations[args.vararg] = args.varargannotation
if args.kwargannotation:
annotations[args.kwarg] = args.kwargannotation
if returns:
- annotations['return'] = returns
+ annotations["return"] = returns
- items = [(node_classes.Const(key, parent=obj), value)
- for (key, value) in annotations.items()]
+ items = [
+ (node_classes.Const(key, parent=obj), value)
+ for (key, value) in annotations.items()
+ ]
obj.postinit(items)
return obj
@@ -263,7 +259,6 @@ class FunctionModel(ObjectModel):
@property
def py__kwdefaults__(self):
-
def _default_args(args, parent):
for arg in args.kwonlyargs:
try:
@@ -303,15 +298,17 @@ class FunctionModel(ObjectModel):
if len(caller.args) != 2:
raise exceptions.InferenceError(
"Invalid arguments for descriptor binding",
- target=self, context=context)
+ target=self,
+ context=context,
+ )
context = contextmod.copy_context(context)
cls = next(caller.args[0].infer(context=context))
if cls is astroid.Uninferable:
raise exceptions.InferenceError(
- "Invalid class inferred",
- target=self, context=context)
+ "Invalid class inferred", target=self, context=context
+ )
# For some reason func is a Node that the below
# code is not expecting
@@ -321,12 +318,15 @@ class FunctionModel(ObjectModel):
# Rebuild the original value, but with the parent set as the
# class where it will be bound.
- new_func = func.__class__(name=func.name, doc=func.doc,
- lineno=func.lineno, col_offset=func.col_offset,
- parent=cls)
+ new_func = func.__class__(
+ name=func.name,
+ doc=func.doc,
+ lineno=func.lineno,
+ col_offset=func.col_offset,
+ parent=cls,
+ )
# pylint: disable=no-member
- new_func.postinit(func.args, func.body,
- func.decorators, func.returns)
+ new_func.postinit(func.args, func.body, func.decorators, func.returns)
# Build a proper bound method that points to our newly built function.
proxy = bases.UnboundMethod(new_func)
@@ -346,8 +346,8 @@ class FunctionModel(ObjectModel):
"""
nonlocal func
params = func.args.args.copy()
- params.append(astroid.AssignName(name='type'))
- arguments = astroid.Arguments(parent=func.args.parent,)
+ params.append(astroid.AssignName(name="type"))
+ arguments = astroid.Arguments(parent=func.args.parent)
arguments.postinit(
args=params,
defaults=[],
@@ -388,7 +388,6 @@ class FunctionModel(ObjectModel):
class ClassModel(ObjectModel):
-
@property
def py__module__(self):
return node_classes.Const(self._instance.root().qname())
@@ -408,8 +407,9 @@ class ClassModel(ObjectModel):
@property
def py__mro__(self):
if not self._instance.newstyle:
- raise exceptions.AttributeInferenceError(target=self._instance,
- attribute='__mro__')
+ raise exceptions.AttributeInferenceError(
+ target=self._instance, attribute="__mro__"
+ )
mro = self._instance.mro()
obj = node_classes.Tuple(parent=self._instance)
@@ -419,8 +419,9 @@ class ClassModel(ObjectModel):
@property
def pymro(self):
if not self._instance.newstyle:
- raise exceptions.AttributeInferenceError(target=self._instance,
- attribute='mro')
+ raise exceptions.AttributeInferenceError(
+ target=self._instance, attribute="mro"
+ )
from astroid import bases
@@ -433,7 +434,7 @@ class ClassModel(ObjectModel):
yield other_self.py__mro__
implicit_metaclass = self._instance.implicit_metaclass()
- mro_method = implicit_metaclass.locals['mro'][0]
+ mro_method = implicit_metaclass.locals["mro"][0]
return MroBoundMethod(proxy=mro_method, bound=implicit_metaclass)
@property
@@ -447,6 +448,7 @@ class ClassModel(ObjectModel):
@property
def py__class__(self):
from astroid import helpers
+
return helpers.object_type(self._instance)
@property
@@ -460,13 +462,17 @@ class ClassModel(ObjectModel):
from astroid import scoped_nodes
if not self._instance.newstyle:
- raise exceptions.AttributeInferenceError(target=self._instance,
- attribute='__subclasses__')
+ raise exceptions.AttributeInferenceError(
+ target=self._instance, attribute="__subclasses__"
+ )
qname = self._instance.qname()
root = self._instance.root()
- classes = [cls for cls in root.nodes_of_class(scoped_nodes.ClassDef)
- if cls != self._instance and cls.is_subtype_of(qname)]
+ classes = [
+ cls
+ for cls in root.nodes_of_class(scoped_nodes.ClassDef)
+ if cls != self._instance and cls.is_subtype_of(qname)
+ ]
obj = node_classes.List(parent=self._instance)
obj.postinit(classes)
@@ -476,9 +482,8 @@ class ClassModel(ObjectModel):
yield obj
implicit_metaclass = self._instance.implicit_metaclass()
- subclasses_method = implicit_metaclass.locals['__subclasses__'][0]
- return SubclassesBoundMethod(proxy=subclasses_method,
- bound=implicit_metaclass)
+ subclasses_method = implicit_metaclass.locals["__subclasses__"][0]
+ return SubclassesBoundMethod(proxy=subclasses_method, bound=implicit_metaclass)
@property
def py__dict__(self):
@@ -486,7 +491,6 @@ class ClassModel(ObjectModel):
class SuperModel(ObjectModel):
-
@property
def py__thisclass__(self):
return self._instance.mro_pointer
@@ -505,10 +509,10 @@ class SuperModel(ObjectModel):
class UnboundMethodModel(ObjectModel):
-
@property
def py__class__(self):
from astroid import helpers
+
return helpers.object_type(self._instance)
@property
@@ -525,7 +529,6 @@ class UnboundMethodModel(ObjectModel):
class BoundMethodModel(FunctionModel):
-
@property
def py__func__(self):
return self._instance._proxied._proxied
@@ -536,52 +539,51 @@ class BoundMethodModel(FunctionModel):
class GeneratorModel(FunctionModel):
-
def __new__(cls, *args, **kwargs):
# Append the values from the GeneratorType unto this object.
ret = super(GeneratorModel, cls).__new__(cls, *args, **kwargs)
- generator = astroid.MANAGER.astroid_cache[builtins.__name__]['generator']
+ generator = astroid.MANAGER.astroid_cache[builtins.__name__]["generator"]
for name, values in generator.locals.items():
method = values[0]
patched = lambda cls, meth=method: meth
- setattr(type(ret), 'py' + name, property(patched))
+ setattr(type(ret), "py" + name, property(patched))
return ret
@property
def py__name__(self):
- return node_classes.Const(value=self._instance.parent.name,
- parent=self._instance)
+ return node_classes.Const(
+ value=self._instance.parent.name, parent=self._instance
+ )
@property
def py__doc__(self):
- return node_classes.Const(value=self._instance.parent.doc,
- parent=self._instance)
+ return node_classes.Const(
+ value=self._instance.parent.doc, parent=self._instance
+ )
class AsyncGeneratorModel(GeneratorModel):
-
def __new__(cls, *args, **kwargs):
# Append the values from the AGeneratorType unto this object.
ret = super().__new__(cls, *args, **kwargs)
astroid_builtins = astroid.MANAGER.astroid_cache[builtins.__name__]
- generator = astroid_builtins.get('async_generator')
+ generator = astroid_builtins.get("async_generator")
if generator is None:
# Make it backward compatible.
- generator = astroid_builtins.get('generator')
+ generator = astroid_builtins.get("generator")
for name, values in generator.locals.items():
method = values[0]
patched = lambda cls, meth=method: meth
- setattr(type(ret), 'py' + name, property(patched))
+ setattr(type(ret), "py" + name, property(patched))
return ret
class InstanceModel(ObjectModel):
-
@property
def py__class__(self):
return self._instance._proxied
@@ -600,12 +602,11 @@ class InstanceModel(ObjectModel):
class ExceptionInstanceModel(InstanceModel):
-
@property
def pyargs(self):
- message = node_classes.Const('')
+ message = node_classes.Const("")
args = node_classes.Tuple(parent=self._instance)
- args.postinit((message, ))
+ args.postinit((message,))
return args
@property
@@ -616,7 +617,6 @@ class ExceptionInstanceModel(InstanceModel):
class DictModel(ObjectModel):
-
@property
def py__class__(self):
return self._instance._proxied
@@ -642,9 +642,10 @@ class DictModel(ObjectModel):
obj.postinit(elts=elems)
from astroid import objects
+
obj = objects.DictItems(obj)
- return self._generic_dict_attribute(obj, 'items')
+ return self._generic_dict_attribute(obj, "items")
@property
def pykeys(self):
@@ -653,9 +654,10 @@ class DictModel(ObjectModel):
obj.postinit(elts=keys)
from astroid import objects
+
obj = objects.DictKeys(obj)
- return self._generic_dict_attribute(obj, 'keys')
+ return self._generic_dict_attribute(obj, "keys")
@property
def pyvalues(self):
@@ -665,6 +667,7 @@ class DictModel(ObjectModel):
obj.postinit(values)
from astroid import objects
+
obj = objects.DictValues(obj)
- return self._generic_dict_attribute(obj, 'values')
+ return self._generic_dict_attribute(obj, "values")
diff --git a/astroid/manager.py b/astroid/manager.py
index 7c8fca5f..f05588ae 100644
--- a/astroid/manager.py
+++ b/astroid/manager.py
@@ -29,8 +29,8 @@ from astroid import transforms
def safe_repr(obj):
try:
return repr(obj)
- except Exception: # pylint: disable=broad-except
- return '???'
+ except Exception: # pylint: disable=broad-except
+ return "???"
class AstroidManager:
@@ -40,7 +40,7 @@ class AstroidManager:
Use the Borg pattern.
"""
- name = 'astroid loader'
+ name = "astroid loader"
brain = {}
def __init__(self):
@@ -73,25 +73,32 @@ class AstroidManager:
pass
if modname is None:
try:
- modname = '.'.join(modutils.modpath_from_file(filepath))
+ modname = ".".join(modutils.modpath_from_file(filepath))
except ImportError:
modname = filepath
- if modname in self.astroid_cache and self.astroid_cache[modname].file == filepath:
+ if (
+ modname in self.astroid_cache
+ and self.astroid_cache[modname].file == filepath
+ ):
return self.astroid_cache[modname]
if source:
from astroid.builder import AstroidBuilder
+
return AstroidBuilder(self).file_build(filepath, modname)
if fallback and modname:
return self.ast_from_module_name(modname)
raise exceptions.AstroidBuildingError(
- 'Unable to build an AST for {path}.', path=filepath)
+ "Unable to build an AST for {path}.", path=filepath
+ )
def _build_stub_module(self, modname):
from astroid.builder import AstroidBuilder
- return AstroidBuilder(self).string_build('', modname)
+
+ return AstroidBuilder(self).string_build("", modname)
def _build_namespace_module(self, modname, path):
from astroid.builder import build_namespace_package_module
+
return build_namespace_package_module(modname, path)
def _can_load_extension(self, modname):
@@ -99,16 +106,17 @@ class AstroidManager:
return True
if modutils.is_standard_module(modname):
return True
- parts = modname.split('.')
+ parts = modname.split(".")
return any(
- '.'.join(parts[:x]) in self.extension_package_whitelist
- for x in range(1, len(parts) + 1))
+ ".".join(parts[:x]) in self.extension_package_whitelist
+ for x in range(1, len(parts) + 1)
+ )
def ast_from_module_name(self, modname, context_file=None):
"""given a module name, return the astroid object"""
if modname in self.astroid_cache:
return self.astroid_cache[modname]
- if modname == '__main__':
+ if modname == "__main__":
return self._build_stub_module(modname)
old_cwd = os.getcwd()
if context_file:
@@ -120,32 +128,41 @@ class AstroidManager:
if module is not None:
return module
- elif found_spec.type in (spec.ModuleType.C_BUILTIN,
- spec.ModuleType.C_EXTENSION):
- if (found_spec.type == spec.ModuleType.C_EXTENSION
- and not self._can_load_extension(modname)):
+ elif found_spec.type in (
+ spec.ModuleType.C_BUILTIN,
+ spec.ModuleType.C_EXTENSION,
+ ):
+ if (
+ found_spec.type == spec.ModuleType.C_EXTENSION
+ and not self._can_load_extension(modname)
+ ):
return self._build_stub_module(modname)
try:
module = modutils.load_module_from_name(modname)
except Exception as ex:
raise exceptions.AstroidImportError(
- 'Loading {modname} failed with:\n{error}',
- modname=modname, path=found_spec.location) from ex
+ "Loading {modname} failed with:\n{error}",
+ modname=modname,
+ path=found_spec.location,
+ ) from ex
return self.ast_from_module(module, modname)
elif found_spec.type == spec.ModuleType.PY_COMPILED:
raise exceptions.AstroidImportError(
"Unable to load compiled module {modname}.",
- modname=modname, path=found_spec.location)
+ modname=modname,
+ path=found_spec.location,
+ )
elif found_spec.type == spec.ModuleType.PY_NAMESPACE:
- return self._build_namespace_module(modname,
- found_spec.submodule_search_locations)
+ return self._build_namespace_module(
+ modname, found_spec.submodule_search_locations
+ )
if found_spec.location is None:
raise exceptions.AstroidImportError(
- "Can't find a file for module {modname}.",
- modname=modname)
+ "Can't find a file for module {modname}.", modname=modname
+ )
return self.ast_from_file(found_spec.location, modname, fallback=False)
except exceptions.AstroidBuildingError as e:
@@ -162,21 +179,23 @@ class AstroidManager:
if zipimport is None:
return None
from astroid.builder import AstroidBuilder
+
builder = AstroidBuilder(self)
- for ext in ('.zip', '.egg'):
+ for ext in (".zip", ".egg"):
try:
eggpath, resource = filepath.rsplit(ext + os.path.sep, 1)
except ValueError:
continue
try:
importer = zipimport.zipimporter(eggpath + ext)
- zmodname = resource.replace(os.path.sep, '.')
+ zmodname = resource.replace(os.path.sep, ".")
if importer.is_package(resource):
- zmodname = zmodname + '.__init__'
- module = builder.string_build(importer.get_source(resource),
- zmodname, filepath)
+ zmodname = zmodname + ".__init__"
+ module = builder.string_build(
+ importer.get_source(resource), zmodname, filepath
+ )
return module
- except Exception: # pylint: disable=broad-except
+ except Exception: # pylint: disable=broad-except
continue
return None
@@ -186,11 +205,14 @@ class AstroidManager:
except KeyError:
try:
value = modutils.file_info_from_modpath(
- modname.split('.'), context_file=contextfile)
+ modname.split("."), context_file=contextfile
+ )
except ImportError as ex:
value = exceptions.AstroidImportError(
- 'Failed to import module {modname} with error:\n{error}.',
- modname=modname, error=ex)
+ "Failed to import module {modname} with error:\n{error}.",
+ modname=modname,
+ error=ex,
+ )
self._mod_file_cache[(modname, contextfile)] = value
if isinstance(value, exceptions.AstroidBuildingError):
raise value
@@ -209,6 +231,7 @@ class AstroidManager:
except AttributeError:
pass
from astroid.builder import AstroidBuilder
+
return AstroidBuilder(self).module_build(module, modname)
def ast_from_class(self, klass, modname=None):
@@ -218,14 +241,17 @@ class AstroidManager:
modname = klass.__module__
except AttributeError as exc:
raise exceptions.AstroidBuildingError(
- 'Unable to get module for class {class_name}.',
- cls=klass, class_repr=safe_repr(klass), modname=modname) from exc
+ "Unable to get module for class {class_name}.",
+ cls=klass,
+ class_repr=safe_repr(klass),
+ modname=modname,
+ ) from exc
modastroid = self.ast_from_module_name(modname)
- return modastroid.getattr(klass.__name__)[0] # XXX
+ return modastroid.getattr(klass.__name__)[0] # XXX
def infer_ast_from_something(self, obj, context=None):
"""infer astroid for the given class"""
- if hasattr(obj, '__class__') and not isinstance(obj, type):
+ if hasattr(obj, "__class__") and not isinstance(obj, type):
klass = obj.__class__
else:
klass = obj
@@ -233,22 +259,31 @@ class AstroidManager:
modname = klass.__module__
except AttributeError as exc:
raise exceptions.AstroidBuildingError(
- 'Unable to get module for {class_repr}.',
- cls=klass, class_repr=safe_repr(klass)) from exc
+ "Unable to get module for {class_repr}.",
+ cls=klass,
+ class_repr=safe_repr(klass),
+ ) from exc
except Exception as exc:
raise exceptions.AstroidImportError(
- 'Unexpected error while retrieving module for {class_repr}:\n'
- '{error}', cls=klass, class_repr=safe_repr(klass)) from exc
+ "Unexpected error while retrieving module for {class_repr}:\n"
+ "{error}",
+ cls=klass,
+ class_repr=safe_repr(klass),
+ ) from exc
try:
name = klass.__name__
except AttributeError as exc:
raise exceptions.AstroidBuildingError(
- 'Unable to get name for {class_repr}:\n',
- cls=klass, class_repr=safe_repr(klass)) from exc
+ "Unable to get name for {class_repr}:\n",
+ cls=klass,
+ class_repr=safe_repr(klass),
+ ) from exc
except Exception as exc:
raise exceptions.AstroidImportError(
- 'Unexpected error while retrieving name for {class_repr}:\n'
- '{error}', cls=klass, class_repr=safe_repr(klass)) from exc
+ "Unexpected error while retrieving name for {class_repr}:\n" "{error}",
+ cls=klass,
+ class_repr=safe_repr(klass),
+ ) from exc
# take care, on living object __module__ is regularly wrong :(
modastroid = self.ast_from_module_name(modname)
if klass is obj:
@@ -280,5 +315,5 @@ class AstroidManager:
# unittest_lookup.LookupTC.test_builtin_lookup fail depending on the
# test order
import astroid.raw_building
- astroid.raw_building._astroid_bootstrapping(
- astroid_builtin=astroid_builtin)
+
+ astroid.raw_building._astroid_bootstrapping(astroid_builtin=astroid_builtin)
diff --git a/astroid/mixins.py b/astroid/mixins.py
index c199f61a..cec4b4bc 100644
--- a/astroid/mixins.py
+++ b/astroid/mixins.py
@@ -53,7 +53,6 @@ class FilterStmtsMixin:
class AssignTypeMixin:
-
def assign_type(self):
return self
@@ -69,7 +68,6 @@ class AssignTypeMixin:
class ParentAssignTypeMixin(AssignTypeMixin):
-
def assign_type(self):
return self.parent.assign_type()
@@ -88,7 +86,7 @@ class ImportFromMixin(FilterStmtsMixin):
# on relative imports
# XXX: no more needed ?
mymodule = self.root()
- level = getattr(self, 'level', None) # Import as no level
+ level = getattr(self, "level", None) # Import as no level
if modname is None:
modname = self.modname
# XXX we should investigate deeper if we really want to check
@@ -97,22 +95,25 @@ class ImportFromMixin(FilterStmtsMixin):
# FIXME: we used to raise InferenceError here, but why ?
return mymodule
- return mymodule.import_module(modname, level=level,
- relative_only=level and level >= 1)
+ return mymodule.import_module(
+ modname, level=level, relative_only=level and level >= 1
+ )
def real_name(self, asname):
"""get name from 'as' name"""
for name, _asname in self.names:
- if name == '*':
+ if name == "*":
return asname
if not _asname:
- name = name.split('.', 1)[0]
+ name = name.split(".", 1)[0]
_asname = name
if asname == _asname:
return name
raise exceptions.AttributeInferenceError(
- 'Could not find original name for {attribute} in {target!r}',
- target=self, attribute=asname)
+ "Could not find original name for {attribute} in {target!r}",
+ target=self,
+ attribute=asname,
+ )
class MultiLineBlockMixin:
@@ -125,10 +126,7 @@ class MultiLineBlockMixin:
@decorators.cachedproperty
def _multi_line_blocks(self):
- return tuple(
- getattr(self, field)
- for field in self._multi_line_block_fields
- )
+ return tuple(getattr(self, field) for field in self._multi_line_block_fields)
def _get_return_nodes_skip_functions(self):
for block in self._multi_line_blocks:
@@ -152,5 +150,6 @@ class MultiLineBlockMixin:
class NoChildrenMixin:
"""Mixin for nodes with no children, e.g. Pass."""
+
def get_children(self):
yield from ()
diff --git a/astroid/modutils.py b/astroid/modutils.py
index 90ea31c7..4e6f918f 100644
--- a/astroid/modutils.py
+++ b/astroid/modutils.py
@@ -32,9 +32,11 @@ import os
import platform
import sys
import itertools
-from distutils.sysconfig import get_python_lib # pylint: disable=import-error
+from distutils.sysconfig import get_python_lib # pylint: disable=import-error
+
# pylint: disable=import-error, no-name-in-module
from distutils.errors import DistutilsPlatformError
+
# distutils is replaced by virtualenv with a module that does
# weird path manipulations in order to get to the
# real distutils module.
@@ -42,12 +44,12 @@ from distutils.errors import DistutilsPlatformError
from .interpreter._import import spec
from .interpreter._import import util
-if sys.platform.startswith('win'):
- PY_SOURCE_EXTS = ('py', 'pyw')
- PY_COMPILED_EXTS = ('dll', 'pyd')
+if sys.platform.startswith("win"):
+ PY_SOURCE_EXTS = ("py", "pyw")
+ PY_COMPILED_EXTS = ("dll", "pyd")
else:
- PY_SOURCE_EXTS = ('py',)
- PY_COMPILED_EXTS = ('so',)
+ PY_SOURCE_EXTS = ("py",)
+ PY_COMPILED_EXTS = ("so",)
try:
@@ -60,37 +62,38 @@ try:
get_python_lib(standard_lib=True, prefix=sys.prefix),
# Take care of installations where exec_prefix != prefix.
get_python_lib(standard_lib=True, prefix=sys.exec_prefix),
- get_python_lib(standard_lib=True)}
+ get_python_lib(standard_lib=True),
+ }
# get_python_lib(standard_lib=1) is not available on pypy, set STD_LIB_DIR to
# non-valid path, see https://bugs.pypy.org/issue1164
except DistutilsPlatformError:
STD_LIB_DIRS = set()
-if os.name == 'nt':
- STD_LIB_DIRS.add(os.path.join(sys.prefix, 'dlls'))
+if os.name == "nt":
+ STD_LIB_DIRS.add(os.path.join(sys.prefix, "dlls"))
try:
# real_prefix is defined when running inside virtual environments,
# created with the **virtualenv** library.
- STD_LIB_DIRS.add(os.path.join(sys.real_prefix, 'dlls'))
+ STD_LIB_DIRS.add(os.path.join(sys.real_prefix, "dlls"))
except AttributeError:
# sys.base_exec_prefix is always defined, but in a virtual environment
# created with the stdlib **venv** module, it points to the original
# installation, if the virtual env is activated.
try:
- STD_LIB_DIRS.add(os.path.join(sys.base_exec_prefix, 'dlls'))
+ STD_LIB_DIRS.add(os.path.join(sys.base_exec_prefix, "dlls"))
except AttributeError:
pass
-if platform.python_implementation() == 'PyPy':
- _root = os.path.join(sys.prefix, 'lib_pypy')
+if platform.python_implementation() == "PyPy":
+ _root = os.path.join(sys.prefix, "lib_pypy")
STD_LIB_DIRS.add(_root)
try:
# real_prefix is defined when running inside virtualenv.
- STD_LIB_DIRS.add(os.path.join(sys.real_prefix, 'lib_pypy'))
+ STD_LIB_DIRS.add(os.path.join(sys.real_prefix, "lib_pypy"))
except AttributeError:
pass
del _root
-if os.name == 'posix':
+if os.name == "posix":
# Need the real prefix is we're under a virtualenv, otherwise
# the usual one will do.
try:
@@ -99,11 +102,11 @@ if os.name == 'posix':
prefix = sys.prefix
def _posix_path(path):
- base_python = 'python%d.%d' % sys.version_info[:2]
+ base_python = "python%d.%d" % sys.version_info[:2]
return os.path.join(prefix, path, base_python)
- STD_LIB_DIRS.add(_posix_path('lib'))
- if sys.maxsize > 2**32:
+ STD_LIB_DIRS.add(_posix_path("lib"))
+ if sys.maxsize > 2 ** 32:
# This tries to fix a problem with /usr/lib64 builds,
# where systems are running both 32-bit and 64-bit code
# on the same machine, which reflects into the places where
@@ -111,10 +114,10 @@ if os.name == 'posix':
# here http://bugs.python.org/issue1294959.
# An easy reproducing case would be
# https://github.com/PyCQA/pylint/issues/712#issuecomment-163178753
- STD_LIB_DIRS.add(_posix_path('lib64'))
+ STD_LIB_DIRS.add(_posix_path("lib64"))
EXT_LIB_DIR = get_python_lib()
-IS_JYTHON = platform.python_implementation() == 'Jython'
+IS_JYTHON = platform.python_implementation() == "Jython"
BUILTIN_MODULES = dict.fromkeys(sys.builtin_module_names, True)
@@ -123,6 +126,7 @@ class NoSourceFile(Exception):
source file for a precompiled file
"""
+
def _normalize_path(path):
return os.path.normcase(os.path.abspath(path))
@@ -158,6 +162,7 @@ def _handle_blacklist(blacklist, dirnames, filenames):
_NORM_PATH_CACHE = {}
+
def _cache_normalize_path(path):
"""abspath with caching"""
# _module_file calls abspath on every path in sys.path every time it's
@@ -166,11 +171,12 @@ def _cache_normalize_path(path):
try:
return _NORM_PATH_CACHE[path]
except KeyError:
- if not path: # don't cache result for ''
+ if not path: # don't cache result for ''
return _normalize_path(path)
result = _NORM_PATH_CACHE[path] = _normalize_path(path)
return result
+
def load_module_from_name(dotted_name, path=None, use_sys=True):
"""Load a Python module from its name.
@@ -193,7 +199,7 @@ def load_module_from_name(dotted_name, path=None, use_sys=True):
:rtype: module
:return: the loaded module
"""
- return load_module_from_modpath(dotted_name.split('.'), path, use_sys)
+ return load_module_from_modpath(dotted_name.split("."), path, use_sys)
def load_module_from_modpath(parts, path=None, use_sys=1):
@@ -219,14 +225,14 @@ def load_module_from_modpath(parts, path=None, use_sys=1):
"""
if use_sys:
try:
- return sys.modules['.'.join(parts)]
+ return sys.modules[".".join(parts)]
except KeyError:
pass
modpath = []
prevmodule = None
for part in parts:
modpath.append(part)
- curname = '.'.join(modpath)
+ curname = ".".join(modpath)
module = None
if len(modpath) != len(parts):
# even with use_sys=False, should try to get outer packages from sys.modules
@@ -242,12 +248,12 @@ def load_module_from_modpath(parts, path=None, use_sys=1):
mp_file.close()
if prevmodule:
setattr(prevmodule, part, module)
- _file = getattr(module, '__file__', '')
+ _file = getattr(module, "__file__", "")
prevmodule = module
if not _file and util.is_namespace(curname):
continue
if not _file and len(modpath) != len(parts):
- raise ImportError('no module in %s' % '.'.join(parts[len(modpath):]))
+ raise ImportError("no module in %s" % ".".join(parts[len(modpath) :]))
path = [os.path.dirname(_file)]
return module
@@ -285,7 +291,7 @@ def check_modpath_has_init(path, mod_path):
modpath.append(part)
path = os.path.join(path, part)
if not _has_init(path):
- old_namespace = util.is_namespace('.'.join(modpath))
+ old_namespace = util.is_namespace(".".join(modpath))
if not old_namespace:
return False
return True
@@ -319,7 +325,7 @@ def _get_relative_base_path(filename, path_to_check):
if importable_path:
base_path = os.path.splitext(importable_path)[0]
- relative_base_path = base_path[len(path_to_check):]
+ relative_base_path = base_path[len(path_to_check) :]
return [pkg for pkg in relative_base_path.split(os.sep) if pkg]
return None
@@ -329,8 +335,7 @@ def modpath_from_file_with_callback(filename, extrapath=None, is_package_cb=None
filename = os.path.expanduser(_path_from_filename(filename))
if extrapath is not None:
- for path_ in itertools.chain(map(_canonicalize_path, extrapath),
- extrapath):
+ for path_ in itertools.chain(map(_canonicalize_path, extrapath), extrapath):
path = os.path.abspath(path_)
if not path:
continue
@@ -338,7 +343,7 @@ def modpath_from_file_with_callback(filename, extrapath=None, is_package_cb=None
if not submodpath:
continue
if is_package_cb(path, submodpath[:-1]):
- return extrapath[path_].split('.') + submodpath
+ return extrapath[path_].split(".") + submodpath
for path in itertools.chain(map(_canonicalize_path, sys.path), sys.path):
path = _cache_normalize_path(path)
@@ -350,9 +355,9 @@ def modpath_from_file_with_callback(filename, extrapath=None, is_package_cb=None
if is_package_cb(path, modpath[:-1]):
return modpath
- raise ImportError('Unable to find module for %s in %s' % (
- filename, ', \n'.join(sys.path)))
-
+ raise ImportError(
+ "Unable to find module for %s in %s" % (filename, ", \n".join(sys.path))
+ )
def modpath_from_file(filename, extrapath=None):
@@ -381,6 +386,7 @@ def modpath_from_file(filename, extrapath=None):
def file_from_modpath(modpath, path=None, context_file=None):
return file_info_from_modpath(modpath, path, context_file).location
+
def file_info_from_modpath(modpath, path=None, context_file=None):
"""given a mod path (i.e. split module / package name), return the
corresponding file, giving priority to source file over precompiled
@@ -415,15 +421,17 @@ def file_info_from_modpath(modpath, path=None, context_file=None):
context = os.path.dirname(context_file)
else:
context = context_file
- if modpath[0] == 'xml':
+ if modpath[0] == "xml":
# handle _xmlplus
try:
- return _spec_from_modpath(['_xmlplus'] + modpath[1:], path, context)
+ return _spec_from_modpath(["_xmlplus"] + modpath[1:], path, context)
except ImportError:
return _spec_from_modpath(modpath, path, context)
- elif modpath == ['os', 'path']:
+ elif modpath == ["os", "path"]:
# FIXME: currently ignoring search_path...
- return spec.ModuleSpec(name='os.path', location=os.path.__file__, module_type=imp.PY_SOURCE)
+ return spec.ModuleSpec(
+ name="os.path", location=os.path.__file__, module_type=imp.PY_SOURCE
+ )
return _spec_from_modpath(modpath, path, context)
@@ -454,9 +462,9 @@ def get_module_part(dotted_name, context_file=None):
(see #10066)
"""
# os.path trick
- if dotted_name.startswith('os.path'):
- return 'os.path'
- parts = dotted_name.split('.')
+ if dotted_name.startswith("os.path"):
+ return "os.path"
+ parts = dotted_name.split(".")
if context_file is not None:
# first check for builtin module which won't be considered latter
# in that case (path != None)
@@ -467,22 +475,24 @@ def get_module_part(dotted_name, context_file=None):
# don't use += or insert, we want a new list to be created !
path = None
starti = 0
- if parts[0] == '':
- assert context_file is not None, \
- 'explicit relative import, but no context_file?'
- path = [] # prevent resolving the import non-relatively
+ if parts[0] == "":
+ assert (
+ context_file is not None
+ ), "explicit relative import, but no context_file?"
+ path = [] # prevent resolving the import non-relatively
starti = 1
- while parts[starti] == '': # for all further dots: change context
+ while parts[starti] == "": # for all further dots: change context
starti += 1
context_file = os.path.dirname(context_file)
for i in range(starti, len(parts)):
try:
- file_from_modpath(parts[starti:i+1], path=path,
- context_file=context_file)
+ file_from_modpath(
+ parts[starti : i + 1], path=path, context_file=context_file
+ )
except ImportError:
if i < max(1, len(parts) - 2):
raise
- return '.'.join(parts[:i])
+ return ".".join(parts[:i])
return dotted_name
@@ -513,7 +523,7 @@ def get_module_files(src_directory, blacklist, list_all=False):
continue
_handle_blacklist(blacklist, dirnames, filenames)
# check for __init__.py
- if not list_all and '__init__.py' not in filenames:
+ if not list_all and "__init__.py" not in filenames:
dirnames[:] = ()
continue
for filename in filenames:
@@ -540,7 +550,7 @@ def get_source_file(filename, include_no_ext=False):
filename = os.path.abspath(_path_from_filename(filename))
base, orig_ext = os.path.splitext(filename)
for ext in PY_SOURCE_EXTS:
- source_path = '%s.%s' % (base, ext)
+ source_path = "%s.%s" % (base, ext)
if os.path.exists(source_path):
return source_path
if include_no_ext and not orig_ext and os.path.exists(base):
@@ -573,7 +583,7 @@ def is_standard_module(modname, std_path=None):
- is located on the path listed in one of the directory in `std_path`
- is a built-in module
"""
- modname = modname.split('.')[0]
+ modname = modname.split(".")[0]
try:
filename = file_from_modpath([modname])
except ImportError:
@@ -596,7 +606,6 @@ def is_standard_module(modname, std_path=None):
return False
-
def is_relative(modname, from_file):
"""return true if the given module name is relative to the given
file name
@@ -617,7 +626,7 @@ def is_relative(modname, from_file):
if from_file in sys.path:
return False
try:
- stream, _, _ = imp.find_module(modname.split('.')[0], [from_file])
+ stream, _, _ = imp.find_module(modname.split(".")[0], [from_file])
# Close the stream to avoid ResourceWarnings.
if stream:
@@ -629,6 +638,7 @@ def is_relative(modname, from_file):
# internal only functions #####################################################
+
def _spec_from_modpath(modpath, path=None, context=None):
"""given a mod path (i.e. split module / package name), return the
corresponding spec
@@ -650,7 +660,9 @@ def _spec_from_modpath(modpath, path=None, context=None):
if found_spec.type == spec.ModuleType.PY_COMPILED:
try:
location = get_source_file(found_spec.location)
- return found_spec._replace(location=location, type=spec.ModuleType.PY_SOURCE)
+ return found_spec._replace(
+ location=location, type=spec.ModuleType.PY_SOURCE
+ )
except NoSourceFile:
return found_spec._replace(location=location)
elif found_spec.type == spec.ModuleType.C_BUILTIN:
@@ -667,7 +679,7 @@ def _is_python_file(filename):
.pyc and .pyo are ignored
"""
- for ext in ('.py', '.so', '.pyd', '.pyw'):
+ for ext in (".py", ".so", ".pyd", ".pyw"):
if filename.endswith(ext):
return True
return False
@@ -677,15 +689,16 @@ def _has_init(directory):
"""if the given directory has a valid __init__ file, return its path,
else return None
"""
- mod_or_pack = os.path.join(directory, '__init__')
- for ext in PY_SOURCE_EXTS + ('pyc', 'pyo'):
- if os.path.exists(mod_or_pack + '.' + ext):
- return mod_or_pack + '.' + ext
+ mod_or_pack = os.path.join(directory, "__init__")
+ for ext in PY_SOURCE_EXTS + ("pyc", "pyo"):
+ if os.path.exists(mod_or_pack + "." + ext):
+ return mod_or_pack + "." + ext
return None
def is_namespace(specobj):
return specobj.type == spec.ModuleType.PY_NAMESPACE
+
def is_directory(specobj):
return specobj.type == spec.ModuleType.PKG_DIRECTORY
diff --git a/astroid/node_classes.py b/astroid/node_classes.py
index ba0f301b..8247b0e2 100644
--- a/astroid/node_classes.py
+++ b/astroid/node_classes.py
@@ -74,7 +74,9 @@ def unpack_infer(stmt, context=None):
return dict(node=stmt, context=context)
-def are_exclusive(stmt1, stmt2, exceptions=None): # pylint: disable=redefined-outer-name
+def are_exclusive(
+ stmt1, stmt2, exceptions=None
+): # pylint: disable=redefined-outer-name
"""return true if the two given statements are mutually exclusive
`exceptions` may be a list of exception names. If specified, discard If
@@ -105,31 +107,41 @@ def are_exclusive(stmt1, stmt2, exceptions=None): # pylint: disable=redefined-ou
# if the common parent is a If or TryExcept statement, look if
# nodes are in exclusive branches
if isinstance(node, If) and exceptions is None:
- if (node.locate_child(previous)[1]
- is not node.locate_child(children[node])[1]):
+ if (
+ node.locate_child(previous)[1]
+ is not node.locate_child(children[node])[1]
+ ):
return True
elif isinstance(node, TryExcept):
c2attr, c2node = node.locate_child(previous)
c1attr, c1node = node.locate_child(children[node])
if c1node is not c2node:
first_in_body_caught_by_handlers = (
- c2attr == 'handlers'
- and c1attr == 'body'
- and previous.catch(exceptions))
+ c2attr == "handlers"
+ and c1attr == "body"
+ and previous.catch(exceptions)
+ )
second_in_body_caught_by_handlers = (
- c2attr == 'body'
- and c1attr == 'handlers'
- and children[node].catch(exceptions))
+ c2attr == "body"
+ and c1attr == "handlers"
+ and children[node].catch(exceptions)
+ )
first_in_else_other_in_handlers = (
- c2attr == 'handlers' and c1attr == 'orelse')
+ c2attr == "handlers" and c1attr == "orelse"
+ )
second_in_else_other_in_handlers = (
- c2attr == 'orelse' and c1attr == 'handlers')
- if any((first_in_body_caught_by_handlers,
+ c2attr == "orelse" and c1attr == "handlers"
+ )
+ if any(
+ (
+ first_in_body_caught_by_handlers,
second_in_body_caught_by_handlers,
first_in_else_other_in_handlers,
- second_in_else_other_in_handlers)):
+ second_in_else_other_in_handlers,
+ )
+ ):
return True
- elif c2attr == 'handlers' and c1attr == 'handlers':
+ elif c2attr == "handlers" and c1attr == "handlers":
return previous is not children[node]
return False
previous = node
@@ -177,8 +189,11 @@ def _infer_slice(node, context=None):
return slice(lower, upper, step)
raise exceptions.AstroidTypeError(
- message='Could not infer slice used in subscript',
- node=node, index=node.parent, context=context)
+ message="Could not infer slice used in subscript",
+ node=node,
+ index=node.parent,
+ context=context,
+ )
def _container_getitem(instance, elts, index, context=None):
@@ -194,35 +209,41 @@ def _container_getitem(instance, elts, index, context=None):
return elts[index.value]
except IndexError as exc:
raise exceptions.AstroidIndexError(
- message='Index {index!s} out of range',
- node=instance, index=index, context=context) from exc
+ message="Index {index!s} out of range",
+ node=instance,
+ index=index,
+ context=context,
+ ) from exc
except TypeError as exc:
raise exceptions.AstroidTypeError(
- message='Type error {error!r}',
- node=instance, index=index, context=context) from exc
+ message="Type error {error!r}", node=instance, index=index, context=context
+ ) from exc
- raise exceptions.AstroidTypeError('Could not use %s as subscript index' % index)
+ raise exceptions.AstroidTypeError("Could not use %s as subscript index" % index)
OP_PRECEDENCE = {
op: precedence
- for precedence, ops in enumerate([
- ['Lambda'], # lambda x: x + 1
- ['IfExp'], # 1 if True else 2
- ['or'],
- ['and'],
- ['not'],
- ['Compare'], # in, not in, is, is not, <, <=, >, >=, !=, ==
- ['|'],
- ['^'],
- ['&'],
- ['<<', '>>'],
- ['+', '-'],
- ['*', '@', '/', '//', '%'],
- ['UnaryOp'], # +, -, ~
- ['**'],
- ['Await'],
- ]) for op in ops
+ for precedence, ops in enumerate(
+ [
+ ["Lambda"], # lambda x: x + 1
+ ["IfExp"], # 1 if True else 2
+ ["or"],
+ ["and"],
+ ["not"],
+ ["Compare"], # in, not in, is, is not, <, <=, >, >=, !=, ==
+ ["|"],
+ ["^"],
+ ["&"],
+ ["<<", ">>"],
+ ["+", "-"],
+ ["*", "@", "/", "//", "%"],
+ ["UnaryOp"], # +, -, ~
+ ["**"],
+ ["Await"],
+ ]
+ )
+ for op in ops
}
@@ -231,12 +252,13 @@ class NodeNG:
This is the base class for all Astroid node classes.
"""
+
is_statement = False
"""Whether this node indicates a statement.
:type: bool
"""
- optional_assign = False # True for For (and for Comprehension if py <3.0)
+ optional_assign = False # True for For (and for Comprehension if py <3.0)
"""Whether this node optionally assigns a variable.
This is for loop assignments because loop won't necessarily perform an
@@ -245,7 +267,7 @@ class NodeNG:
:type: bool
"""
- is_function = False # True for FunctionDef nodes
+ is_function = False # True for FunctionDef nodes
"""Whether this node indicates a function.
:type: bool
@@ -329,13 +351,11 @@ class NodeNG:
if not context:
return self._infer(context, **kwargs)
- key = (self, context.lookupname,
- context.callcontext, context.boundnode)
+ key = (self, context.lookupname, context.callcontext, context.boundnode)
if key in context.inferred:
return iter(context.inferred[key])
- gen = context.cache_generator(
- key, self._infer(context, **kwargs))
+ gen = context.cache_generator(key, self._infer(context, **kwargs))
return util.limit_inference(gen, MANAGER.max_inferable_values)
def _repr_name(self):
@@ -346,46 +366,49 @@ class NodeNG:
:returns: The nice name.
:rtype: str
"""
- names = {'name', 'attrname'}
+ names = {"name", "attrname"}
if all(name not in self._astroid_fields for name in names):
- return getattr(self, 'name', getattr(self, 'attrname', ''))
- return ''
+ return getattr(self, "name", getattr(self, "attrname", ""))
+ return ""
def __str__(self):
rname = self._repr_name()
cname = type(self).__name__
if rname:
- string = '%(cname)s.%(rname)s(%(fields)s)'
+ string = "%(cname)s.%(rname)s(%(fields)s)"
alignment = len(cname) + len(rname) + 2
else:
- string = '%(cname)s(%(fields)s)'
+ string = "%(cname)s(%(fields)s)"
alignment = len(cname) + 1
result = []
for field in self._other_fields + self._astroid_fields:
value = getattr(self, field)
width = 80 - len(field) - alignment
- lines = pprint.pformat(value, indent=2,
- width=width).splitlines(True)
+ lines = pprint.pformat(value, indent=2, width=width).splitlines(True)
inner = [lines[0]]
for line in lines[1:]:
- inner.append(' ' * alignment + line)
- result.append('%s=%s' % (field, ''.join(inner)))
+ inner.append(" " * alignment + line)
+ result.append("%s=%s" % (field, "".join(inner)))
- return string % {'cname': cname,
- 'rname': rname,
- 'fields': (',\n' + ' ' * alignment).join(result)}
+ return string % {
+ "cname": cname,
+ "rname": rname,
+ "fields": (",\n" + " " * alignment).join(result),
+ }
def __repr__(self):
rname = self._repr_name()
if rname:
- string = '<%(cname)s.%(rname)s l.%(lineno)s at 0x%(id)x>'
+ string = "<%(cname)s.%(rname)s l.%(lineno)s at 0x%(id)x>"
else:
- string = '<%(cname)s l.%(lineno)s at 0x%(id)x>'
- return string % {'cname': type(self).__name__,
- 'rname': rname,
- 'lineno': self.fromlineno,
- 'id': id(self)}
+ string = "<%(cname)s l.%(lineno)s at 0x%(id)x>"
+ return string % {
+ "cname": type(self).__name__,
+ "rname": rname,
+ "lineno": self.fromlineno,
+ "id": id(self),
+ }
def accept(self, visitor):
"""Visit this node using the given visitor."""
@@ -415,7 +438,7 @@ class NodeNG:
"""
for field in self._astroid_fields[::-1]:
attr = getattr(self, field)
- if not attr: # None or empty listy / tuple
+ if not attr: # None or empty listy / tuple
continue
if isinstance(attr, (list, tuple)):
return attr[-1]
@@ -496,11 +519,13 @@ class NodeNG:
if node_or_sequence is child:
return [node_or_sequence]
# /!\ compiler.ast Nodes have an __iter__ walking over child nodes
- if (isinstance(node_or_sequence, (tuple, list))
- and child in node_or_sequence):
+ if (
+ isinstance(node_or_sequence, (tuple, list))
+ and child in node_or_sequence
+ ):
return node_or_sequence
- msg = 'Could not find %s in %s\'s children'
+ msg = "Could not find %s in %s's children"
raise exceptions.AstroidError(msg % (repr(child), repr(self)))
def locate_child(self, child):
@@ -521,10 +546,14 @@ class NodeNG:
# /!\ compiler.ast Nodes have an __iter__ walking over child nodes
if child is node_or_sequence:
return field, child
- if isinstance(node_or_sequence, (tuple, list)) and child in node_or_sequence:
+ if (
+ isinstance(node_or_sequence, (tuple, list))
+ and child in node_or_sequence
+ ):
return field, node_or_sequence
- msg = 'Could not find %s in %s\'s children'
+ msg = "Could not find %s in %s's children"
raise exceptions.AstroidError(msg % (repr(child), repr(self)))
+
# FIXME : should we merge child_sequence and locate_child ? locate_child
# is only used in are_exclusive, child_sequence one time in pylint.
@@ -560,8 +589,9 @@ class NodeNG:
mylineno = self.fromlineno
nearest = None, 0
for node in nodes:
- assert node.root() is myroot, \
- 'nodes %s and %s are not from the same module' % (self, node)
+ assert node.root() is myroot, (
+ "nodes %s and %s are not from the same module" % (self, node)
+ )
lineno = node.fromlineno
if node.fromlineno > mylineno:
break
@@ -696,8 +726,9 @@ class NodeNG:
def _infer(self, context=None):
"""we don't know how to resolve a statement by default"""
# this method is overridden by most concrete classes
- raise exceptions.InferenceError('No inference function for {node!r}.',
- node=self, context=context)
+ raise exceptions.InferenceError(
+ "No inference function for {node!r}.", node=self, context=context
+ )
def inferred(self):
"""Get a list of the inferred values.
@@ -750,8 +781,15 @@ class NodeNG:
"""
return as_string.to_code(self)
- def repr_tree(self, ids=False, include_linenos=False,
- ast_state=False, indent=' ', max_depth=0, max_width=80):
+ def repr_tree(
+ self,
+ ids=False,
+ include_linenos=False,
+ ast_state=False,
+ indent=" ",
+ max_depth=0,
+ max_width=80,
+ ):
"""Get a string representation of the AST from this node.
:param ids: If true, includes the ids with the node type names.
@@ -782,13 +820,13 @@ class NodeNG:
"""
# pylint: disable=too-many-statements
@_singledispatch
- def _repr_tree(node, result, done, cur_indent='', depth=1):
+ def _repr_tree(node, result, done, cur_indent="", depth=1):
"""Outputs a representation of a non-tuple/list, non-node that's
contained within an AST, including strings.
"""
- lines = pprint.pformat(node,
- width=max(max_width - len(cur_indent),
- 1)).splitlines(True)
+ lines = pprint.pformat(
+ node, width=max(max_width - len(cur_indent), 1)
+ ).splitlines(True)
result.append(lines[0])
result.extend([cur_indent + line for line in lines[1:]])
return len(lines) != 1
@@ -796,10 +834,10 @@ class NodeNG:
# pylint: disable=unused-variable; doesn't understand singledispatch
@_repr_tree.register(tuple)
@_repr_tree.register(list)
- def _repr_seq(node, result, done, cur_indent='', depth=1):
+ def _repr_seq(node, result, done, cur_indent="", depth=1):
"""Outputs a representation of a sequence that's contained within an AST."""
cur_indent += indent
- result.append('[')
+ result.append("[")
if not node:
broken = False
elif len(node) == 1:
@@ -807,46 +845,47 @@ class NodeNG:
elif len(node) == 2:
broken = _repr_tree(node[0], result, done, cur_indent, depth)
if not broken:
- result.append(', ')
+ result.append(", ")
else:
- result.append(',\n')
+ result.append(",\n")
result.append(cur_indent)
- broken = (_repr_tree(node[1], result, done, cur_indent, depth)
- or broken)
+ broken = _repr_tree(node[1], result, done, cur_indent, depth) or broken
else:
- result.append('\n')
+ result.append("\n")
result.append(cur_indent)
for child in node[:-1]:
_repr_tree(child, result, done, cur_indent, depth)
- result.append(',\n')
+ result.append(",\n")
result.append(cur_indent)
_repr_tree(node[-1], result, done, cur_indent, depth)
broken = True
- result.append(']')
+ result.append("]")
return broken
# pylint: disable=unused-variable; doesn't understand singledispatch
@_repr_tree.register(NodeNG)
- def _repr_node(node, result, done, cur_indent='', depth=1):
+ def _repr_node(node, result, done, cur_indent="", depth=1):
"""Outputs a strings representation of an astroid node."""
if node in done:
- result.append(indent + '<Recursion on %s with id=%s' %
- (type(node).__name__, id(node)))
+ result.append(
+ indent
+ + "<Recursion on %s with id=%s" % (type(node).__name__, id(node))
+ )
return False
done.add(node)
if max_depth and depth > max_depth:
- result.append('...')
+ result.append("...")
return False
depth += 1
cur_indent += indent
if ids:
- result.append('%s<0x%x>(\n' % (type(node).__name__, id(node)))
+ result.append("%s<0x%x>(\n" % (type(node).__name__, id(node)))
else:
- result.append('%s(' % type(node).__name__)
+ result.append("%s(" % type(node).__name__)
fields = []
if include_linenos:
- fields.extend(('lineno', 'col_offset'))
+ fields.extend(("lineno", "col_offset"))
fields.extend(node._other_fields)
fields.extend(node._astroid_fields)
if ast_state:
@@ -854,28 +893,27 @@ class NodeNG:
if not fields:
broken = False
elif len(fields) == 1:
- result.append('%s=' % fields[0])
- broken = _repr_tree(getattr(node, fields[0]), result, done,
- cur_indent, depth)
+ result.append("%s=" % fields[0])
+ broken = _repr_tree(
+ getattr(node, fields[0]), result, done, cur_indent, depth
+ )
else:
- result.append('\n')
+ result.append("\n")
result.append(cur_indent)
for field in fields[:-1]:
- result.append('%s=' % field)
- _repr_tree(getattr(node, field), result, done, cur_indent,
- depth)
- result.append(',\n')
+ result.append("%s=" % field)
+ _repr_tree(getattr(node, field), result, done, cur_indent, depth)
+ result.append(",\n")
result.append(cur_indent)
- result.append('%s=' % fields[-1])
- _repr_tree(getattr(node, fields[-1]), result, done, cur_indent,
- depth)
+ result.append("%s=" % fields[-1])
+ _repr_tree(getattr(node, fields[-1]), result, done, cur_indent, depth)
broken = True
- result.append(')')
+ result.append(")")
return broken
result = []
_repr_tree(self, result, set())
- return ''.join(result)
+ return "".join(result)
def bool_value(self):
"""Determine the boolean value of this node.
@@ -899,8 +937,7 @@ class NodeNG:
def op_precedence(self):
# Look up by class name or default to highest precedence
- return OP_PRECEDENCE.get(
- self.__class__.__name__, len(OP_PRECEDENCE))
+ return OP_PRECEDENCE.get(self.__class__.__name__, len(OP_PRECEDENCE))
def op_left_associative(self):
# Everything is left associative except `**` and IfExp
@@ -909,6 +946,7 @@ class NodeNG:
class Statement(NodeNG):
"""Statement node adding a few attributes"""
+
is_statement = True
"""Whether this node indicates a statement.
@@ -924,7 +962,7 @@ class Statement(NodeNG):
stmts = self.parent.child_sequence(self)
index = stmts.index(self)
try:
- return stmts[index +1]
+ return stmts[index + 1]
except IndexError:
pass
@@ -937,16 +975,16 @@ class Statement(NodeNG):
stmts = self.parent.child_sequence(self)
index = stmts.index(self)
if index >= 1:
- return stmts[index -1]
+ return stmts[index - 1]
return None
-class _BaseContainer(mixins.ParentAssignTypeMixin,
- NodeNG, bases.Instance,
- metaclass=abc.ABCMeta):
+class _BaseContainer(
+ mixins.ParentAssignTypeMixin, NodeNG, bases.Instance, metaclass=abc.ABCMeta
+):
"""Base class for Set, FrozenSet, Tuple and List."""
- _astroid_fields = ('elts',)
+ _astroid_fields = ("elts",)
def __init__(self, lineno=None, col_offset=None, parent=None):
"""
@@ -1121,8 +1159,11 @@ class LookupMixIn:
# Fixes issue #375
if mystmt is stmt and is_from_decorator(self):
continue
- assert hasattr(node, 'assign_type'), (node, node.scope(),
- node.scope().locals)
+ assert hasattr(node, "assign_type"), (
+ node,
+ node.scope(),
+ node.scope().locals,
+ )
assign_type = node.assign_type()
if node.has_base(self):
break
@@ -1192,8 +1233,10 @@ class LookupMixIn:
# Name classes
-class AssignName(mixins.NoChildrenMixin, LookupMixIn,
- mixins.ParentAssignTypeMixin, NodeNG):
+
+class AssignName(
+ mixins.NoChildrenMixin, LookupMixIn, mixins.ParentAssignTypeMixin, NodeNG
+):
"""Variation of :class:`ast.Assign` representing assignment to a name.
An :class:`AssignName` is the name of something that is assigned to.
@@ -1207,7 +1250,8 @@ class AssignName(mixins.NoChildrenMixin, LookupMixIn,
>>> list(node.get_children())[0].as_string()
'variable'
"""
- _other_fields = ('name',)
+
+ _other_fields = ("name",)
def __init__(self, name=None, lineno=None, col_offset=None, parent=None):
"""
@@ -1233,8 +1277,9 @@ class AssignName(mixins.NoChildrenMixin, LookupMixIn,
super(AssignName, self).__init__(lineno, col_offset, parent)
-class DelName(mixins.NoChildrenMixin, LookupMixIn,
- mixins.ParentAssignTypeMixin, NodeNG):
+class DelName(
+ mixins.NoChildrenMixin, LookupMixIn, mixins.ParentAssignTypeMixin, NodeNG
+):
"""Variation of :class:`ast.Delete` representing deletion of a name.
A :class:`DelName` is the name of something that is deleted.
@@ -1245,7 +1290,8 @@ class DelName(mixins.NoChildrenMixin, LookupMixIn,
>>> list(node.get_children())[0].as_string()
'variable'
"""
- _other_fields = ('name',)
+
+ _other_fields = ("name",)
def __init__(self, name=None, lineno=None, col_offset=None, parent=None):
"""
@@ -1285,7 +1331,8 @@ class Name(mixins.NoChildrenMixin, LookupMixIn, NodeNG):
>>> list(node.get_children())[0].as_string()
'range'
"""
- _other_fields = ('name',)
+
+ _other_fields = ("name",)
def __init__(self, name=None, lineno=None, col_offset=None, parent=None):
"""
@@ -1329,6 +1376,7 @@ class Arguments(mixins.AssignTypeMixin, NodeNG):
>>> node.args
<Arguments l.1 at 0x7effe1db82e8>
"""
+
# Python 3.4+ uses a different approach regarding annotations,
# each argument is a new class, _ast.arg, which exposes an
# 'annotation' attribute. In astroid though, arguments are exposed
@@ -1340,9 +1388,16 @@ class Arguments(mixins.AssignTypeMixin, NodeNG):
# for each normal argument. If an argument doesn't have an
# annotation, its value will be None.
- _astroid_fields = ('args', 'defaults', 'kwonlyargs',
- 'kw_defaults', 'annotations', 'varargannotation',
- 'kwargannotation', 'kwonlyargs_annotations')
+ _astroid_fields = (
+ "args",
+ "defaults",
+ "kwonlyargs",
+ "kw_defaults",
+ "annotations",
+ "varargannotation",
+ "kwargannotation",
+ "kwonlyargs_annotations",
+ )
varargannotation = None
"""The type annotation for the variable length arguments.
@@ -1354,7 +1409,7 @@ class Arguments(mixins.AssignTypeMixin, NodeNG):
:type: NodeNG
"""
- _other_fields = ('vararg', 'kwarg')
+ _other_fields = ("vararg", "kwarg")
def __init__(self, vararg=None, kwarg=None, parent=None):
"""
@@ -1416,11 +1471,17 @@ class Arguments(mixins.AssignTypeMixin, NodeNG):
:type: list(NodeNG)
"""
- def postinit(self, args, defaults, kwonlyargs, kw_defaults,
- annotations,
- kwonlyargs_annotations=None,
- varargannotation=None,
- kwargannotation=None):
+ def postinit(
+ self,
+ args,
+ defaults,
+ kwonlyargs,
+ kw_defaults,
+ annotations,
+ kwonlyargs_annotations=None,
+ varargannotation=None,
+ kwargannotation=None,
+ ):
"""Do some setup after initialisation.
:param args: The names of the required arguments.
@@ -1487,22 +1548,23 @@ class Arguments(mixins.AssignTypeMixin, NodeNG):
result = []
if self.args:
result.append(
- _format_args(self.args, self.defaults,
- getattr(self, 'annotations', None))
+ _format_args(
+ self.args, self.defaults, getattr(self, "annotations", None)
+ )
)
if self.vararg:
- result.append('*%s' % self.vararg)
+ result.append("*%s" % self.vararg)
if self.kwonlyargs:
if not self.vararg:
- result.append('*')
- result.append(_format_args(
- self.kwonlyargs,
- self.kw_defaults,
- self.kwonlyargs_annotations
- ))
+ result.append("*")
+ result.append(
+ _format_args(
+ self.kwonlyargs, self.kw_defaults, self.kwonlyargs_annotations
+ )
+ )
if self.kwarg:
- result.append('**%s' % self.kwarg)
- return ', '.join(result)
+ result.append("**%s" % self.kwarg)
+ return ", ".join(result)
def default_value(self, argname):
"""Get the default value for an argument.
@@ -1537,8 +1599,11 @@ class Arguments(mixins.AssignTypeMixin, NodeNG):
return True
if name == self.kwarg:
return True
- return (self.find_argname(name, True)[1] is not None or
- self.kwonlyargs and _find_arg(name, self.kwonlyargs, True)[1] is not None)
+ return (
+ self.find_argname(name, True)[1] is not None
+ or self.kwonlyargs
+ and _find_arg(name, self.kwonlyargs, True)[1] is not None
+ )
def find_argname(self, argname, rec=False):
"""Get the index and :class:`AssignName` node for given name.
@@ -1553,7 +1618,7 @@ class Arguments(mixins.AssignTypeMixin, NodeNG):
:returns: The index and node for the argument.
:rtype: tuple(str or None, AssignName or None)
"""
- if self.args: # self.args may be None in some cases (builtin function)
+ if self.args: # self.args may be None in some cases (builtin function)
return _find_arg(argname, self.args, rec)
return None, None
@@ -1597,7 +1662,7 @@ def _find_arg(argname, args, rec=False):
def _format_args(args, defaults=None, annotations=None):
values = []
if args is None:
- return ''
+ return ""
if annotations is None:
annotations = []
if defaults is not None:
@@ -1605,17 +1670,17 @@ def _format_args(args, defaults=None, annotations=None):
packed = itertools.zip_longest(args, annotations)
for i, (arg, annotation) in enumerate(packed):
if isinstance(arg, Tuple):
- values.append('(%s)' % _format_args(arg.elts))
+ values.append("(%s)" % _format_args(arg.elts))
else:
argname = arg.name
if annotation is not None:
- argname += ':' + annotation.as_string()
+ argname += ":" + annotation.as_string()
values.append(argname)
if defaults is not None and i >= default_offset:
- if defaults[i-default_offset] is not None:
- values[-1] += '=' + defaults[i-default_offset].as_string()
- return ', '.join(values)
+ if defaults[i - default_offset] is not None:
+ values[-1] += "=" + defaults[i - default_offset].as_string()
+ return ", ".join(values)
class AssignAttr(mixins.ParentAssignTypeMixin, NodeNG):
@@ -1629,8 +1694,9 @@ class AssignAttr(mixins.ParentAssignTypeMixin, NodeNG):
>>> list(node.get_children())[0].as_string()
'self.attribute'
"""
- _astroid_fields = ('expr',)
- _other_fields = ('attrname',)
+
+ _astroid_fields = ("expr",)
+ _other_fields = ("attrname",)
expr = None
"""What has the attribute that is being assigned to.
@@ -1681,7 +1747,8 @@ class Assert(Statement):
>>> node
<Assert l.1 at 0x7effe1d527b8>
"""
- _astroid_fields = ('test', 'fail',)
+
+ _astroid_fields = ("test", "fail")
test = None
"""The test that passes or fails the assertion.
@@ -1722,8 +1789,9 @@ class Assign(mixins.AssignTypeMixin, Statement):
>>> node
<Assign l.1 at 0x7effe1db8550>
"""
- _astroid_fields = ('targets', 'value',)
- _other_other_fields = ('type_annotation',)
+
+ _astroid_fields = ("targets", "value")
+ _other_other_fields = ("type_annotation",)
targets = None
"""What is being assigned to.
@@ -1777,8 +1845,8 @@ class AnnAssign(mixins.AssignTypeMixin, Statement):
<AnnAssign l.1 at 0x7effe1d4c630>
"""
- _astroid_fields = ('target', 'annotation', 'value',)
- _other_fields = ('simple',)
+ _astroid_fields = ("target", "annotation", "value")
+ _other_fields = ("simple",)
target = None
"""What is being assigned to.
@@ -1838,8 +1906,9 @@ class AugAssign(mixins.AssignTypeMixin, Statement):
>>> node
<AugAssign l.1 at 0x7effe1db4d68>
"""
- _astroid_fields = ('target', 'value')
- _other_fields = ('op',)
+
+ _astroid_fields = ("target", "value")
+ _other_fields = ("op",)
target = None
"""What is being assigned to.
@@ -1904,8 +1973,11 @@ class AugAssign(mixins.AssignTypeMixin, Statement):
"""
try:
results = self._infer_augassign(context=context)
- return [result for result in results
- if isinstance(result, util.BadBinaryOperationMessage)]
+ return [
+ result
+ for result in results
+ if isinstance(result, util.BadBinaryOperationMessage)
+ ]
except exceptions.InferenceError:
return []
@@ -1924,7 +1996,8 @@ class Repr(NodeNG):
>>> node
<Repr l.1 at 0x7fa0951d75d0>
"""
- _astroid_fields = ('value',)
+
+ _astroid_fields = ("value",)
value = None
"""What is having :func:`repr` called on it.
@@ -1949,8 +2022,9 @@ class BinOp(NodeNG):
>>> node
<BinOp l.1 at 0x7f23b2e8cfd0>
"""
- _astroid_fields = ('left', 'right')
- _other_fields = ('op',)
+
+ _astroid_fields = ("left", "right")
+ _other_fields = ("op",)
left = None
"""What is being applied to the operator on the left side.
@@ -2012,8 +2086,11 @@ class BinOp(NodeNG):
"""
try:
results = self._infer_binop(context=context)
- return [result for result in results
- if isinstance(result, util.BadBinaryOperationMessage)]
+ return [
+ result
+ for result in results
+ if isinstance(result, util.BadBinaryOperationMessage)
+ ]
except exceptions.InferenceError:
return []
@@ -2026,7 +2103,7 @@ class BinOp(NodeNG):
def op_left_associative(self):
# 2**3**4 == 2**(3**4)
- return self.op != '**'
+ return self.op != "**"
class BoolOp(NodeNG):
@@ -2038,8 +2115,9 @@ class BoolOp(NodeNG):
>>> node
<BinOp l.1 at 0x7f23b2e71c50>
"""
- _astroid_fields = ('values',)
- _other_fields = ('op',)
+
+ _astroid_fields = ("values",)
+ _other_fields = ("op",)
values = None
"""The values being applied to the operator.
@@ -2102,7 +2180,8 @@ class Call(NodeNG):
>>> node
<Call l.1 at 0x7f23b2e71eb8>
"""
- _astroid_fields = ('func', 'args', 'keywords')
+
+ _astroid_fields = ("func", "args", "keywords")
func = None
"""What is being called.
@@ -2172,7 +2251,8 @@ class Compare(NodeNG):
>>> node.ops
[('<=', <Name.b l.1 at 0x7f23b2e9e2b0>), ('<=', <Name.c l.1 at 0x7f23b2e9e390>)]
"""
- _astroid_fields = ('left', 'ops',)
+
+ _astroid_fields = ("left", "ops")
left = None
"""The value at the left being applied to a comparison operator.
@@ -2209,7 +2289,7 @@ class Compare(NodeNG):
"""
yield self.left
for _, comparator in self.ops:
- yield comparator # we don't want the 'op'
+ yield comparator # we don't want the 'op'
def last_child(self):
"""An optimized version of list(get_children())[-1]
@@ -2219,7 +2299,7 @@ class Compare(NodeNG):
"""
# XXX maybe if self.ops:
return self.ops[-1][1]
- #return self.left
+ # return self.left
class Comprehension(NodeNG):
@@ -2234,8 +2314,9 @@ class Comprehension(NodeNG):
>>> list(node.get_children())[1].as_string()
'for x in some_values'
"""
- _astroid_fields = ('target', 'iter', 'ifs')
- _other_fields = ('is_async',)
+
+ _astroid_fields = ("target", "iter", "ifs")
+ _other_fields = ("is_async",)
target = None
"""What is assigned to by the comprehension.
@@ -2292,6 +2373,7 @@ class Comprehension(NodeNG):
:type: bool
"""
+
def assign_type(self):
"""The type of assignment that this node performs.
@@ -2334,7 +2416,8 @@ class Const(mixins.NoChildrenMixin, NodeNG, bases.Instance):
<Const.NoneType l.1 at 0x7f23b2e359e8>,
<Const.bytes l.1 at 0x7f23b2e35a20>]
"""
- _other_fields = ('value',)
+
+ _other_fields = ("value",)
def __init__(self, value, lineno=None, col_offset=None, parent=None):
"""
@@ -2386,7 +2469,7 @@ class Const(mixins.NoChildrenMixin, NodeNG, bases.Instance):
else:
raise exceptions.AstroidTypeError(
- 'Could not use type {} as subscript index'.format(type(index))
+ "Could not use type {} as subscript index".format(type(index))
)
try:
@@ -2394,16 +2477,17 @@ class Const(mixins.NoChildrenMixin, NodeNG, bases.Instance):
return Const(self.value[index_value])
except IndexError as exc:
raise exceptions.AstroidIndexError(
- message='Index {index!r} out of range',
- node=self, index=index, context=context) from exc
+ message="Index {index!r} out of range",
+ node=self,
+ index=index,
+ context=context,
+ ) from exc
except TypeError as exc:
raise exceptions.AstroidTypeError(
- message='Type error {error!r}',
- node=self, index=index, context=context) from exc
+ message="Type error {error!r}", node=self, index=index, context=context
+ ) from exc
- raise exceptions.AstroidTypeError(
- '%r (value=%s)' % (self, self.value)
- )
+ raise exceptions.AstroidTypeError("%r (value=%s)" % (self, self.value))
def has_dynamic_getattr(self):
"""Check if the node has a custom __getattr__ or __getattribute__.
@@ -2469,7 +2553,8 @@ class Decorators(NodeNG):
>>> list(node.get_children())[0]
<Decorators l.1 at 0x7f23b2e35d68>
"""
- _astroid_fields = ('nodes',)
+
+ _astroid_fields = ("nodes",)
nodes = None
"""The decorators that this node contains.
@@ -2506,8 +2591,9 @@ class DelAttr(mixins.ParentAssignTypeMixin, NodeNG):
>>> list(node.get_children())[0]
<DelAttr.attr l.1 at 0x7f23b2e411d0>
"""
- _astroid_fields = ('expr',)
- _other_fields = ('attrname',)
+
+ _astroid_fields = ("expr",)
+ _other_fields = ("attrname",)
expr = None
"""The name that this node represents.
@@ -2558,7 +2644,8 @@ class Delete(mixins.AssignTypeMixin, Statement):
>>> node
<Delete l.1 at 0x7f23b2e35f60>
"""
- _astroid_fields = ('targets',)
+
+ _astroid_fields = ("targets",)
targets = None
"""What is being deleted.
@@ -2586,7 +2673,8 @@ class Dict(NodeNG, bases.Instance):
>>> node
<Dict.dict l.1 at 0x7f23b2e35cc0>
"""
- _astroid_fields = ('items',)
+
+ _astroid_fields = ("items",)
def __init__(self, lineno=None, col_offset=None, parent=None):
"""
@@ -2630,8 +2718,9 @@ class Dict(NodeNG, bases.Instance):
if items is None:
node.items = []
else:
- node.items = [(const_factory(k), const_factory(v))
- for k, v in items.items()]
+ node.items = [
+ (const_factory(k), const_factory(v)) for k, v in items.items()
+ ]
return node
def pytype(self):
@@ -2640,7 +2729,7 @@ class Dict(NodeNG, bases.Instance):
:returns: The name of the type.
:rtype: str
"""
- return '%s.dict' % BUILTINS
+ return "%s.dict" % BUILTINS
def get_children(self):
"""Get the key and value nodes below this node.
@@ -2721,7 +2810,8 @@ class Expr(Statement):
>>> node.parent
<Expr l.1 at 0x7f23b2e35278>
"""
- _astroid_fields = ('value',)
+
+ _astroid_fields = ("value",)
value = None
"""What the expression does.
@@ -2744,7 +2834,7 @@ class Expr(Statement):
yield from self.value._get_yield_nodes_skip_lambdas()
-class Ellipsis(mixins.NoChildrenMixin, NodeNG): # pylint: disable=redefined-builtin
+class Ellipsis(mixins.NoChildrenMixin, NodeNG): # pylint: disable=redefined-builtin
"""Class representing an :class:`ast.Ellipsis` node.
An :class:`Ellipsis` is the ``...`` syntax.
@@ -2770,8 +2860,7 @@ class EmptyNode(mixins.NoChildrenMixin, NodeNG):
object = None
-class ExceptHandler(mixins.MultiLineBlockMixin,
- mixins.AssignTypeMixin, Statement):
+class ExceptHandler(mixins.MultiLineBlockMixin, mixins.AssignTypeMixin, Statement):
"""Class representing an :class:`ast.ExceptHandler`. node.
An :class:`ExceptHandler` is an ``except`` block on a try-except.
@@ -2787,8 +2876,9 @@ class ExceptHandler(mixins.MultiLineBlockMixin,
>>> >>> node.handlers
[<ExceptHandler l.4 at 0x7f23b2e9e860>]
"""
- _astroid_fields = ('type', 'name', 'body',)
- _multi_line_block_fields = ('body',)
+
+ _astroid_fields = ("type", "name", "body")
+ _multi_line_block_fields = ("body",)
type = None
"""The types that the block handles.
@@ -2843,7 +2933,7 @@ class ExceptHandler(mixins.MultiLineBlockMixin,
return self.type.tolineno
return self.lineno
- def catch(self, exceptions): # pylint: disable=redefined-outer-name
+ def catch(self, exceptions): # pylint: disable=redefined-outer-name
"""Check if this node handles any of the given exceptions.
If ``exceptions`` is empty, this will default to ``True``.
@@ -2866,7 +2956,8 @@ class Exec(Statement):
>>> node
<Exec l.1 at 0x7f0e8106c6d0>
"""
- _astroid_fields = ('expr', 'globals', 'locals',)
+
+ _astroid_fields = ("expr", "globals", "locals")
expr = None
"""The expression to be executed.
@@ -2912,7 +3003,8 @@ class ExtSlice(NodeNG):
>>> node.slice
<ExtSlice l.1 at 0x7f23b7b05ef0>
"""
- _astroid_fields = ('dims',)
+
+ _astroid_fields = ("dims",)
dims = None
"""The simple dimensions that form the complete slice.
@@ -2928,17 +3020,22 @@ class ExtSlice(NodeNG):
self.dims = dims
-class For(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn,
- mixins.AssignTypeMixin, Statement):
+class For(
+ mixins.MultiLineBlockMixin,
+ mixins.BlockRangeMixIn,
+ mixins.AssignTypeMixin,
+ Statement,
+):
"""Class representing an :class:`ast.For` node.
>>> node = astroid.extract_node('for thing in things: print(thing)')
>>> node
<For l.1 at 0x7f23b2e8cf28>
"""
- _astroid_fields = ('target', 'iter', 'body', 'orelse',)
- _other_other_fields = ('type_annotation',)
- _multi_line_block_fields = ('body', 'orelse')
+
+ _astroid_fields = ("target", "iter", "body", "orelse")
+ _other_other_fields = ("type_annotation",)
+ _multi_line_block_fields = ("body", "orelse")
target = None
"""What the loop assigns to.
@@ -2966,7 +3063,9 @@ class For(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn,
"""
# pylint: disable=redefined-builtin; had to use the same name as builtin ast module.
- def postinit(self, target=None, iter=None, body=None, orelse=None, type_annotation=None):
+ def postinit(
+ self, target=None, iter=None, body=None, orelse=None, type_annotation=None
+ ):
"""Do some setup after initialisation.
:param target: What the loop assigns to.
@@ -3046,7 +3145,7 @@ class Await(NodeNG):
<Await l.3 at 0x7f23b2e41a20>
"""
- _astroid_fields = ('value', )
+ _astroid_fields = ("value",)
value = None
"""What to wait for.
@@ -3072,10 +3171,12 @@ class ImportFrom(mixins.NoChildrenMixin, mixins.ImportFromMixin, Statement):
>>> node
<ImportFrom l.1 at 0x7f23b2e415c0>
"""
- _other_fields = ('modname', 'names', 'level')
- def __init__(self, fromname, names, level=0, lineno=None,
- col_offset=None, parent=None):
+ _other_fields = ("modname", "names", "level")
+
+ def __init__(
+ self, fromname, names, level=0, lineno=None, col_offset=None, parent=None
+ ):
"""
:param fromname: The module that is being imported from.
:type fromname: str or None
@@ -3127,8 +3228,9 @@ class ImportFrom(mixins.NoChildrenMixin, mixins.ImportFromMixin, Statement):
class Attribute(NodeNG):
"""Class representing an :class:`ast.Attribute` node."""
- _astroid_fields = ('expr',)
- _other_fields = ('attrname',)
+
+ _astroid_fields = ("expr",)
+ _other_fields = ("attrname",)
expr = None
"""The name that this node represents.
@@ -3177,7 +3279,8 @@ class Global(mixins.NoChildrenMixin, Statement):
>>> node
<Global l.1 at 0x7f23b2e9de10>
"""
- _other_fields = ('names',)
+
+ _other_fields = ("names",)
def __init__(self, names, lineno=None, col_offset=None, parent=None):
"""
@@ -3213,8 +3316,9 @@ class If(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement):
>>> node
<If l.1 at 0x7f23b2e9dd30>
"""
- _astroid_fields = ('test', 'body', 'orelse')
- _multi_line_block_fields = ('body', 'orelse')
+
+ _astroid_fields = ("test", "body", "orelse")
+ _multi_line_block_fields = ("body", "orelse")
test = None
"""The condition that the statement tests.
@@ -3269,8 +3373,7 @@ class If(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement):
return lineno, lineno
if lineno <= self.body[-1].tolineno:
return lineno, self.body[-1].tolineno
- return self._elsed_block_range(lineno, self.orelse,
- self.body[0].fromlineno - 1)
+ return self._elsed_block_range(lineno, self.orelse, self.body[0].fromlineno - 1)
def get_children(self):
yield self.test
@@ -3281,6 +3384,7 @@ class If(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement):
def has_elif_block(self):
return len(self.orelse) == 1 and isinstance(self.orelse[0], If)
+
class IfExp(NodeNG):
"""Class representing an :class:`ast.IfExp` node.
@@ -3288,7 +3392,8 @@ class IfExp(NodeNG):
>>> node
<IfExp l.1 at 0x7f23b2e9dbe0>
"""
- _astroid_fields = ('test', 'body', 'orelse')
+
+ _astroid_fields = ("test", "body", "orelse")
test = None
"""The condition that the statement tests.
@@ -3339,7 +3444,8 @@ class Import(mixins.NoChildrenMixin, mixins.ImportFromMixin, Statement):
>>> node
<Import l.1 at 0x7f23b2e4e5c0>
"""
- _other_fields = ('names',)
+
+ _other_fields = ("names",)
def __init__(self, names=None, lineno=None, col_offset=None, parent=None):
"""
@@ -3379,7 +3485,8 @@ class Index(NodeNG):
>>> node.slice
<Index l.1 at 0x7f23b2e9e6a0>
"""
- _astroid_fields = ('value',)
+
+ _astroid_fields = ("value",)
value = None
"""The value to subscript with.
@@ -3407,8 +3514,9 @@ class Keyword(NodeNG):
>>> node.keywords
[<Keyword l.1 at 0x7f23b2e9e9b0>]
"""
- _astroid_fields = ('value',)
- _other_fields = ('arg',)
+
+ _astroid_fields = ("value",)
+ _other_fields = ("arg",)
value = None
"""The value being assigned to the keyword argument.
@@ -3457,10 +3565,10 @@ class List(_BaseContainer):
>>> node
<List.list l.1 at 0x7f23b2e9e128>
"""
- _other_fields = ('ctx',)
- def __init__(self, ctx=None, lineno=None,
- col_offset=None, parent=None):
+ _other_fields = ("ctx",)
+
+ def __init__(self, ctx=None, lineno=None, col_offset=None, parent=None):
"""
:param ctx: Whether the list is assigned to or loaded from.
:type ctx: Context or None
@@ -3489,7 +3597,7 @@ class List(_BaseContainer):
:returns: The name of the type.
:rtype: str
"""
- return '%s.list' % BUILTINS
+ return "%s.list" % BUILTINS
def getitem(self, index, context=None):
"""Get an item from this node.
@@ -3512,7 +3620,8 @@ class Nonlocal(mixins.NoChildrenMixin, Statement):
>>> node.body[0]
<Nonlocal l.3 at 0x7f23b2e9e908>
"""
- _other_fields = ('names',)
+
+ _other_fields = ("names",)
def __init__(self, names, lineno=None, col_offset=None, parent=None):
"""
@@ -3557,7 +3666,8 @@ class Print(Statement):
>>> node
<Print l.1 at 0x7f0e8101d290>
"""
- _astroid_fields = ('dest', 'values',)
+
+ _astroid_fields = ("dest", "values")
dest = None
"""Where to print to.
@@ -3612,12 +3722,13 @@ class Raise(Statement):
>>> node
<Raise l.1 at 0x7f23b2e9e828>
"""
+
exc = None
"""What is being raised.
:type: NodeNG or None
"""
- _astroid_fields = ('exc', 'cause')
+ _astroid_fields = ("exc", "cause")
cause = None
"""The exception being used to raise this one.
@@ -3646,7 +3757,7 @@ class Raise(Statement):
if not self.exc:
return False
for name in self.exc._get_name_nodes():
- if name.name == 'NotImplementedError':
+ if name.name == "NotImplementedError":
return True
return False
@@ -3665,7 +3776,8 @@ class Return(Statement):
>>> node
<Return l.1 at 0x7f23b8211908>
"""
- _astroid_fields = ('value',)
+
+ _astroid_fields = ("value",)
value = None
"""The value being returned.
@@ -3705,7 +3817,7 @@ class Set(_BaseContainer):
:returns: The name of the type.
:rtype: str
"""
- return '%s.set' % BUILTINS
+ return "%s.set" % BUILTINS
class Slice(NodeNG):
@@ -3717,7 +3829,8 @@ class Slice(NodeNG):
>>> node.slice
<Slice l.1 at 0x7f23b2e71e80>
"""
- _astroid_fields = ('lower', 'upper', 'step')
+
+ _astroid_fields = ("lower", "upper", "step")
lower = None
"""The lower index in the slice.
@@ -3761,7 +3874,7 @@ class Slice(NodeNG):
@decorators.cachedproperty
def _proxied(self):
builtins = MANAGER.astroid_cache[BUILTINS]
- return builtins.getattr('slice')[0]
+ return builtins.getattr("slice")[0]
def pytype(self):
"""Get the name of the type that this node represents.
@@ -3769,7 +3882,7 @@ class Slice(NodeNG):
:returns: The name of the type.
:rtype: str
"""
- return '%s.slice' % BUILTINS
+ return "%s.slice" % BUILTINS
def igetattr(self, attrname, context=None):
"""Infer the possible values of the given attribute on the slice.
@@ -3780,11 +3893,11 @@ class Slice(NodeNG):
:returns: The inferred possible values.
:rtype: iterable(NodeNG)
"""
- if attrname == 'start':
+ if attrname == "start":
yield self._wrap_attribute(self.lower)
- elif attrname == 'stop':
+ elif attrname == "stop":
yield self._wrap_attribute(self.upper)
- elif attrname == 'step':
+ elif attrname == "step":
yield self._wrap_attribute(self.step)
else:
yield from self.getattr(attrname, context=context)
@@ -3810,8 +3923,9 @@ class Starred(mixins.ParentAssignTypeMixin, NodeNG):
>>> node
<Starred l.1 at 0x7f23b2e41978>
"""
- _astroid_fields = ('value',)
- _other_fields = ('ctx', )
+
+ _astroid_fields = ("value",)
+ _other_fields = ("ctx",)
value = None
"""What is being unpacked.
@@ -3839,8 +3953,9 @@ class Starred(mixins.ParentAssignTypeMixin, NodeNG):
:type: Context or None
"""
- super(Starred, self).__init__(lineno=lineno,
- col_offset=col_offset, parent=parent)
+ super(Starred, self).__init__(
+ lineno=lineno, col_offset=col_offset, parent=parent
+ )
def postinit(self, value=None):
"""Do some setup after initialisation.
@@ -3861,8 +3976,9 @@ class Subscript(NodeNG):
>>> node
<Subscript l.1 at 0x7f23b2e71f60>
"""
- _astroid_fields = ('value', 'slice')
- _other_fields = ('ctx', )
+
+ _astroid_fields = ("value", "slice")
+ _other_fields = ("ctx",)
value = None
"""What is being indexed.
@@ -3895,8 +4011,9 @@ class Subscript(NodeNG):
:type: Context or None
"""
- super(Subscript, self).__init__(lineno=lineno,
- col_offset=col_offset, parent=parent)
+ super(Subscript, self).__init__(
+ lineno=lineno, col_offset=col_offset, parent=parent
+ )
# pylint: disable=redefined-builtin; had to use the same name as builtin ast module.
def postinit(self, value=None, slice=None):
@@ -3928,8 +4045,9 @@ class TryExcept(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement):
>>> node
<TryExcept l.2 at 0x7f23b2e9d908>
"""
- _astroid_fields = ('body', 'handlers', 'orelse',)
- _multi_line_block_fields = ('body', 'handlers', 'orelse')
+
+ _astroid_fields = ("body", "handlers", "orelse")
+ _multi_line_block_fields = ("body", "handlers", "orelse")
body = None
"""The contents of the block to catch exceptions from.
@@ -3992,8 +4110,7 @@ class TryExcept(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement):
yield from self.orelse or ()
-class TryFinally(mixins.MultiLineBlockMixin,
- mixins.BlockRangeMixIn, Statement):
+class TryFinally(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement):
"""Class representing an :class:`ast.TryFinally` node.
>>> node = astroid.extract_node('''
@@ -4007,8 +4124,9 @@ class TryFinally(mixins.MultiLineBlockMixin,
>>> node
<TryFinally l.2 at 0x7f23b2e41d68>
"""
- _astroid_fields = ('body', 'finalbody',)
- _multi_line_block_fields = ('body', 'finalbody')
+
+ _astroid_fields = ("body", "finalbody")
+ _multi_line_block_fields = ("body", "finalbody")
body = None
"""The try-except that the finally is attached to.
@@ -4044,8 +4162,12 @@ class TryFinally(mixins.MultiLineBlockMixin,
"""
child = self.body[0]
# py2.5 try: except: finally:
- if (isinstance(child, TryExcept) and child.fromlineno == self.fromlineno
- and lineno > self.fromlineno and lineno <= child.tolineno):
+ if (
+ isinstance(child, TryExcept)
+ and child.fromlineno == self.fromlineno
+ and lineno > self.fromlineno
+ and lineno <= child.tolineno
+ ):
return child.block_range(lineno)
return self._elsed_block_range(lineno, self.finalbody)
@@ -4062,10 +4184,9 @@ class Tuple(_BaseContainer):
<Tuple.tuple l.1 at 0x7f23b2e41780>
"""
- _other_fields = ('ctx',)
+ _other_fields = ("ctx",)
- def __init__(self, ctx=None, lineno=None,
- col_offset=None, parent=None):
+ def __init__(self, ctx=None, lineno=None, col_offset=None, parent=None):
"""
:param ctx: Whether the tuple is assigned to or loaded from.
:type ctx: Context or None
@@ -4094,7 +4215,7 @@ class Tuple(_BaseContainer):
:returns: The name of the type.
:rtype: str
"""
- return '%s.tuple' % BUILTINS
+ return "%s.tuple" % BUILTINS
def getitem(self, index, context=None):
"""Get an item from this node.
@@ -4112,8 +4233,9 @@ class UnaryOp(NodeNG):
>>> node
<UnaryOp l.1 at 0x7f23b2e4e198>
"""
- _astroid_fields = ('operand',)
- _other_fields = ('op',)
+
+ _astroid_fields = ("operand",)
+ _other_fields = ("op",)
operand = None
"""What the unary operator is applied to.
@@ -4166,8 +4288,11 @@ class UnaryOp(NodeNG):
"""
try:
results = self._infer_unaryop(context=context)
- return [result for result in results
- if isinstance(result, util.BadUnaryOperationMessage)]
+ return [
+ result
+ for result in results
+ if isinstance(result, util.BadUnaryOperationMessage)
+ ]
except exceptions.InferenceError:
return []
@@ -4175,7 +4300,7 @@ class UnaryOp(NodeNG):
yield self.operand
def op_precedence(self):
- if self.op == 'not':
+ if self.op == "not":
return OP_PRECEDENCE[self.op]
return super().op_precedence()
@@ -4191,8 +4316,9 @@ class While(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement):
>>> node
<While l.2 at 0x7f23b2e4e390>
"""
- _astroid_fields = ('test', 'body', 'orelse',)
- _multi_line_block_fields = ('body', 'orelse')
+
+ _astroid_fields = ("test", "body", "orelse")
+ _multi_line_block_fields = ("body", "orelse")
test = None
"""The condition that the loop tests.
@@ -4243,7 +4369,7 @@ class While(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement):
starting at the given line number.
:rtype: tuple(int, int)
"""
- return self. _elsed_block_range(lineno, self.orelse)
+ return self._elsed_block_range(lineno, self.orelse)
def get_children(self):
yield self.test
@@ -4252,8 +4378,12 @@ class While(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement):
yield from self.orelse
-class With(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn,
- mixins.AssignTypeMixin, Statement):
+class With(
+ mixins.MultiLineBlockMixin,
+ mixins.BlockRangeMixIn,
+ mixins.AssignTypeMixin,
+ Statement,
+):
"""Class representing an :class:`ast.With` node.
>>> node = astroid.extract_node('''
@@ -4263,9 +4393,10 @@ class With(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn,
>>> node
<With l.2 at 0x7f23b2e4e710>
"""
- _astroid_fields = ('items', 'body',)
- _other_other_fields = ('type_annotation',)
- _multi_line_block_fields = ('body',)
+
+ _astroid_fields = ("items", "body")
+ _other_other_fields = ("type_annotation",)
+ _multi_line_block_fields = ("body",)
items = None
"""The pairs of context managers and the names they are assigned to.
@@ -4328,7 +4459,8 @@ class Yield(NodeNG):
>>> node
<Yield l.1 at 0x7f23b2e4e5f8>
"""
- _astroid_fields = ('value',)
+
+ _astroid_fields = ("value",)
value = None
"""The value to yield.
@@ -4370,7 +4502,8 @@ class FormattedValue(NodeNG):
>>> node.values
[<Const.str l.1 at 0x7f23b2e4eda0>, <FormattedValue l.1 at 0x7f23b2e4edd8>]
"""
- _astroid_fields = ('value', 'format_spec')
+
+ _astroid_fields = ("value", "format_spec")
value = None
"""The value to be formatted into the string.
@@ -4423,7 +4556,8 @@ class JoinedStr(NodeNG):
>>> node
<JoinedStr l.1 at 0x7f23b2e4ed30>
"""
- _astroid_fields = ('values',)
+
+ _astroid_fields = ("values",)
values = None
"""The string expressions to be joined.
@@ -4449,6 +4583,7 @@ class Unknown(mixins.AssignTypeMixin, NodeNG):
the args attribute of FunctionDef nodes where function signature
introspection failed.
"""
+
name = "Unknown"
def qname(self):
@@ -4468,13 +4603,16 @@ CONST_CLS = {
set: Set,
type(None): Const,
type(NotImplemented): Const,
- }
+}
+
def _update_const_classes():
"""update constant classes, so the keys of CONST_CLS can be reused"""
klasses = (bool, int, float, complex, str, bytes)
for kls in klasses:
CONST_CLS[kls] = Const
+
+
_update_const_classes()
@@ -4495,7 +4633,7 @@ _CONST_CLS_CONSTRUCTORS = {
Tuple: _two_step_initialization,
Dict: _dict_initialization,
Set: _two_step_initialization,
- Const: lambda cls, value: cls(value)
+ Const: lambda cls, value: cls(value),
}
diff --git a/astroid/nodes.py b/astroid/nodes.py
index eb20cc1a..20672593 100644
--- a/astroid/nodes.py
+++ b/astroid/nodes.py
@@ -21,50 +21,153 @@ All nodes inherit from :class:`~astroid.node_classes.NodeNG`.
# pylint: disable=unused-import,redefined-builtin
from astroid.node_classes import (
- Arguments, AssignAttr, Assert, Assign, AnnAssign,
- AssignName, AugAssign, Repr, BinOp, BoolOp, Break, Call, Compare,
- Comprehension, Const, Continue, Decorators, DelAttr, DelName, Delete,
- Dict, Expr, Ellipsis, EmptyNode, ExceptHandler, Exec, ExtSlice, For,
- ImportFrom, Attribute, Global, If, IfExp, Import, Index, Keyword,
- List, Name, Nonlocal, Pass, Print, Raise, Return, Set, Slice, Starred, Subscript,
- TryExcept, TryFinally, Tuple, UnaryOp, While, With, Yield, YieldFrom,
+ Arguments,
+ AssignAttr,
+ Assert,
+ Assign,
+ AnnAssign,
+ AssignName,
+ AugAssign,
+ Repr,
+ BinOp,
+ BoolOp,
+ Break,
+ Call,
+ Compare,
+ Comprehension,
+ Const,
+ Continue,
+ Decorators,
+ DelAttr,
+ DelName,
+ Delete,
+ Dict,
+ Expr,
+ Ellipsis,
+ EmptyNode,
+ ExceptHandler,
+ Exec,
+ ExtSlice,
+ For,
+ ImportFrom,
+ Attribute,
+ Global,
+ If,
+ IfExp,
+ Import,
+ Index,
+ Keyword,
+ List,
+ Name,
+ Nonlocal,
+ Pass,
+ Print,
+ Raise,
+ Return,
+ Set,
+ Slice,
+ Starred,
+ Subscript,
+ TryExcept,
+ TryFinally,
+ Tuple,
+ UnaryOp,
+ While,
+ With,
+ Yield,
+ YieldFrom,
const_factory,
- AsyncFor, Await, AsyncWith,
- FormattedValue, JoinedStr,
+ AsyncFor,
+ Await,
+ AsyncWith,
+ FormattedValue,
+ JoinedStr,
# Node not present in the builtin ast module.
DictUnpack,
Unknown,
)
from astroid.scoped_nodes import (
- Module, GeneratorExp, Lambda, DictComp,
- ListComp, SetComp, FunctionDef, ClassDef,
+ Module,
+ GeneratorExp,
+ Lambda,
+ DictComp,
+ ListComp,
+ SetComp,
+ FunctionDef,
+ ClassDef,
AsyncFunctionDef,
)
-
ALL_NODE_CLASSES = (
- AsyncFunctionDef, AsyncFor, AsyncWith, Await,
-
- Arguments, AssignAttr, Assert, Assign, AnnAssign, AssignName, AugAssign,
- Repr, BinOp, BoolOp, Break,
- Call, ClassDef, Compare, Comprehension, Const, Continue,
- Decorators, DelAttr, DelName, Delete,
- Dict, DictComp, DictUnpack, Expr,
- Ellipsis, EmptyNode, ExceptHandler, Exec, ExtSlice,
- For, ImportFrom, FunctionDef,
- Attribute, GeneratorExp, Global,
- If, IfExp, Import, Index,
+ AsyncFunctionDef,
+ AsyncFor,
+ AsyncWith,
+ Await,
+ Arguments,
+ AssignAttr,
+ Assert,
+ Assign,
+ AnnAssign,
+ AssignName,
+ AugAssign,
+ Repr,
+ BinOp,
+ BoolOp,
+ Break,
+ Call,
+ ClassDef,
+ Compare,
+ Comprehension,
+ Const,
+ Continue,
+ Decorators,
+ DelAttr,
+ DelName,
+ Delete,
+ Dict,
+ DictComp,
+ DictUnpack,
+ Expr,
+ Ellipsis,
+ EmptyNode,
+ ExceptHandler,
+ Exec,
+ ExtSlice,
+ For,
+ ImportFrom,
+ FunctionDef,
+ Attribute,
+ GeneratorExp,
+ Global,
+ If,
+ IfExp,
+ Import,
+ Index,
Keyword,
- Lambda, List, ListComp,
- Name, Nonlocal,
+ Lambda,
+ List,
+ ListComp,
+ Name,
+ Nonlocal,
Module,
- Pass, Print,
- Raise, Return,
- Set, SetComp, Slice, Starred, Subscript,
- TryExcept, TryFinally, Tuple,
+ Pass,
+ Print,
+ Raise,
+ Return,
+ Set,
+ SetComp,
+ Slice,
+ Starred,
+ Subscript,
+ TryExcept,
+ TryFinally,
+ Tuple,
UnaryOp,
- While, With,
- Yield, YieldFrom,
- FormattedValue, JoinedStr,
- )
+ While,
+ With,
+ Yield,
+ YieldFrom,
+ FormattedValue,
+ JoinedStr,
+)
diff --git a/astroid/objects.py b/astroid/objects.py
index 156ed520..367f650e 100644
--- a/astroid/objects.py
+++ b/astroid/objects.py
@@ -29,22 +29,22 @@ from astroid import util
BUILTINS = builtins.__name__
-objectmodel = util.lazy_import('interpreter.objectmodel')
+objectmodel = util.lazy_import("interpreter.objectmodel")
class FrozenSet(node_classes._BaseContainer):
"""class representing a FrozenSet composite node"""
def pytype(self):
- return '%s.frozenset' % BUILTINS
+ return "%s.frozenset" % BUILTINS
def _infer(self, context=None):
yield self
@decorators.cachedproperty
- def _proxied(self): # pylint: disable=method-hidden
+ def _proxied(self): # pylint: disable=method-hidden
ast_builtins = MANAGER.astroid_cache[BUILTINS]
- return ast_builtins.getattr('frozenset')[0]
+ return ast_builtins.getattr("frozenset")[0]
class Super(node_classes.NodeNG):
@@ -59,6 +59,7 @@ class Super(node_classes.NodeNG):
*self_class* is the class where the super call is, while
*scope* is the function where the super call is.
"""
+
# pylint: disable=unnecessary-lambda
special_attributes = util.lazy_descriptor(lambda: objectmodel.SuperModel())
@@ -78,43 +79,49 @@ class Super(node_classes.NodeNG):
if not isinstance(self.mro_pointer, scoped_nodes.ClassDef):
raise exceptions.SuperError(
"The first argument to super must be a subtype of "
- "type, not {mro_pointer}.", super_=self)
+ "type, not {mro_pointer}.",
+ super_=self,
+ )
if isinstance(self.type, scoped_nodes.ClassDef):
# `super(type, type)`, most likely in a class method.
self._class_based = True
mro_type = self.type
else:
- mro_type = getattr(self.type, '_proxied', None)
+ mro_type = getattr(self.type, "_proxied", None)
if not isinstance(mro_type, (bases.Instance, scoped_nodes.ClassDef)):
raise exceptions.SuperError(
"The second argument to super must be an "
"instance or subtype of type, not {type}.",
- super_=self)
+ super_=self,
+ )
if not mro_type.newstyle:
- raise exceptions.SuperError("Unable to call super on old-style classes.", super_=self)
+ raise exceptions.SuperError(
+ "Unable to call super on old-style classes.", super_=self
+ )
mro = mro_type.mro()
if self.mro_pointer not in mro:
raise exceptions.SuperError(
"The second argument to super must be an "
"instance or subtype of type, not {type}.",
- super_=self)
+ super_=self,
+ )
index = mro.index(self.mro_pointer)
- return mro[index + 1:]
+ return mro[index + 1 :]
@decorators.cachedproperty
def _proxied(self):
ast_builtins = MANAGER.astroid_cache[BUILTINS]
- return ast_builtins.getattr('super')[0]
+ return ast_builtins.getattr("super")[0]
def pytype(self):
- return '%s.super' % BUILTINS
+ return "%s.super" % BUILTINS
def display_type(self):
- return 'Super of'
+ return "Super of"
@property
def name(self):
@@ -137,15 +144,27 @@ class Super(node_classes.NodeNG):
# leak out as is from this function.
except exceptions.SuperError as exc:
raise exceptions.AttributeInferenceError(
- ('Lookup for {name} on {target!r} because super call {super!r} '
- 'is invalid.'),
- target=self, attribute=name, context=context, super_=exc.super_) from exc
+ (
+ "Lookup for {name} on {target!r} because super call {super!r} "
+ "is invalid."
+ ),
+ target=self,
+ attribute=name,
+ context=context,
+ super_=exc.super_,
+ ) from exc
except exceptions.MroError as exc:
raise exceptions.AttributeInferenceError(
- ('Lookup for {name} on {target!r} failed because {cls!r} has an '
- 'invalid MRO.'),
- target=self, attribute=name, context=context, mros=exc.mros,
- cls=exc.cls) from exc
+ (
+ "Lookup for {name} on {target!r} failed because {cls!r} has an "
+ "invalid MRO."
+ ),
+ target=self,
+ attribute=name,
+ context=context,
+ mros=exc.mros,
+ cls=exc.cls,
+ ) from exc
found = False
for cls in mro:
if name not in cls.locals:
@@ -159,11 +178,11 @@ class Super(node_classes.NodeNG):
# We can obtain different descriptors from a super depending
# on what we are accessing and where the super call is.
- if inferred.type == 'classmethod':
+ if inferred.type == "classmethod":
yield bases.BoundMethod(inferred, cls)
- elif self._scope.type == 'classmethod' and inferred.type == 'method':
+ elif self._scope.type == "classmethod" and inferred.type == "method":
yield inferred
- elif self._class_based or inferred.type == 'staticmethod':
+ elif self._class_based or inferred.type == "staticmethod":
yield inferred
elif bases._is_property(inferred):
# TODO: support other descriptors as well.
@@ -175,9 +194,9 @@ class Super(node_classes.NodeNG):
yield bases.BoundMethod(inferred, cls)
if not found:
- raise exceptions.AttributeInferenceError(target=self,
- attribute=name,
- context=context)
+ raise exceptions.AttributeInferenceError(
+ target=self, attribute=name, context=context
+ )
def getattr(self, name, context=None):
return list(self.igetattr(name, context=context))
@@ -192,7 +211,9 @@ class ExceptionInstance(bases.Instance):
"""
# pylint: disable=unnecessary-lambda
- special_attributes = util.lazy_descriptor(lambda: objectmodel.ExceptionInstanceModel())
+ special_attributes = util.lazy_descriptor(
+ lambda: objectmodel.ExceptionInstanceModel()
+ )
class DictInstance(bases.Instance):
@@ -223,6 +244,7 @@ class DictValues(bases.Proxy):
__str__ = node_classes.NodeNG.__str__
__repr__ = node_classes.NodeNG.__repr__
+
# TODO: Hack to solve the circular import problem between node_classes and objects
# This is not needed in 2.0, which has a cleaner design overall
node_classes.Dict.__bases__ = (node_classes.NodeNG, DictInstance)
diff --git a/astroid/protocols.py b/astroid/protocols.py
index 6a051cc2..77d0ceb4 100644
--- a/astroid/protocols.py
+++ b/astroid/protocols.py
@@ -35,51 +35,53 @@ from astroid import helpers
from astroid import nodes
from astroid import util
-raw_building = util.lazy_import('raw_building')
-objects = util.lazy_import('objects')
+raw_building = util.lazy_import("raw_building")
+objects = util.lazy_import("objects")
+
def _reflected_name(name):
return "__r" + name[2:]
+
def _augmented_name(name):
return "__i" + name[2:]
-_CONTEXTLIB_MGR = 'contextlib.contextmanager'
-BIN_OP_METHOD = {'+': '__add__',
- '-': '__sub__',
- '/': '__truediv__',
- '//': '__floordiv__',
- '*': '__mul__',
- '**': '__pow__',
- '%': '__mod__',
- '&': '__and__',
- '|': '__or__',
- '^': '__xor__',
- '<<': '__lshift__',
- '>>': '__rshift__',
- '@': '__matmul__'
- }
+_CONTEXTLIB_MGR = "contextlib.contextmanager"
+BIN_OP_METHOD = {
+ "+": "__add__",
+ "-": "__sub__",
+ "/": "__truediv__",
+ "//": "__floordiv__",
+ "*": "__mul__",
+ "**": "__pow__",
+ "%": "__mod__",
+ "&": "__and__",
+ "|": "__or__",
+ "^": "__xor__",
+ "<<": "__lshift__",
+ ">>": "__rshift__",
+ "@": "__matmul__",
+}
REFLECTED_BIN_OP_METHOD = {
- key: _reflected_name(value)
- for (key, value) in BIN_OP_METHOD.items()
+ key: _reflected_name(value) for (key, value) in BIN_OP_METHOD.items()
}
AUGMENTED_OP_METHOD = {
- key + "=": _augmented_name(value)
- for (key, value) in BIN_OP_METHOD.items()
+ key + "=": _augmented_name(value) for (key, value) in BIN_OP_METHOD.items()
}
-UNARY_OP_METHOD = {'+': '__pos__',
- '-': '__neg__',
- '~': '__invert__',
- 'not': None, # XXX not '__nonzero__'
- }
+UNARY_OP_METHOD = {
+ "+": "__pos__",
+ "-": "__neg__",
+ "~": "__invert__",
+ "not": None, # XXX not '__nonzero__'
+}
_UNARY_OPERATORS = {
- '+': operator_mod.pos,
- '-': operator_mod.neg,
- '~': operator_mod.invert,
- 'not': operator_mod.not_,
+ "+": operator_mod.pos,
+ "-": operator_mod.neg,
+ "~": operator_mod.invert,
+ "not": operator_mod.not_,
}
@@ -88,6 +90,7 @@ def _infer_unary_op(obj, op):
value = func(obj)
return nodes.const_factory(value)
+
nodes.Tuple.infer_unary_op = lambda self, op: _infer_unary_op(tuple(self.elts), op)
nodes.List.infer_unary_op = lambda self, op: _infer_unary_op(self.elts, op)
nodes.Set.infer_unary_op = lambda self, op: _infer_unary_op(set(self.elts), op)
@@ -96,25 +99,26 @@ nodes.Dict.infer_unary_op = lambda self, op: _infer_unary_op(dict(self.items), o
# Binary operations
-BIN_OP_IMPL = {'+': lambda a, b: a + b,
- '-': lambda a, b: a - b,
- '/': lambda a, b: a / b,
- '//': lambda a, b: a // b,
- '*': lambda a, b: a * b,
- '**': lambda a, b: a ** b,
- '%': lambda a, b: a % b,
- '&': lambda a, b: a & b,
- '|': lambda a, b: a | b,
- '^': lambda a, b: a ^ b,
- '<<': lambda a, b: a << b,
- '>>': lambda a, b: a >> b,
- }
+BIN_OP_IMPL = {
+ "+": lambda a, b: a + b,
+ "-": lambda a, b: a - b,
+ "/": lambda a, b: a / b,
+ "//": lambda a, b: a // b,
+ "*": lambda a, b: a * b,
+ "**": lambda a, b: a ** b,
+ "%": lambda a, b: a % b,
+ "&": lambda a, b: a & b,
+ "|": lambda a, b: a | b,
+ "^": lambda a, b: a ^ b,
+ "<<": lambda a, b: a << b,
+ ">>": lambda a, b: a >> b,
+}
if sys.version_info >= (3, 5):
# MatMult is available since Python 3.5+.
- BIN_OP_IMPL['@'] = operator_mod.matmul
+ BIN_OP_IMPL["@"] = operator_mod.matmul
for _KEY, _IMPL in list(BIN_OP_IMPL.items()):
- BIN_OP_IMPL[_KEY + '='] = _IMPL
+ BIN_OP_IMPL[_KEY + "="] = _IMPL
@decorators.yes_if_nothing_inferred
@@ -128,16 +132,17 @@ def const_infer_binary_op(self, opnode, operator, other, context, _):
except TypeError:
# ArithmeticError is not enough: float >> float is a TypeError
yield not_implemented
- except Exception: # pylint: disable=broad-except
+ except Exception: # pylint: disable=broad-except
yield util.Uninferable
except TypeError:
yield not_implemented
- elif isinstance(self.value, str) and operator == '%':
+ elif isinstance(self.value, str) and operator == "%":
# TODO(cpopa): implement string interpolation later on.
yield util.Uninferable
else:
yield not_implemented
+
nodes.Const.infer_binary_op = const_infer_binary_op
@@ -169,18 +174,18 @@ def _filter_uninferable_nodes(elts, context):
@decorators.yes_if_nothing_inferred
def tl_infer_binary_op(self, opnode, operator, other, context, method):
not_implemented = nodes.Const(NotImplemented)
- if isinstance(other, self.__class__) and operator == '+':
+ if isinstance(other, self.__class__) and operator == "+":
node = self.__class__(parent=opnode)
elts = list(_filter_uninferable_nodes(self.elts, context))
elts += list(_filter_uninferable_nodes(other.elts, context))
node.elts = elts
yield node
- elif isinstance(other, nodes.Const) and operator == '*':
+ elif isinstance(other, nodes.Const) and operator == "*":
if not isinstance(other.value, int):
yield not_implemented
return
yield _multiply_seq_by_int(self, opnode, other, context)
- elif isinstance(other, bases.Instance) and operator == '*':
+ elif isinstance(other, bases.Instance) and operator == "*":
# Verify if the instance supports __index__.
as_index = helpers.class_instance_as_index(other)
if not as_index:
@@ -190,6 +195,7 @@ def tl_infer_binary_op(self, opnode, operator, other, context, method):
else:
yield not_implemented
+
nodes.Tuple.infer_binary_op = tl_infer_binary_op
nodes.List.infer_binary_op = tl_infer_binary_op
@@ -198,6 +204,7 @@ nodes.List.infer_binary_op = tl_infer_binary_op
def instance_class_infer_binary_op(self, opnode, operator, other, context, method):
return method.infer_call_result(self, context)
+
bases.Instance.infer_binary_op = instance_class_infer_binary_op
nodes.ClassDef.infer_binary_op = instance_class_infer_binary_op
@@ -215,6 +222,7 @@ The `context` argument is the current inference context which should be given
to any intermediary inference necessary.
"""
+
def _resolve_looppart(parts, assign_path, context):
"""recursive function to resolve multiple assignments on loops"""
assign_path = assign_path[:]
@@ -223,19 +231,21 @@ def _resolve_looppart(parts, assign_path, context):
if part is util.Uninferable:
continue
# XXX handle __iter__ and log potentially detected errors
- if not hasattr(part, 'itered'):
+ if not hasattr(part, "itered"):
continue
try:
itered = part.itered()
except TypeError:
- continue # XXX log error
+ continue # XXX log error
for stmt in itered:
index_node = nodes.Const(index)
try:
assigned = stmt.getitem(index_node, context)
- except (AttributeError,
- exceptions.AstroidTypeError,
- exceptions.AstroidIndexError):
+ except (
+ AttributeError,
+ exceptions.AstroidTypeError,
+ exceptions.AstroidIndexError,
+ ):
continue
if not assign_path:
# we achieved to resolved the assignment path,
@@ -247,25 +257,26 @@ def _resolve_looppart(parts, assign_path, context):
# we are not yet on the last part of the path
# search on each possibly inferred value
try:
- yield from _resolve_looppart(assigned.infer(context), assign_path, context)
+ yield from _resolve_looppart(
+ assigned.infer(context), assign_path, context
+ )
except exceptions.InferenceError:
break
@decorators.raise_if_nothing_inferred
def for_assigned_stmts(self, node=None, context=None, assign_path=None):
- if isinstance(self, nodes.AsyncFor) or getattr(self, 'is_async', False):
+ if isinstance(self, nodes.AsyncFor) or getattr(self, "is_async", False):
# Skip inferring of async code for now
- return dict(node=self, unknown=node,
- assign_path=assign_path, context=context)
+ return dict(node=self, unknown=node, assign_path=assign_path, context=context)
if assign_path is None:
for lst in self.iter.infer(context):
if isinstance(lst, (nodes.Tuple, nodes.List)):
yield from lst.elts
else:
yield from _resolve_looppart(self.iter.infer(context), assign_path, context)
- return dict(node=self, unknown=node,
- assign_path=assign_path, context=context)
+ return dict(node=self, unknown=node, assign_path=assign_path, context=context)
+
nodes.For.assigned_stmts = for_assigned_stmts
nodes.Comprehension.assigned_stmts = for_assigned_stmts
@@ -278,11 +289,17 @@ def sequence_assigned_stmts(self, node=None, context=None, assign_path=None):
index = self.elts.index(node)
except ValueError as exc:
raise exceptions.InferenceError(
- 'Tried to retrieve a node {node!r} which does not exist',
- node=self, assign_path=assign_path, context=context) from exc
+ "Tried to retrieve a node {node!r} which does not exist",
+ node=self,
+ assign_path=assign_path,
+ context=context,
+ ) from exc
assign_path.insert(0, index)
- return self.parent.assigned_stmts(node=self, context=context, assign_path=assign_path)
+ return self.parent.assigned_stmts(
+ node=self, context=context, assign_path=assign_path
+ )
+
nodes.Tuple.assigned_stmts = sequence_assigned_stmts
nodes.List.assigned_stmts = sequence_assigned_stmts
@@ -290,6 +307,8 @@ nodes.List.assigned_stmts = sequence_assigned_stmts
def assend_assigned_stmts(self, node=None, context=None, assign_path=None):
return self.parent.assigned_stmts(node=self, context=context)
+
+
nodes.AssignName.assigned_stmts = assend_assigned_stmts
nodes.AssignAttr.assigned_stmts = assend_assigned_stmts
@@ -301,22 +320,21 @@ def _arguments_infer_argname(self, name, context):
yield util.Uninferable
return
# first argument of instance/class method
- if self.args and getattr(self.args[0], 'name', None) == name:
+ if self.args and getattr(self.args[0], "name", None) == name:
functype = self.parent.type
cls = self.parent.parent.scope()
- is_metaclass = isinstance(cls, nodes.ClassDef) and cls.type == 'metaclass'
+ is_metaclass = isinstance(cls, nodes.ClassDef) and cls.type == "metaclass"
# If this is a metaclass, then the first argument will always
# be the class, not an instance.
- if is_metaclass or functype == 'classmethod':
+ if is_metaclass or functype == "classmethod":
yield cls
return
- if functype == 'method':
+ if functype == "method":
yield bases.Instance(self.parent.parent.frame())
return
if context and context.callcontext:
- call_site = arguments.CallSite(context.callcontext,
- context.extra_context)
+ call_site = arguments.CallSite(context.callcontext, context.extra_context)
for value in call_site.infer_argument(self.parent, name, context):
yield value
return
@@ -351,6 +369,7 @@ def arguments_assigned_stmts(self, node=None, context=None, assign_path=None):
return args.infer_argument(self.parent, node.name, context)
return _arguments_infer_argname(self, node.name, context)
+
nodes.Arguments.assigned_stmts = arguments_assigned_stmts
@@ -359,10 +378,11 @@ def assign_assigned_stmts(self, node=None, context=None, assign_path=None):
if not assign_path:
yield self.value
return None
- yield from _resolve_assignment_parts(self.value.infer(context), assign_path, context)
+ yield from _resolve_assignment_parts(
+ self.value.infer(context), assign_path, context
+ )
- return dict(node=self, unknown=node,
- assign_path=assign_path, context=context)
+ return dict(node=self, unknown=node, assign_path=assign_path, context=context)
def assign_annassigned_stmts(self, node=None, context=None, assign_path=None):
@@ -372,6 +392,7 @@ def assign_annassigned_stmts(self, node=None, context=None, assign_path=None):
else:
yield inferred
+
nodes.Assign.assigned_stmts = assign_assigned_stmts
nodes.AnnAssign.assigned_stmts = assign_annassigned_stmts
nodes.AugAssign.assigned_stmts = assign_assigned_stmts
@@ -390,7 +411,7 @@ def _resolve_assignment_parts(parts, assign_path, context):
except IndexError:
return
- elif hasattr(part, 'getitem'):
+ elif hasattr(part, "getitem"):
index_node = nodes.Const(index)
try:
assigned = part.getitem(index_node, context)
@@ -412,7 +433,9 @@ def _resolve_assignment_parts(parts, assign_path, context):
# we are not yet on the last part of the path search on each
# possibly inferred value
try:
- yield from _resolve_assignment_parts(assigned.infer(context), assign_path, context)
+ yield from _resolve_assignment_parts(
+ assigned.infer(context), assign_path, context
+ )
except exceptions.InferenceError:
return
@@ -424,8 +447,7 @@ def excepthandler_assigned_stmts(self, node=None, context=None, assign_path=None
assigned = objects.ExceptionInstance(assigned)
yield assigned
- return dict(node=self, unknown=node,
- assign_path=assign_path, context=context)
+ return dict(node=self, unknown=node, assign_path=assign_path, context=context)
nodes.ExceptHandler.assigned_stmts = excepthandler_assigned_stmts
@@ -458,9 +480,9 @@ def _infer_context_manager(self, mgr, context):
possible_yield_points = func.nodes_of_class(nodes.Yield)
# Ignore yields in nested functions
- yield_point = next((node for node in possible_yield_points
- if node.scope() == func),
- None)
+ yield_point = next(
+ (node for node in possible_yield_points if node.scope() == func), None
+ )
if yield_point:
if not yield_point.value:
const = nodes.Const(None)
@@ -471,8 +493,12 @@ def _infer_context_manager(self, mgr, context):
yield from yield_point.value.infer(context=context)
elif isinstance(inferred, bases.Instance):
try:
- enter = next(inferred.igetattr('__enter__', context=context))
- except (StopIteration, exceptions.InferenceError, exceptions.AttributeInferenceError):
+ enter = next(inferred.igetattr("__enter__", context=context))
+ except (
+ StopIteration,
+ exceptions.InferenceError,
+ exceptions.AttributeInferenceError,
+ ):
return
if not isinstance(enter, bases.BoundMethod):
return
@@ -519,26 +545,36 @@ def with_assigned_stmts(self, node=None, context=None, assign_path=None):
# Walk the assign_path and get the item at the final index.
obj = result
for index in assign_path:
- if not hasattr(obj, 'elts'):
+ if not hasattr(obj, "elts"):
raise exceptions.InferenceError(
- 'Wrong type ({targets!r}) for {node!r} assignment',
- node=self, targets=node, assign_path=assign_path,
- context=context)
+ "Wrong type ({targets!r}) for {node!r} assignment",
+ node=self,
+ targets=node,
+ assign_path=assign_path,
+ context=context,
+ )
try:
obj = obj.elts[index]
except IndexError as exc:
raise exceptions.InferenceError(
- 'Tried to infer a nonexistent target with index {index} '
- 'in {node!r}.', node=self, targets=node,
- assign_path=assign_path, context=context) from exc
+ "Tried to infer a nonexistent target with index {index} "
+ "in {node!r}.",
+ node=self,
+ targets=node,
+ assign_path=assign_path,
+ context=context,
+ ) from exc
except TypeError as exc:
raise exceptions.InferenceError(
- 'Tried to unpack a non-iterable value '
- 'in {node!r}.', node=self, targets=node,
- assign_path=assign_path, context=context) from exc
+ "Tried to unpack a non-iterable value " "in {node!r}.",
+ node=self,
+ targets=node,
+ assign_path=assign_path,
+ context=context,
+ ) from exc
yield obj
- return dict(node=self, unknown=node,
- assign_path=assign_path, context=context)
+ return dict(node=self, unknown=node, assign_path=assign_path, context=context)
+
nodes.With.assigned_stmts = with_assigned_stmts
@@ -557,7 +593,10 @@ def starred_assigned_stmts(self, node=None, context=None, assign_path=None):
# Determine the lookups for the rhs of the iteration
itered = target.itered()
for index, element in enumerate(itered):
- if isinstance(element, nodes.Starred) and element.value.name == starred.value.name:
+ if (
+ isinstance(element, nodes.Starred)
+ and element.value.name == starred.value.name
+ ):
lookups.append((index, len(itered)))
break
if isinstance(element, nodes.Tuple):
@@ -566,10 +605,13 @@ def starred_assigned_stmts(self, node=None, context=None, assign_path=None):
stmt = self.statement()
if not isinstance(stmt, (nodes.Assign, nodes.For)):
- raise exceptions.InferenceError('Statement {stmt!r} enclosing {node!r} '
- 'must be an Assign or For node.',
- node=self, stmt=stmt, unknown=node,
- context=context)
+ raise exceptions.InferenceError(
+ "Statement {stmt!r} enclosing {node!r} " "must be an Assign or For node.",
+ node=self,
+ stmt=stmt,
+ unknown=node,
+ context=context,
+ )
if context is None:
context = contextmod.InferenceContext()
@@ -579,17 +621,20 @@ def starred_assigned_stmts(self, node=None, context=None, assign_path=None):
lhs = stmt.targets[0]
if sum(1 for _ in lhs.nodes_of_class(nodes.Starred)) > 1:
- raise exceptions.InferenceError('Too many starred arguments in the '
- ' assignment targets {lhs!r}.',
- node=self, targets=lhs,
- unknown=node, context=context)
+ raise exceptions.InferenceError(
+ "Too many starred arguments in the " " assignment targets {lhs!r}.",
+ node=self,
+ targets=lhs,
+ unknown=node,
+ context=context,
+ )
try:
rhs = next(value.infer(context))
except exceptions.InferenceError:
yield util.Uninferable
return
- if rhs is util.Uninferable or not hasattr(rhs, 'itered'):
+ if rhs is util.Uninferable or not hasattr(rhs, "itered"):
yield util.Uninferable
return
@@ -621,10 +666,7 @@ def starred_assigned_stmts(self, node=None, context=None, assign_path=None):
continue
# We're done
packed = nodes.List(
- ctx=Store,
- parent=self,
- lineno=lhs.lineno,
- col_offset=lhs.col_offset,
+ ctx=Store, parent=self, lineno=lhs.lineno, col_offset=lhs.col_offset
)
packed.postinit(elts=elts)
yield packed
@@ -636,7 +678,9 @@ def starred_assigned_stmts(self, node=None, context=None, assign_path=None):
except exceptions.InferenceError:
yield util.Uninferable
return
- if inferred_iterable is util.Uninferable or not hasattr(inferred_iterable, 'itered'):
+ if inferred_iterable is util.Uninferable or not hasattr(
+ inferred_iterable, "itered"
+ ):
yield util.Uninferable
return
try:
@@ -649,7 +693,7 @@ def starred_assigned_stmts(self, node=None, context=None, assign_path=None):
if not isinstance(target, nodes.Tuple):
raise exceptions.InferenceError(
- 'Could not make sense of this, the target must be a tuple',
+ "Could not make sense of this, the target must be a tuple",
context=context,
)
@@ -657,8 +701,7 @@ def starred_assigned_stmts(self, node=None, context=None, assign_path=None):
_determine_starred_iteration_lookups(self, target, lookups)
if not lookups:
raise exceptions.InferenceError(
- 'Could not make sense of this, needs at least a lookup',
- context=context,
+ "Could not make sense of this, needs at least a lookup", context=context
)
# Make the last lookup a slice, since that what we want for a Starred node
@@ -667,7 +710,7 @@ def starred_assigned_stmts(self, node=None, context=None, assign_path=None):
lookup_slice = slice(
last_element_index,
- None if is_starred_last else (last_element_length - last_element_index)
+ None if is_starred_last else (last_element_length - last_element_index),
)
lookups[-1] = lookup_slice
@@ -685,7 +728,7 @@ def starred_assigned_stmts(self, node=None, context=None, assign_path=None):
found_element = None
for lookup in lookups:
- if not hasattr(element, 'itered'):
+ if not hasattr(element, "itered"):
break
if not isinstance(lookup, slice):
# Grab just the index, not the whole length
@@ -703,10 +746,7 @@ def starred_assigned_stmts(self, node=None, context=None, assign_path=None):
found_element = element
unpacked = nodes.List(
- ctx=Store,
- parent=self,
- lineno=self.lineno,
- col_offset=self.col_offset,
+ ctx=Store, parent=self, lineno=self.lineno, col_offset=self.col_offset
)
unpacked.postinit(elts=found_element or [])
yield unpacked
diff --git a/astroid/raw_building.py b/astroid/raw_building.py
index 263a3829..1cd6c81f 100644
--- a/astroid/raw_building.py
+++ b/astroid/raw_building.py
@@ -40,26 +40,29 @@ _LOG = logging.getLogger(__name__)
def _io_discrepancy(member):
# _io module names itself `io`: http://bugs.python.org/issue18602
- member_self = getattr(member, '__self__', None)
- return (member_self and
- inspect.ismodule(member_self) and
- member_self.__name__ == '_io' and
- member.__module__ == 'io')
+ member_self = getattr(member, "__self__", None)
+ return (
+ member_self
+ and inspect.ismodule(member_self)
+ and member_self.__name__ == "_io"
+ and member.__module__ == "io"
+ )
+
def _attach_local_node(parent, node, name):
- node.name = name # needed by add_local_node
+ node.name = name # needed by add_local_node
parent.add_local_node(node)
def _add_dunder_class(func, member):
"""Add a __class__ member to the given func node, if we can determine it."""
python_cls = member.__class__
- cls_name = getattr(python_cls, '__name__', None)
+ cls_name = getattr(python_cls, "__name__", None)
if not cls_name:
return
cls_bases = [ancestor.__name__ for ancestor in python_cls.__bases__]
ast_klass = build_class(cls_name, cls_bases, python_cls.__doc__)
- func.instance_attrs['__class__'] = [ast_klass]
+ func.instance_attrs["__class__"] = [ast_klass]
_marker = object()
@@ -73,11 +76,14 @@ def attach_dummy_node(node, name, runtime_object=_marker):
enode.object = runtime_object
_attach_local_node(node, enode, name)
+
def _has_underlying_object(self):
return self.object is not None and self.object is not _marker
+
nodes.EmptyNode.has_underlying_object = _has_underlying_object
+
def attach_const_node(node, name, value):
"""create a Const node and register it in the locals of the given
node with the specified name
@@ -85,6 +91,7 @@ def attach_const_node(node, name, value):
if name not in node.special_attributes:
_attach_local_node(node, nodes.const_factory(value), name)
+
def attach_import_node(node, modname, membername):
"""create a ImportFrom node and register it in the locals of the given
node with the specified name
@@ -139,6 +146,7 @@ def build_from_import(fromname, names):
"""create and initialize an astroid ImportFrom import statement"""
return nodes.ImportFrom(fromname, [(name, None) for name in names])
+
def register_arguments(func, args=None):
"""add given arguments to local
@@ -161,8 +169,7 @@ def register_arguments(func, args=None):
def object_build_class(node, member, localname):
"""create astroid for a living class object"""
basenames = [base.__name__ for base in member.__bases__]
- return _base_class_object_build(node, member, basenames,
- localname=localname)
+ return _base_class_object_build(node, member, basenames, localname=localname)
def object_build_function(node, member, localname):
@@ -173,8 +180,9 @@ def object_build_function(node, member, localname):
args.append(varargs)
if varkw is not None:
args.append(varkw)
- func = build_function(getattr(member, '__name__', None) or localname, args,
- defaults, member.__doc__)
+ func = build_function(
+ getattr(member, "__name__", None) or localname, args, defaults, member.__doc__
+ )
node.add_local_node(func, localname)
@@ -186,8 +194,9 @@ def object_build_datadescriptor(node, member, name):
def object_build_methoddescriptor(node, member, localname):
"""create astroid for a living method descriptor object"""
# FIXME get arguments ?
- func = build_function(getattr(member, '__name__', None) or localname,
- doc=member.__doc__)
+ func = build_function(
+ getattr(member, "__name__", None) or localname, doc=member.__doc__
+ )
# set node's arguments to None to notice that we have no information, not
# and empty argument list
func.args.args = None
@@ -199,8 +208,11 @@ def _base_class_object_build(node, member, basenames, name=None, localname=None)
"""create astroid for a living class object, with a given set of base names
(e.g. ancestors)
"""
- klass = build_class(name or getattr(member, '__name__', None) or localname,
- basenames, member.__doc__)
+ klass = build_class(
+ name or getattr(member, "__name__", None) or localname,
+ basenames,
+ member.__doc__,
+ )
klass._newstyle = isinstance(member, type)
node.add_local_node(klass, localname)
try:
@@ -212,7 +224,7 @@ def _base_class_object_build(node, member, basenames, name=None, localname=None)
instdict = member().__dict__
else:
raise TypeError
- except: # pylint: disable=bare-except
+ except: # pylint: disable=bare-except
pass
else:
for item_name, obj in instdict.items():
@@ -232,11 +244,11 @@ def _build_from_function(node, name, member, module):
# Some implementations don't provide the code object,
# such as Jython.
code = None
- filename = getattr(code, 'co_filename', None)
+ filename = getattr(code, "co_filename", None)
if filename is None:
assert isinstance(member, object)
object_build_methoddescriptor(node, member, name)
- elif filename != getattr(module, '__file__', None):
+ elif filename != getattr(module, "__file__", None):
attach_dummy_node(node, name, member)
else:
object_build_function(node, member, name)
@@ -271,7 +283,7 @@ class InspectBuilder:
node.file = node.path = os.path.abspath(path) if path else path
node.name = modname
MANAGER.cache_module(node)
- node.package = hasattr(module, '__path__')
+ node.package = hasattr(module, "__path__")
self._done = {}
self.object_build(node, module)
return node
@@ -295,8 +307,9 @@ class InspectBuilder:
if inspect.isfunction(member):
_build_from_function(node, name, member, self._module)
elif inspect.isbuiltin(member):
- if (not _io_discrepancy(member) and
- self.imported_member(node, member, name)):
+ if not _io_discrepancy(member) and self.imported_member(
+ node, member, name
+ ):
continue
object_build_methoddescriptor(node, member, name)
elif inspect.isclass(member):
@@ -310,7 +323,7 @@ class InspectBuilder:
class_node = object_build_class(node, member, name)
# recursion
self.object_build(class_node, member)
- if name == '__class__' and class_node.parent is None:
+ if name == "__class__" and class_node.parent is None:
class_node.parent = self._done[self._module]
elif inspect.ismethoddescriptor(member):
assert isinstance(member, object)
@@ -335,13 +348,14 @@ class InspectBuilder:
# attribute ! Also, this may trigger an exception on badly built module
# (see http://www.logilab.org/ticket/57299 for instance)
try:
- modname = getattr(member, '__module__', None)
- except: # pylint: disable=bare-except
- _LOG.exception('unexpected error while building '
- 'astroid from living object')
+ modname = getattr(member, "__module__", None)
+ except: # pylint: disable=bare-except
+ _LOG.exception(
+ "unexpected error while building " "astroid from living object"
+ )
modname = None
if modname is None:
- if name in ('__new__', '__subclasshook__'):
+ if name in ("__new__", "__subclasshook__"):
# Python 2.5.1 (r251:54863, Sep 1 2010, 22:03:14)
# >>> print object.__new__.__module__
# None
@@ -350,10 +364,7 @@ class InspectBuilder:
attach_dummy_node(node, name, member)
return True
- real_name = {
- 'gtk': 'gtk_gtk',
- '_io': 'io',
- }.get(modname, modname)
+ real_name = {"gtk": "gtk_gtk", "_io": "io"}.get(modname, modname)
if real_name != self._module.__name__:
# check if it sounds valid and then add an import node, else use a
@@ -372,6 +383,8 @@ class InspectBuilder:
Astroid_BUILDER = InspectBuilder()
_CONST_PROXY = {}
+
+
def _astroid_bootstrapping(astroid_builtin=None):
"""astroid boot strapping the builtins module"""
# this boot strapping is necessary since we need the Const nodes to
@@ -382,10 +395,10 @@ def _astroid_bootstrapping(astroid_builtin=None):
# pylint: disable=redefined-outer-name
for cls, node_cls in node_classes.CONST_CLS.items():
if cls is type(None):
- proxy = build_class('NoneType')
+ proxy = build_class("NoneType")
proxy.parent = astroid_builtin
elif cls is type(NotImplemented):
- proxy = build_class('NotImplementedType')
+ proxy = build_class("NotImplementedType")
proxy.parent = astroid_builtin
else:
proxy = astroid_builtin.getattr(cls.__name__)[0]
@@ -394,38 +407,49 @@ def _astroid_bootstrapping(astroid_builtin=None):
else:
_CONST_PROXY[cls] = proxy
+
_astroid_bootstrapping()
# TODO : find a nicer way to handle this situation;
def _set_proxied(const):
return _CONST_PROXY[const.value.__class__]
+
+
nodes.Const._proxied = property(_set_proxied)
-_GeneratorType = nodes.ClassDef(types.GeneratorType.__name__, types.GeneratorType.__doc__)
+_GeneratorType = nodes.ClassDef(
+ types.GeneratorType.__name__, types.GeneratorType.__doc__
+)
_GeneratorType.parent = MANAGER.astroid_cache[builtins.__name__]
bases.Generator._proxied = _GeneratorType
Astroid_BUILDER.object_build(bases.Generator._proxied, types.GeneratorType)
-if hasattr(types, 'AsyncGeneratorType'):
+if hasattr(types, "AsyncGeneratorType"):
# pylint: disable=no-member; AsyncGeneratorType
_AsyncGeneratorType = nodes.ClassDef(
- types.AsyncGeneratorType.__name__,
- types.AsyncGeneratorType.__doc__
+ types.AsyncGeneratorType.__name__, types.AsyncGeneratorType.__doc__
)
_AsyncGeneratorType.parent = MANAGER.astroid_cache[builtins.__name__]
bases.AsyncGenerator._proxied = _AsyncGeneratorType
Astroid_BUILDER.object_build(
- bases.AsyncGenerator._proxied,
- types.AsyncGeneratorType
+ bases.AsyncGenerator._proxied, types.AsyncGeneratorType
)
- # pylint: enable=no-member
+# pylint: enable=no-member
_builtins = MANAGER.astroid_cache[builtins.__name__]
-BUILTIN_TYPES = (types.GetSetDescriptorType, types.GeneratorType,
- types.MemberDescriptorType, type(None), type(NotImplemented),
- types.FunctionType, types.MethodType,
- types.BuiltinFunctionType, types.ModuleType, types.TracebackType)
+BUILTIN_TYPES = (
+ types.GetSetDescriptorType,
+ types.GeneratorType,
+ types.MemberDescriptorType,
+ type(None),
+ type(NotImplemented),
+ types.FunctionType,
+ types.MethodType,
+ types.BuiltinFunctionType,
+ types.ModuleType,
+ types.TracebackType,
+)
for _type in BUILTIN_TYPES:
if _type.__name__ not in _builtins:
cls = nodes.ClassDef(_type.__name__, _type.__doc__)
diff --git a/astroid/rebuilder.py b/astroid/rebuilder.py
index 3cac7083..4a2d52ab 100644
--- a/astroid/rebuilder.py
+++ b/astroid/rebuilder.py
@@ -27,18 +27,16 @@ from astroid._ast import _parse, _get_parser_module, parse_function_type_comment
from astroid import nodes
-CONST_NAME_TRANSFORMS = {'None': None,
- 'True': True,
- 'False': False,
- }
-
-REDIRECT = {'arguments': 'Arguments',
- 'comprehension': 'Comprehension',
- "ListCompFor": 'Comprehension',
- "GenExprFor": 'Comprehension',
- 'excepthandler': 'ExceptHandler',
- 'keyword': 'Keyword',
- }
+CONST_NAME_TRANSFORMS = {"None": None, "True": True, "False": False}
+
+REDIRECT = {
+ "arguments": "Arguments",
+ "comprehension": "Comprehension",
+ "ListCompFor": "Comprehension",
+ "GenExprFor": "Comprehension",
+ "excepthandler": "ExceptHandler",
+ "keyword": "Keyword",
+}
PY3 = sys.version_info >= (3, 0)
PY34 = sys.version_info >= (3, 4)
PY37 = sys.version_info >= (3, 7)
@@ -46,52 +44,44 @@ PY37 = sys.version_info >= (3, 7)
def _binary_operators_from_module(module):
binary_operators = {
- module.Add: '+',
- module.BitAnd: '&',
- module.BitOr: '|',
- module.BitXor: '^',
- module.Div: '/',
- module.FloorDiv: '//',
- module.Mod: '%',
- module.Mult: '*',
- module.Pow: '**',
- module.Sub: '-',
- module.LShift: '<<',
- module.RShift: '>>',
+ module.Add: "+",
+ module.BitAnd: "&",
+ module.BitOr: "|",
+ module.BitXor: "^",
+ module.Div: "/",
+ module.FloorDiv: "//",
+ module.Mod: "%",
+ module.Mult: "*",
+ module.Pow: "**",
+ module.Sub: "-",
+ module.LShift: "<<",
+ module.RShift: ">>",
}
if sys.version_info >= (3, 5):
- binary_operators[module.MatMult] = '@'
+ binary_operators[module.MatMult] = "@"
return binary_operators
def _bool_operators_from_module(module):
- return {
- module.And: 'and',
- module.Or: 'or',
- }
+ return {module.And: "and", module.Or: "or"}
def _unary_operators_from_module(module):
- return {
- module.UAdd: '+',
- module.USub: '-',
- module.Not: 'not',
- module.Invert: '~',
- }
+ return {module.UAdd: "+", module.USub: "-", module.Not: "not", module.Invert: "~"}
def _compare_operators_from_module(module):
return {
- module.Eq: '==',
- module.Gt: '>',
- module.GtE: '>=',
- module.In: 'in',
- module.Is: 'is',
- module.IsNot: 'is not',
- module.Lt: '<',
- module.LtE: '<=',
- module.NotEq: '!=',
- module.NotIn: 'not in',
+ module.Eq: "==",
+ module.Gt: ">",
+ module.GtE: ">=",
+ module.In: "in",
+ module.Is: "is",
+ module.IsNot: "is not",
+ module.Lt: "<",
+ module.LtE: "<=",
+ module.NotEq: "!=",
+ module.NotIn: "not in",
}
@@ -104,8 +94,7 @@ def _contexts_from_module(module):
}
-def _visit_or_none(node, attr, visitor, parent, visit='visit',
- **kws):
+def _visit_or_none(node, attr, visitor, parent, visit="visit", **kws):
"""If the given node has an attribute, visits the attribute, and
otherwise returns None.
@@ -137,12 +126,14 @@ class TreeRebuilder:
def _get_doc(self, node):
try:
- if PY37 and hasattr(node, 'docstring'):
+ if PY37 and hasattr(node, "docstring"):
doc = node.docstring
return node, doc
- if (node.body
- and isinstance(node.body[0], self._parser_module.Expr)
- and isinstance(node.body[0].value, self._parser_module.Str)):
+ if (
+ node.body
+ and isinstance(node.body[0], self._parser_module.Expr)
+ and isinstance(node.body[0].value, self._parser_module.Str)
+ ):
doc = node.body[0].value.s
node.body = node.body[1:]
return node, doc
@@ -156,9 +147,14 @@ class TreeRebuilder:
def visit_module(self, node, modname, modpath, package):
"""visit a Module node by returning a fresh instance of it"""
node, doc = self._get_doc(node)
- newnode = nodes.Module(name=modname, doc=doc, file=modpath,
- path=[modpath],
- package=package, parent=None)
+ newnode = nodes.Module(
+ name=modname,
+ doc=doc,
+ file=modpath,
+ path=[modpath],
+ package=package,
+ parent=None,
+ )
newnode.postinit([self.visit(child, newnode) for child in node.body])
return newnode
@@ -168,7 +164,7 @@ class TreeRebuilder:
visit_method = self._visit_meths[cls]
else:
cls_name = cls.__name__
- visit_name = 'visit_' + REDIRECT.get(cls_name, cls_name).lower()
+ visit_name = "visit_" + REDIRECT.get(cls_name, cls_name).lower()
visit_method = getattr(self, visit_name)
self._visit_meths[cls] = visit_method
return visit_method(node, parent)
@@ -184,14 +180,13 @@ class TreeRebuilder:
"""visit an Arguments node by returning a fresh instance of it"""
vararg, kwarg = node.vararg, node.kwarg
if PY34:
- newnode = nodes.Arguments(vararg.arg if vararg else None,
- kwarg.arg if kwarg else None,
- parent)
+ newnode = nodes.Arguments(
+ vararg.arg if vararg else None, kwarg.arg if kwarg else None, parent
+ )
else:
newnode = nodes.Arguments(vararg, kwarg, parent)
args = [self.visit(child, newnode) for child in node.args]
- defaults = [self.visit(child, newnode)
- for child in node.defaults]
+ defaults = [self.visit(child, newnode) for child in node.defaults]
varargannotation = None
kwargannotation = None
# change added in 82732 (7c5c678e4164), vararg and kwarg
@@ -199,22 +194,23 @@ class TreeRebuilder:
if vararg:
if PY34:
if node.vararg.annotation:
- varargannotation = self.visit(node.vararg.annotation,
- newnode)
+ varargannotation = self.visit(node.vararg.annotation, newnode)
vararg = vararg.arg
if kwarg:
if PY34:
if node.kwarg.annotation:
- kwargannotation = self.visit(node.kwarg.annotation,
- newnode)
+ kwargannotation = self.visit(node.kwarg.annotation, newnode)
kwarg = kwarg.arg
if PY3:
- kwonlyargs = [self.visit(child, newnode) for child
- in node.kwonlyargs]
- kw_defaults = [self.visit(child, newnode) if child else
- None for child in node.kw_defaults]
- annotations = [self.visit(arg.annotation, newnode) if
- arg.annotation else None for arg in node.args]
+ kwonlyargs = [self.visit(child, newnode) for child in node.kwonlyargs]
+ kw_defaults = [
+ self.visit(child, newnode) if child else None
+ for child in node.kw_defaults
+ ]
+ annotations = [
+ self.visit(arg.annotation, newnode) if arg.annotation else None
+ for arg in node.args
+ ]
kwonlyargs_annotations = [
self.visit(arg.annotation, newnode) if arg.annotation else None
for arg in node.kwonlyargs
@@ -233,7 +229,7 @@ class TreeRebuilder:
annotations=annotations,
kwonlyargs_annotations=kwonlyargs_annotations,
varargannotation=varargannotation,
- kwargannotation=kwargannotation
+ kwargannotation=kwargannotation,
)
# save argument names in locals:
if vararg:
@@ -253,7 +249,7 @@ class TreeRebuilder:
return newnode
def check_type_comment(self, node):
- type_comment = getattr(node, 'type_comment', None)
+ type_comment = getattr(node, "type_comment", None)
if not type_comment:
return None
@@ -270,7 +266,7 @@ class TreeRebuilder:
return type_object.value
def check_function_type_comment(self, node):
- type_comment = getattr(node, 'type_comment', None)
+ type_comment = getattr(node, "type_comment", None)
if not type_comment:
return None
@@ -281,7 +277,9 @@ class TreeRebuilder:
return None
returns = None
- argtypes = [self.visit(elem, node) for elem in (type_comment_ast.argtypes or [])]
+ argtypes = [
+ self.visit(elem, node) for elem in (type_comment_ast.argtypes or [])
+ ]
if type_comment_ast.returns:
returns = self.visit(type_comment_ast.returns, node)
@@ -299,18 +297,27 @@ class TreeRebuilder:
return newnode
def visit_assignname(self, node, parent, node_name=None):
- '''visit a node and return a AssignName node'''
- newnode = nodes.AssignName(node_name, getattr(node, 'lineno', None),
- getattr(node, 'col_offset', None), parent)
+ """visit a node and return a AssignName node"""
+ newnode = nodes.AssignName(
+ node_name,
+ getattr(node, "lineno", None),
+ getattr(node, "col_offset", None),
+ parent,
+ )
self._save_assignment(newnode)
return newnode
def visit_augassign(self, node, parent):
"""visit a AugAssign node by returning a fresh instance of it"""
- newnode = nodes.AugAssign(self._bin_op_classes[type(node.op)] + "=",
- node.lineno, node.col_offset, parent)
- newnode.postinit(self.visit(node.target, newnode),
- self.visit(node.value, newnode))
+ newnode = nodes.AugAssign(
+ self._bin_op_classes[type(node.op)] + "=",
+ node.lineno,
+ node.col_offset,
+ parent,
+ )
+ newnode.postinit(
+ self.visit(node.target, newnode), self.visit(node.value, newnode)
+ )
return newnode
def visit_repr(self, node, parent):
@@ -321,112 +328,129 @@ class TreeRebuilder:
def visit_binop(self, node, parent):
"""visit a BinOp node by returning a fresh instance of it"""
- newnode = nodes.BinOp(self._bin_op_classes[type(node.op)],
- node.lineno, node.col_offset, parent)
- newnode.postinit(self.visit(node.left, newnode),
- self.visit(node.right, newnode))
+ newnode = nodes.BinOp(
+ self._bin_op_classes[type(node.op)], node.lineno, node.col_offset, parent
+ )
+ newnode.postinit(
+ self.visit(node.left, newnode), self.visit(node.right, newnode)
+ )
return newnode
def visit_boolop(self, node, parent):
"""visit a BoolOp node by returning a fresh instance of it"""
- newnode = nodes.BoolOp(self._bool_op_classes[type(node.op)],
- node.lineno, node.col_offset, parent)
- newnode.postinit([self.visit(child, newnode)
- for child in node.values])
+ newnode = nodes.BoolOp(
+ self._bool_op_classes[type(node.op)], node.lineno, node.col_offset, parent
+ )
+ newnode.postinit([self.visit(child, newnode) for child in node.values])
return newnode
def visit_break(self, node, parent):
"""visit a Break node by returning a fresh instance of it"""
- return nodes.Break(getattr(node, 'lineno', None),
- getattr(node, 'col_offset', None),
- parent)
+ return nodes.Break(
+ getattr(node, "lineno", None), getattr(node, "col_offset", None), parent
+ )
def visit_call(self, node, parent):
"""visit a CallFunc node by returning a fresh instance of it"""
newnode = nodes.Call(node.lineno, node.col_offset, parent)
- starargs = _visit_or_none(node, 'starargs', self, newnode)
- kwargs = _visit_or_none(node, 'kwargs', self, newnode)
- args = [self.visit(child, newnode)
- for child in node.args]
+ starargs = _visit_or_none(node, "starargs", self, newnode)
+ kwargs = _visit_or_none(node, "kwargs", self, newnode)
+ args = [self.visit(child, newnode) for child in node.args]
if node.keywords:
- keywords = [self.visit(child, newnode)
- for child in node.keywords]
+ keywords = [self.visit(child, newnode) for child in node.keywords]
else:
keywords = None
if starargs:
- new_starargs = nodes.Starred(col_offset=starargs.col_offset,
- lineno=starargs.lineno,
- parent=starargs.parent)
+ new_starargs = nodes.Starred(
+ col_offset=starargs.col_offset,
+ lineno=starargs.lineno,
+ parent=starargs.parent,
+ )
new_starargs.postinit(value=starargs)
args.append(new_starargs)
if kwargs:
- new_kwargs = nodes.Keyword(arg=None, col_offset=kwargs.col_offset,
- lineno=kwargs.lineno,
- parent=kwargs.parent)
+ new_kwargs = nodes.Keyword(
+ arg=None,
+ col_offset=kwargs.col_offset,
+ lineno=kwargs.lineno,
+ parent=kwargs.parent,
+ )
new_kwargs.postinit(value=kwargs)
if keywords:
keywords.append(new_kwargs)
else:
keywords = [new_kwargs]
- newnode.postinit(self.visit(node.func, newnode),
- args, keywords)
+ newnode.postinit(self.visit(node.func, newnode), args, keywords)
return newnode
def visit_classdef(self, node, parent, newstyle=None):
"""visit a ClassDef node to become astroid"""
node, doc = self._get_doc(node)
- newnode = nodes.ClassDef(node.name, doc, node.lineno,
- node.col_offset, parent)
+ newnode = nodes.ClassDef(node.name, doc, node.lineno, node.col_offset, parent)
metaclass = None
if PY3:
for keyword in node.keywords:
- if keyword.arg == 'metaclass':
+ if keyword.arg == "metaclass":
metaclass = self.visit(keyword, newnode).value
break
if node.decorator_list:
decorators = self.visit_decorators(node, newnode)
else:
decorators = None
- newnode.postinit([self.visit(child, newnode)
- for child in node.bases],
- [self.visit(child, newnode)
- for child in node.body],
- decorators, newstyle, metaclass,
- [self.visit(kwd, newnode) for kwd in node.keywords
- if kwd.arg != 'metaclass'] if PY3 else [])
+ newnode.postinit(
+ [self.visit(child, newnode) for child in node.bases],
+ [self.visit(child, newnode) for child in node.body],
+ decorators,
+ newstyle,
+ metaclass,
+ [
+ self.visit(kwd, newnode)
+ for kwd in node.keywords
+ if kwd.arg != "metaclass"
+ ]
+ if PY3
+ else [],
+ )
return newnode
def visit_const(self, node, parent):
"""visit a Const node by returning a fresh instance of it"""
- return nodes.Const(node.value,
- getattr(node, 'lineno', None),
- getattr(node, 'col_offset', None), parent)
+ return nodes.Const(
+ node.value,
+ getattr(node, "lineno", None),
+ getattr(node, "col_offset", None),
+ parent,
+ )
def visit_continue(self, node, parent):
"""visit a Continue node by returning a fresh instance of it"""
- return nodes.Continue(getattr(node, 'lineno', None),
- getattr(node, 'col_offset', None),
- parent)
+ return nodes.Continue(
+ getattr(node, "lineno", None), getattr(node, "col_offset", None), parent
+ )
def visit_compare(self, node, parent):
"""visit a Compare node by returning a fresh instance of it"""
newnode = nodes.Compare(node.lineno, node.col_offset, parent)
- newnode.postinit(self.visit(node.left, newnode),
- [(self._cmp_op_classes[op.__class__],
- self.visit(expr, newnode))
- for (op, expr) in zip(node.ops, node.comparators)])
+ newnode.postinit(
+ self.visit(node.left, newnode),
+ [
+ (self._cmp_op_classes[op.__class__], self.visit(expr, newnode))
+ for (op, expr) in zip(node.ops, node.comparators)
+ ],
+ )
return newnode
def visit_comprehension(self, node, parent):
"""visit a Comprehension node by returning a fresh instance of it"""
newnode = nodes.Comprehension(parent)
- newnode.postinit(self.visit(node.target, newnode),
- self.visit(node.iter, newnode),
- [self.visit(child, newnode)
- for child in node.ifs],
- getattr(node, 'is_async', None))
+ newnode.postinit(
+ self.visit(node.target, newnode),
+ self.visit(node.iter, newnode),
+ [self.visit(child, newnode) for child in node.ifs],
+ getattr(node, "is_async", None),
+ )
return newnode
def visit_decorators(self, node, parent):
@@ -434,15 +458,13 @@ class TreeRebuilder:
# /!\ node is actually a _ast.FunctionDef node while
# parent is an astroid.nodes.FunctionDef node
newnode = nodes.Decorators(node.lineno, node.col_offset, parent)
- newnode.postinit([self.visit(child, newnode)
- for child in node.decorator_list])
+ newnode.postinit([self.visit(child, newnode) for child in node.decorator_list])
return newnode
def visit_delete(self, node, parent):
"""visit a Delete node by returning a fresh instance of it"""
newnode = nodes.Delete(node.lineno, node.col_offset, parent)
- newnode.postinit([self.visit(child, newnode)
- for child in node.targets])
+ newnode.postinit([self.visit(child, newnode) for child in node.targets])
return newnode
def _visit_dict_items(self, node, parent, newnode):
@@ -450,9 +472,9 @@ class TreeRebuilder:
rebuilt_value = self.visit(value, newnode)
if not key:
# Python 3.5 and extended unpacking
- rebuilt_key = nodes.DictUnpack(rebuilt_value.lineno,
- rebuilt_value.col_offset,
- parent)
+ rebuilt_key = nodes.DictUnpack(
+ rebuilt_value.lineno, rebuilt_value.col_offset, parent
+ )
else:
rebuilt_key = self.visit(key, newnode)
yield rebuilt_key, rebuilt_value
@@ -467,10 +489,11 @@ class TreeRebuilder:
def visit_dictcomp(self, node, parent):
"""visit a DictComp node by returning a fresh instance of it"""
newnode = nodes.DictComp(node.lineno, node.col_offset, parent)
- newnode.postinit(self.visit(node.key, newnode),
- self.visit(node.value, newnode),
- [self.visit(child, newnode)
- for child in node.generators])
+ newnode.postinit(
+ self.visit(node.key, newnode),
+ self.visit(node.value, newnode),
+ [self.visit(child, newnode) for child in node.generators],
+ )
return newnode
def visit_expr(self, node, parent):
@@ -482,40 +505,42 @@ class TreeRebuilder:
# Not used in Python 3.8+.
def visit_ellipsis(self, node, parent):
"""visit an Ellipsis node by returning a fresh instance of it"""
- return nodes.Ellipsis(getattr(node, 'lineno', None),
- getattr(node, 'col_offset', None), parent)
-
+ return nodes.Ellipsis(
+ getattr(node, "lineno", None), getattr(node, "col_offset", None), parent
+ )
def visit_emptynode(self, node, parent):
"""visit an EmptyNode node by returning a fresh instance of it"""
- return nodes.EmptyNode(getattr(node, 'lineno', None),
- getattr(node, 'col_offset', None), parent)
-
+ return nodes.EmptyNode(
+ getattr(node, "lineno", None), getattr(node, "col_offset", None), parent
+ )
def visit_excepthandler(self, node, parent):
"""visit an ExceptHandler node by returning a fresh instance of it"""
newnode = nodes.ExceptHandler(node.lineno, node.col_offset, parent)
# /!\ node.name can be a tuple
- newnode.postinit(_visit_or_none(node, 'type', self, newnode),
- _visit_or_none(node, 'name', self, newnode),
- [self.visit(child, newnode)
- for child in node.body])
+ newnode.postinit(
+ _visit_or_none(node, "type", self, newnode),
+ _visit_or_none(node, "name", self, newnode),
+ [self.visit(child, newnode) for child in node.body],
+ )
return newnode
def visit_exec(self, node, parent):
"""visit an Exec node by returning a fresh instance of it"""
newnode = nodes.Exec(node.lineno, node.col_offset, parent)
- newnode.postinit(self.visit(node.body, newnode),
- _visit_or_none(node, 'globals', self, newnode),
- _visit_or_none(node, 'locals', self, newnode))
+ newnode.postinit(
+ self.visit(node.body, newnode),
+ _visit_or_none(node, "globals", self, newnode),
+ _visit_or_none(node, "locals", self, newnode),
+ )
return newnode
# Not used in Python 3.8+.
def visit_extslice(self, node, parent):
"""visit an ExtSlice node by returning a fresh instance of it"""
newnode = nodes.ExtSlice(parent=parent)
- newnode.postinit([self.visit(dim, newnode)
- for dim in node.dims])
+ newnode.postinit([self.visit(dim, newnode) for dim in node.dims])
return newnode
def _visit_for(self, cls, node, parent):
@@ -537,9 +562,14 @@ class TreeRebuilder:
def visit_importfrom(self, node, parent):
"""visit an ImportFrom node by returning a fresh instance of it"""
names = [(alias.name, alias.asname) for alias in node.names]
- newnode = nodes.ImportFrom(node.module or '', names, node.level or None,
- getattr(node, 'lineno', None),
- getattr(node, 'col_offset', None), parent)
+ newnode = nodes.ImportFrom(
+ node.module or "",
+ names,
+ node.level or None,
+ getattr(node, "lineno", None),
+ getattr(node, "col_offset", None),
+ parent,
+ )
# store From names to add them to locals after building
self._import_from_nodes.append(newnode)
return newnode
@@ -548,8 +578,7 @@ class TreeRebuilder:
"""visit an FunctionDef node to become astroid"""
self._global_names.append({})
node, doc = self._get_doc(node)
- newnode = cls(node.name, doc, node.lineno,
- node.col_offset, parent)
+ newnode = cls(node.name, doc, node.lineno, node.col_offset, parent)
if node.decorator_list:
decorators = self.visit_decorators(node, newnode)
else:
@@ -580,9 +609,10 @@ class TreeRebuilder:
def visit_generatorexp(self, node, parent):
"""visit a GeneratorExp node by returning a fresh instance of it"""
newnode = nodes.GeneratorExp(node.lineno, node.col_offset, parent)
- newnode.postinit(self.visit(node.elt, newnode),
- [self.visit(child, newnode)
- for child in node.generators])
+ newnode.postinit(
+ self.visit(node.elt, newnode),
+ [self.visit(child, newnode) for child in node.generators],
+ )
return newnode
def visit_attribute(self, node, parent):
@@ -591,25 +621,26 @@ class TreeRebuilder:
if context == astroid.Del:
# FIXME : maybe we should reintroduce and visit_delattr ?
# for instance, deactivating assign_ctx
- newnode = nodes.DelAttr(node.attr, node.lineno, node.col_offset,
- parent)
+ newnode = nodes.DelAttr(node.attr, node.lineno, node.col_offset, parent)
elif context == astroid.Store:
- newnode = nodes.AssignAttr(node.attr, node.lineno, node.col_offset,
- parent)
+ newnode = nodes.AssignAttr(node.attr, node.lineno, node.col_offset, parent)
# Prohibit a local save if we are in an ExceptHandler.
if not isinstance(parent, astroid.ExceptHandler):
self._delayed_assattr.append(newnode)
else:
- newnode = nodes.Attribute(node.attr, node.lineno, node.col_offset,
- parent)
+ newnode = nodes.Attribute(node.attr, node.lineno, node.col_offset, parent)
newnode.postinit(self.visit(node.value, newnode))
return newnode
def visit_global(self, node, parent):
"""visit a Global node to become astroid"""
- newnode = nodes.Global(node.names, getattr(node, 'lineno', None),
- getattr(node, 'col_offset', None), parent)
- if self._global_names: # global at the module level, no effect
+ newnode = nodes.Global(
+ node.names,
+ getattr(node, "lineno", None),
+ getattr(node, "col_offset", None),
+ parent,
+ )
+ if self._global_names: # global at the module level, no effect
for name in node.names:
self._global_names[-1].setdefault(name, []).append(newnode)
return newnode
@@ -617,30 +648,36 @@ class TreeRebuilder:
def visit_if(self, node, parent):
"""visit an If node by returning a fresh instance of it"""
newnode = nodes.If(node.lineno, node.col_offset, parent)
- newnode.postinit(self.visit(node.test, newnode),
- [self.visit(child, newnode)
- for child in node.body],
- [self.visit(child, newnode)
- for child in node.orelse])
+ newnode.postinit(
+ self.visit(node.test, newnode),
+ [self.visit(child, newnode) for child in node.body],
+ [self.visit(child, newnode) for child in node.orelse],
+ )
return newnode
def visit_ifexp(self, node, parent):
"""visit a IfExp node by returning a fresh instance of it"""
newnode = nodes.IfExp(node.lineno, node.col_offset, parent)
- newnode.postinit(self.visit(node.test, newnode),
- self.visit(node.body, newnode),
- self.visit(node.orelse, newnode))
+ newnode.postinit(
+ self.visit(node.test, newnode),
+ self.visit(node.body, newnode),
+ self.visit(node.orelse, newnode),
+ )
return newnode
def visit_import(self, node, parent):
"""visit a Import node by returning a fresh instance of it"""
names = [(alias.name, alias.asname) for alias in node.names]
- newnode = nodes.Import(names, getattr(node, 'lineno', None),
- getattr(node, 'col_offset', None), parent)
+ newnode = nodes.Import(
+ names,
+ getattr(node, "lineno", None),
+ getattr(node, "col_offset", None),
+ parent,
+ )
# save import names in parent's locals:
for (name, asname) in newnode.names:
name = asname or name
- parent.set_local(name.split('.')[0], newnode)
+ parent.set_local(name.split(".")[0], newnode)
return newnode
# Not used in Python 3.8+.
@@ -659,27 +696,25 @@ class TreeRebuilder:
def visit_lambda(self, node, parent):
"""visit a Lambda node by returning a fresh instance of it"""
newnode = nodes.Lambda(node.lineno, node.col_offset, parent)
- newnode.postinit(self.visit(node.args, newnode),
- self.visit(node.body, newnode))
+ newnode.postinit(self.visit(node.args, newnode), self.visit(node.body, newnode))
return newnode
def visit_list(self, node, parent):
"""visit a List node by returning a fresh instance of it"""
context = self._get_context(node)
- newnode = nodes.List(ctx=context,
- lineno=node.lineno,
- col_offset=node.col_offset,
- parent=parent)
- newnode.postinit([self.visit(child, newnode)
- for child in node.elts])
+ newnode = nodes.List(
+ ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent
+ )
+ newnode.postinit([self.visit(child, newnode) for child in node.elts])
return newnode
def visit_listcomp(self, node, parent):
"""visit a ListComp node by returning a fresh instance of it"""
newnode = nodes.ListComp(node.lineno, node.col_offset, parent)
- newnode.postinit(self.visit(node.elt, newnode),
- [self.visit(child, newnode)
- for child in node.generators])
+ newnode.postinit(
+ self.visit(node.elt, newnode),
+ [self.visit(child, newnode) for child in node.generators],
+ )
return newnode
def visit_name(self, node, parent):
@@ -688,40 +723,54 @@ class TreeRebuilder:
# True and False can be assigned to something in py2x, so we have to
# check first the context.
if context == astroid.Del:
- newnode = nodes.DelName(node.id, node.lineno, node.col_offset,
- parent)
+ newnode = nodes.DelName(node.id, node.lineno, node.col_offset, parent)
elif context == astroid.Store:
- newnode = nodes.AssignName(node.id, node.lineno, node.col_offset,
- parent)
+ newnode = nodes.AssignName(node.id, node.lineno, node.col_offset, parent)
elif node.id in CONST_NAME_TRANSFORMS:
- newnode = nodes.Const(CONST_NAME_TRANSFORMS[node.id],
- getattr(node, 'lineno', None),
- getattr(node, 'col_offset', None), parent)
+ newnode = nodes.Const(
+ CONST_NAME_TRANSFORMS[node.id],
+ getattr(node, "lineno", None),
+ getattr(node, "col_offset", None),
+ parent,
+ )
return newnode
else:
newnode = nodes.Name(node.id, node.lineno, node.col_offset, parent)
# XXX REMOVE me :
- if context in (astroid.Del, astroid.Store): # 'Aug' ??
+ if context in (astroid.Del, astroid.Store): # 'Aug' ??
self._save_assignment(newnode)
return newnode
def visit_constant(self, node, parent):
"""visit a Constant node by returning a fresh instance of Const"""
- return nodes.Const(node.value, getattr(node, 'lineno', None),
- getattr(node, 'col_offset', None), parent)
+ return nodes.Const(
+ node.value,
+ getattr(node, "lineno", None),
+ getattr(node, "col_offset", None),
+ parent,
+ )
# Not used in Python 3.8+.
def visit_str(self, node, parent):
"""visit a String/Bytes node by returning a fresh instance of Const"""
- return nodes.Const(node.s, getattr(node, 'lineno', None),
- getattr(node, 'col_offset', None), parent)
+ return nodes.Const(
+ node.s,
+ getattr(node, "lineno", None),
+ getattr(node, "col_offset", None),
+ parent,
+ )
+
visit_bytes = visit_str
# Not used in Python 3.8+.
def visit_num(self, node, parent):
"""visit a Num node by returning a fresh instance of Const"""
- return nodes.Const(node.n, getattr(node, 'lineno', None),
- getattr(node, 'col_offset', None), parent)
+ return nodes.Const(
+ node.n,
+ getattr(node, "lineno", None),
+ getattr(node, "col_offset", None),
+ parent,
+ )
def visit_pass(self, node, parent):
"""visit a Pass node by returning a fresh instance of it"""
@@ -730,18 +779,21 @@ class TreeRebuilder:
def visit_print(self, node, parent):
"""visit a Print node by returning a fresh instance of it"""
newnode = nodes.Print(node.nl, node.lineno, node.col_offset, parent)
- newnode.postinit(_visit_or_none(node, 'dest', self, newnode),
- [self.visit(child, newnode)
- for child in node.values])
+ newnode.postinit(
+ _visit_or_none(node, "dest", self, newnode),
+ [self.visit(child, newnode) for child in node.values],
+ )
return newnode
def visit_raise(self, node, parent):
"""visit a Raise node by returning a fresh instance of it"""
newnode = nodes.Raise(node.lineno, node.col_offset, parent)
# pylint: disable=too-many-function-args
- newnode.postinit(_visit_or_none(node, 'type', self, newnode),
- _visit_or_none(node, 'inst', self, newnode),
- _visit_or_none(node, 'tback', self, newnode))
+ newnode.postinit(
+ _visit_or_none(node, "type", self, newnode),
+ _visit_or_none(node, "inst", self, newnode),
+ _visit_or_none(node, "tback", self, newnode),
+ )
return newnode
def visit_return(self, node, parent):
@@ -754,83 +806,86 @@ class TreeRebuilder:
def visit_set(self, node, parent):
"""visit a Set node by returning a fresh instance of it"""
newnode = nodes.Set(node.lineno, node.col_offset, parent)
- newnode.postinit([self.visit(child, newnode)
- for child in node.elts])
+ newnode.postinit([self.visit(child, newnode) for child in node.elts])
return newnode
def visit_setcomp(self, node, parent):
"""visit a SetComp node by returning a fresh instance of it"""
newnode = nodes.SetComp(node.lineno, node.col_offset, parent)
- newnode.postinit(self.visit(node.elt, newnode),
- [self.visit(child, newnode)
- for child in node.generators])
+ newnode.postinit(
+ self.visit(node.elt, newnode),
+ [self.visit(child, newnode) for child in node.generators],
+ )
return newnode
def visit_slice(self, node, parent):
"""visit a Slice node by returning a fresh instance of it"""
newnode = nodes.Slice(parent=parent)
- newnode.postinit(_visit_or_none(node, 'lower', self, newnode),
- _visit_or_none(node, 'upper', self, newnode),
- _visit_or_none(node, 'step', self, newnode))
+ newnode.postinit(
+ _visit_or_none(node, "lower", self, newnode),
+ _visit_or_none(node, "upper", self, newnode),
+ _visit_or_none(node, "step", self, newnode),
+ )
return newnode
def visit_subscript(self, node, parent):
"""visit a Subscript node by returning a fresh instance of it"""
context = self._get_context(node)
- newnode = nodes.Subscript(ctx=context,
- lineno=node.lineno,
- col_offset=node.col_offset,
- parent=parent)
- newnode.postinit(self.visit(node.value, newnode),
- self.visit(node.slice, newnode))
+ newnode = nodes.Subscript(
+ ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent
+ )
+ newnode.postinit(
+ self.visit(node.value, newnode), self.visit(node.slice, newnode)
+ )
return newnode
def visit_tryexcept(self, node, parent):
"""visit a TryExcept node by returning a fresh instance of it"""
newnode = nodes.TryExcept(node.lineno, node.col_offset, parent)
- newnode.postinit([self.visit(child, newnode)
- for child in node.body],
- [self.visit(child, newnode)
- for child in node.handlers],
- [self.visit(child, newnode)
- for child in node.orelse])
+ newnode.postinit(
+ [self.visit(child, newnode) for child in node.body],
+ [self.visit(child, newnode) for child in node.handlers],
+ [self.visit(child, newnode) for child in node.orelse],
+ )
return newnode
def visit_tryfinally(self, node, parent):
"""visit a TryFinally node by returning a fresh instance of it"""
newnode = nodes.TryFinally(node.lineno, node.col_offset, parent)
- newnode.postinit([self.visit(child, newnode)
- for child in node.body],
- [self.visit(n, newnode)
- for n in node.finalbody])
+ newnode.postinit(
+ [self.visit(child, newnode) for child in node.body],
+ [self.visit(n, newnode) for n in node.finalbody],
+ )
return newnode
def visit_tuple(self, node, parent):
"""visit a Tuple node by returning a fresh instance of it"""
context = self._get_context(node)
- newnode = nodes.Tuple(ctx=context,
- lineno=node.lineno,
- col_offset=node.col_offset,
- parent=parent)
- newnode.postinit([self.visit(child, newnode)
- for child in node.elts])
+ newnode = nodes.Tuple(
+ ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent
+ )
+ newnode.postinit([self.visit(child, newnode) for child in node.elts])
return newnode
def visit_unaryop(self, node, parent):
"""visit a UnaryOp node by returning a fresh instance of it"""
- newnode = nodes.UnaryOp(self._unary_op_classes[node.op.__class__],
- node.lineno, node.col_offset, parent)
+ newnode = nodes.UnaryOp(
+ self._unary_op_classes[node.op.__class__],
+ node.lineno,
+ node.col_offset,
+ parent,
+ )
newnode.postinit(self.visit(node.operand, newnode))
return newnode
def visit_while(self, node, parent):
"""visit a While node by returning a fresh instance of it"""
newnode = nodes.While(node.lineno, node.col_offset, parent)
- newnode.postinit(self.visit(node.test, newnode),
- [self.visit(child, newnode)
- for child in node.body],
- [self.visit(child, newnode)
- for child in node.orelse])
+ newnode.postinit(
+ self.visit(node.test, newnode),
+ [self.visit(child, newnode) for child in node.body],
+ [self.visit(child, newnode) for child in node.orelse],
+ )
return newnode
def visit_with(self, node, parent):
@@ -867,8 +922,12 @@ class TreeRebuilder3(TreeRebuilder):
# Not used in Python 3.8+.
def visit_nameconstant(self, node, parent):
# in Python 3.4 we have NameConstant for True / False / None
- return nodes.Const(node.value, getattr(node, 'lineno', None),
- getattr(node, 'col_offset', None), parent)
+ return nodes.Const(
+ node.value,
+ getattr(node, "lineno", None),
+ getattr(node, "col_offset", None),
+ parent,
+ )
def visit_excepthandler(self, node, parent):
"""visit an ExceptHandler node by returning a fresh instance of it"""
@@ -877,31 +936,38 @@ class TreeRebuilder3(TreeRebuilder):
name = self.visit_assignname(node, newnode, node.name)
else:
name = None
- newnode.postinit(_visit_or_none(node, 'type', self, newnode),
- name,
- [self.visit(child, newnode)
- for child in node.body])
+ newnode.postinit(
+ _visit_or_none(node, "type", self, newnode),
+ name,
+ [self.visit(child, newnode) for child in node.body],
+ )
return newnode
def visit_nonlocal(self, node, parent):
"""visit a Nonlocal node and return a new instance of it"""
- return nodes.Nonlocal(node.names, getattr(node, 'lineno', None),
- getattr(node, 'col_offset', None), parent)
+ return nodes.Nonlocal(
+ node.names,
+ getattr(node, "lineno", None),
+ getattr(node, "col_offset", None),
+ parent,
+ )
def visit_raise(self, node, parent):
"""visit a Raise node by returning a fresh instance of it"""
newnode = nodes.Raise(node.lineno, node.col_offset, parent)
# no traceback; anyway it is not used in Pylint
- newnode.postinit(_visit_or_none(node, 'exc', self, newnode),
- _visit_or_none(node, 'cause', self, newnode))
+ newnode.postinit(
+ _visit_or_none(node, "exc", self, newnode),
+ _visit_or_none(node, "cause", self, newnode),
+ )
return newnode
def visit_starred(self, node, parent):
"""visit a Starred node and return a new instance of it"""
context = self._get_context(node)
- newnode = nodes.Starred(ctx=context, lineno=node.lineno,
- col_offset=node.col_offset,
- parent=parent)
+ newnode = nodes.Starred(
+ ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent
+ )
newnode.postinit(self.visit(node.value, newnode))
return newnode
@@ -913,11 +979,8 @@ class TreeRebuilder3(TreeRebuilder):
if node.handlers:
body = [self.visit_tryexcept(node, newnode)]
else:
- body = [self.visit(child, newnode)
- for child in node.body]
- newnode.postinit(body,
- [self.visit(n, newnode)
- for n in node.finalbody])
+ body = [self.visit(child, newnode) for child in node.body]
+ newnode.postinit(body, [self.visit(n, newnode) for n in node.finalbody])
return newnode
elif node.handlers:
return self.visit_tryexcept(node, parent)
@@ -926,22 +989,25 @@ class TreeRebuilder3(TreeRebuilder):
def visit_annassign(self, node, parent):
"""visit an AnnAssign node by returning a fresh instance of it"""
newnode = nodes.AnnAssign(node.lineno, node.col_offset, parent)
- annotation = _visit_or_none(node, 'annotation', self, newnode)
- newnode.postinit(target=self.visit(node.target, newnode),
- annotation=annotation,
- simple=node.simple,
- value=_visit_or_none(node, 'value', self, newnode))
+ annotation = _visit_or_none(node, "annotation", self, newnode)
+ newnode.postinit(
+ target=self.visit(node.target, newnode),
+ annotation=annotation,
+ simple=node.simple,
+ value=_visit_or_none(node, "value", self, newnode),
+ )
return newnode
def _visit_with(self, cls, node, parent):
- if 'items' not in node._fields:
+ if "items" not in node._fields:
# python < 3.3
return super(TreeRebuilder3, self).visit_with(node, parent)
newnode = cls(node.lineno, node.col_offset, parent)
+
def visit_child(child):
expr = self.visit(child.context_expr, newnode)
- var = _visit_or_none(child, 'optional_vars', self, newnode)
+ var = _visit_or_none(child, "optional_vars", self, newnode)
return expr, var
type_annotation = self.check_type_comment(node)
@@ -962,8 +1028,9 @@ class TreeRebuilder3(TreeRebuilder):
return newnode
def visit_classdef(self, node, parent, newstyle=True):
- return super(TreeRebuilder3, self).visit_classdef(node, parent,
- newstyle=newstyle)
+ return super(TreeRebuilder3, self).visit_classdef(
+ node, parent, newstyle=newstyle
+ )
# Async structs added in Python 3.5
def visit_asyncfunctiondef(self, node, parent):
@@ -982,16 +1049,18 @@ class TreeRebuilder3(TreeRebuilder):
def visit_joinedstr(self, node, parent):
newnode = nodes.JoinedStr(node.lineno, node.col_offset, parent)
- newnode.postinit([self.visit(child, newnode)
- for child in node.values])
+ newnode.postinit([self.visit(child, newnode) for child in node.values])
return newnode
def visit_formattedvalue(self, node, parent):
newnode = nodes.FormattedValue(node.lineno, node.col_offset, parent)
- newnode.postinit(self.visit(node.value, newnode),
- node.conversion,
- _visit_or_none(node, 'format_spec', self, newnode))
+ newnode.postinit(
+ self.visit(node.value, newnode),
+ node.conversion,
+ _visit_or_none(node, "format_spec", self, newnode),
+ )
return newnode
+
if sys.version_info >= (3, 0):
TreeRebuilder = TreeRebuilder3
diff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py
index 6b440f81..290ebc22 100644
--- a/astroid/scoped_nodes.py
+++ b/astroid/scoped_nodes.py
@@ -47,7 +47,7 @@ from astroid import util
BUILTINS = builtins.__name__
-ITER_METHODS = ('__iter__', '__getitem__')
+ITER_METHODS = ("__iter__", "__getitem__")
def _c3_merge(sequences, cls, context):
@@ -58,15 +58,15 @@ def _c3_merge(sequences, cls, context):
"""
result = []
while True:
- sequences = [s for s in sequences if s] # purge empty sequences
+ sequences = [s for s in sequences if s] # purge empty sequences
if not sequences:
return result
- for s1 in sequences: # find merge candidates among seq heads
+ for s1 in sequences: # find merge candidates among seq heads
candidate = s1[0]
for s2 in sequences:
if candidate in s2[1:]:
candidate = None
- break # reject the current head, it appears later
+ break # reject the current head, it appears later
else:
break
if not candidate:
@@ -75,7 +75,10 @@ def _c3_merge(sequences, cls, context):
raise exceptions.InconsistentMroError(
message="Cannot create a consistent method resolution order "
"for MROs {mros} of class {cls!r}.",
- mros=sequences, cls=cls, context=context)
+ mros=sequences,
+ cls=cls,
+ context=context,
+ )
result.append(candidate)
# remove the chosen candidate
@@ -90,27 +93,32 @@ def _verify_duplicates_mro(sequences, cls, context):
names = [(node.lineno, node.qname()) for node in sequence if node.name]
if len(names) != len(set(names)):
raise exceptions.DuplicateBasesError(
- message='Duplicates found in MROs {mros} for {cls!r}.',
- mros=sequences, cls=cls, context=context)
+ message="Duplicates found in MROs {mros} for {cls!r}.",
+ mros=sequences,
+ cls=cls,
+ context=context,
+ )
def function_to_method(n, klass):
if isinstance(n, FunctionDef):
- if n.type == 'classmethod':
+ if n.type == "classmethod":
return bases.BoundMethod(n, klass)
- if n.type != 'staticmethod':
+ if n.type != "staticmethod":
return bases.UnboundMethod(n)
return n
MANAGER = manager.AstroidManager()
+
+
def builtin_lookup(name):
"""lookup a name into the builtin module
return the list of matching statements and the astroid for the builtin
module
"""
builtin_astroid = MANAGER.ast_from_module(builtins)
- if name == '__dict__':
+ if name == "__dict__":
return builtin_astroid, ()
try:
stmts = builtin_astroid.locals[name]
@@ -120,8 +128,7 @@ def builtin_lookup(name):
# TODO move this Mixin to mixins.py; problem: 'FunctionDef' in _scope_lookup
-class LocalsDictNodeNG(node_classes.LookupMixIn,
- node_classes.NodeNG):
+class LocalsDictNodeNG(node_classes.LookupMixIn, node_classes.NodeNG):
""" this class provides locals handling common to Module, FunctionDef
and ClassDef nodes, including a dict like interface for direct access
to locals information
@@ -146,7 +153,7 @@ class LocalsDictNodeNG(node_classes.LookupMixIn,
# pylint: disable=no-member; github.com/pycqa/astroid/issues/278
if self.parent is None:
return self.name
- return '%s.%s' % (self.parent.frame().qname(), self.name)
+ return "%s.%s" % (self.parent.frame().qname(), self.name)
def frame(self):
"""The first parent frame node.
@@ -175,14 +182,14 @@ class LocalsDictNodeNG(node_classes.LookupMixIn,
stmts = ()
if stmts:
return self, stmts
- if self.parent: # i.e. not Module
+ if self.parent: # i.e. not Module
# nested scope: if parent scope is a function, that's fine
# else jump to the module
pscope = self.parent.scope()
if not pscope.is_function:
pscope = pscope.root()
return pscope.scope_lookup(node, name)
- return builtin_lookup(name) # Module
+ return builtin_lookup(name) # Module
def set_local(self, name, stmt):
"""Define that the given name is declared in the given statement node.
@@ -195,7 +202,7 @@ class LocalsDictNodeNG(node_classes.LookupMixIn,
:param stmt: The statement that defines the given name.
:type stmt: NodeNG
"""
- #assert not stmt in self.locals.get(name, ()), (self, stmt)
+ # assert not stmt in self.locals.get(name, ()), (self, stmt)
self.locals.setdefault(name, []).append(stmt)
__setitem__ = set_local
@@ -219,7 +226,7 @@ class LocalsDictNodeNG(node_classes.LookupMixIn,
the given child node.
:type name: str or None
"""
- if name != '__class__':
+ if name != "__class__":
# add __class__ node as a child will cause infinite recursion later!
self._append_node(child_node)
self.set_local(name or child_node.name, child_node)
@@ -288,7 +295,8 @@ class Module(LocalsDictNodeNG):
>>> node.parent
<Module l.0 at 0x7f23b2e4eda0>
"""
- _astroid_fields = ('body',)
+
+ _astroid_fields = ("body",)
fromlineno = 0
"""The first line that this node appears on in the source code.
@@ -358,20 +366,33 @@ class Module(LocalsDictNodeNG):
"""
# names of module attributes available through the global scope
- scope_attrs = {'__name__', '__doc__', '__file__', '__path__', '__package__'}
+ scope_attrs = {"__name__", "__doc__", "__file__", "__path__", "__package__"}
"""The names of module attributes available through the global scope.
:type: str(str)
"""
- _other_fields = ('name', 'doc', 'file', 'path', 'package',
- 'pure_python', 'future_imports')
- _other_other_fields = ('locals', 'globals')
-
- def __init__(self, name, doc, file=None,
- path: Optional[List[str]] = None,
- package=None,
- parent=None, pure_python=True):
+ _other_fields = (
+ "name",
+ "doc",
+ "file",
+ "path",
+ "package",
+ "pure_python",
+ "future_imports",
+ )
+ _other_other_fields = ("locals", "globals")
+
+ def __init__(
+ self,
+ name,
+ doc,
+ file=None,
+ path: Optional[List[str]] = None,
+ package=None,
+ parent=None,
+ pure_python=True,
+ ):
"""
:param name: The name of the module.
:type name: str
@@ -412,6 +433,7 @@ class Module(LocalsDictNodeNG):
:type: list(NodeNG) or None
"""
self.future_imports = set()
+
# pylint: enable=redefined-builtin
def postinit(self, body=None):
@@ -426,7 +448,7 @@ class Module(LocalsDictNodeNG):
if self.file_bytes is not None:
return io.BytesIO(self.file_bytes)
if self.file is not None:
- stream = open(self.file, 'rb')
+ stream = open(self.file, "rb")
return stream
return None
@@ -479,7 +501,7 @@ class Module(LocalsDictNodeNG):
:returns: The name of the type.
:rtype: str
"""
- return '%s.module' % BUILTINS
+ return "%s.module" % BUILTINS
def display_type(self):
"""A human readable type of this node.
@@ -487,7 +509,7 @@ class Module(LocalsDictNodeNG):
:returns: The type of this node.
:rtype: str
"""
- return 'Module'
+ return "Module"
def getattr(self, name, context=None, ignore_locals=False):
result = []
@@ -502,15 +524,14 @@ class Module(LocalsDictNodeNG):
result = [self.import_module(name, relative_only=True)]
except (exceptions.AstroidBuildingError, SyntaxError) as exc:
raise exceptions.AttributeInferenceError(
- target=self,
- attribute=name,
- context=context,
+ target=self, attribute=name, context=context
) from exc
result = [n for n in result if not isinstance(n, node_classes.DelName)]
if result:
return result
- raise exceptions.AttributeInferenceError(target=self, attribute=name,
- context=context)
+ raise exceptions.AttributeInferenceError(
+ target=self, attribute=name, context=context
+ )
def igetattr(self, name, context=None):
"""Infer the possible values of the given variable.
@@ -526,14 +547,10 @@ class Module(LocalsDictNodeNG):
context = contextmod.copy_context(context)
context.lookupname = name
try:
- return bases._infer_stmts(self.getattr(name, context),
- context, frame=self)
+ return bases._infer_stmts(self.getattr(name, context), context, frame=self)
except exceptions.AttributeInferenceError as error:
raise exceptions.InferenceError(
- error.message,
- target=self,
- attribute=name,
- context=context,
+ error.message, target=self, attribute=name, context=context
) from error
def fully_defined(self):
@@ -545,7 +562,7 @@ class Module(LocalsDictNodeNG):
:returns: True if the module has been built from a .py file.
:rtype: bool
"""
- return self.file is not None and self.file.endswith('.py')
+ return self.file is not None and self.file.endswith(".py")
def statement(self):
"""The first parent node, including self, marked as statement node.
@@ -632,20 +649,19 @@ class Module(LocalsDictNodeNG):
if level:
if self.package:
level = level - 1
- if level and self.name.count('.') < level:
- raise exceptions.TooManyLevelsError(
- level=level, name=self.name)
+ if level and self.name.count(".") < level:
+ raise exceptions.TooManyLevelsError(level=level, name=self.name)
- package_name = self.name.rsplit('.', level)[0]
+ package_name = self.name.rsplit(".", level)[0]
elif self.package:
package_name = self.name
else:
- package_name = self.name.rsplit('.', 1)[0]
+ package_name = self.name.rsplit(".", 1)[0]
if package_name:
if not modname:
return package_name
- return '%s.%s' % (package_name, modname)
+ return "%s.%s" % (package_name, modname)
return modname
def wildcard_import_names(self):
@@ -659,9 +675,9 @@ class Module(LocalsDictNodeNG):
"""
# We separate the different steps of lookup in try/excepts
# to avoid catching too many Exceptions
- default = [name for name in self.keys() if not name.startswith('_')]
+ default = [name for name in self.keys() if not name.startswith("_")]
try:
- all_values = self['__all__']
+ all_values = self["__all__"]
except KeyError:
return default
@@ -683,8 +699,9 @@ class Module(LocalsDictNodeNG):
if not isinstance(explicit, (node_classes.Tuple, node_classes.List)):
return default
- str_const = lambda node: (isinstance(node, node_classes.Const) and
- isinstance(node.value, str))
+ str_const = lambda node: (
+ isinstance(node, node_classes.Const) and isinstance(node.value, str)
+ )
for node in explicit.elts:
if str_const(node):
inferred.append(node.value)
@@ -703,7 +720,7 @@ class Module(LocalsDictNodeNG):
:returns: The list of publc names.
:rtype: list(str)
"""
- return [name for name in self.keys() if not name.startswith('_')]
+ return [name for name in self.keys() if not name.startswith("_")]
def bool_value(self):
"""Determine the boolean value of this node.
@@ -720,6 +737,7 @@ class Module(LocalsDictNodeNG):
class ComprehensionScope(LocalsDictNodeNG):
"""Scoping for different types of comprehensions."""
+
def frame(self):
"""The first parent frame node.
@@ -741,8 +759,9 @@ class GeneratorExp(ComprehensionScope):
>>> node
<GeneratorExp l.1 at 0x7f23b2e4e400>
"""
- _astroid_fields = ('elt', 'generators')
- _other_other_fields = ('locals',)
+
+ _astroid_fields = ("elt", "generators")
+ _other_other_fields = ("locals",)
elt = None
"""The element that forms the output of the expression.
@@ -811,8 +830,9 @@ class DictComp(ComprehensionScope):
>>> node
<DictComp l.1 at 0x7f23b2e41d68>
"""
- _astroid_fields = ('key', 'value', 'generators')
- _other_other_fields = ('locals',)
+
+ _astroid_fields = ("key", "value", "generators")
+ _other_other_fields = ("locals",)
key = None
"""What produces the keys.
@@ -891,8 +911,9 @@ class SetComp(ComprehensionScope):
>>> node
<SetComp l.1 at 0x7f23b2e41898>
"""
- _astroid_fields = ('elt', 'generators')
- _other_other_fields = ('locals',)
+
+ _astroid_fields = ("elt", "generators")
+ _other_other_fields = ("locals",)
elt = None
"""The element that forms the output of the expression.
@@ -961,7 +982,8 @@ class _ListComp(node_classes.NodeNG):
>>> node
<ListComp l.1 at 0x7f23b2e418d0>
"""
- _astroid_fields = ('elt', 'generators')
+
+ _astroid_fields = ("elt", "generators")
elt = None
"""The element that forms the output of the expression.
@@ -1007,7 +1029,8 @@ class ListComp(_ListComp, ComprehensionScope):
>>> node
<ListComp l.1 at 0x7f23b2e418d0>
"""
- _other_other_fields = ('locals',)
+
+ _other_other_fields = ("locals",)
def __init__(self, lineno=None, col_offset=None, parent=None):
self.locals = {}
@@ -1034,10 +1057,10 @@ def _infer_decorator_callchain(node):
if isinstance(result, bases.Instance):
result = result._proxied
if isinstance(result, ClassDef):
- if result.is_subtype_of('%s.classmethod' % BUILTINS):
- return 'classmethod'
- if result.is_subtype_of('%s.staticmethod' % BUILTINS):
- return 'staticmethod'
+ if result.is_subtype_of("%s.classmethod" % BUILTINS):
+ return "classmethod"
+ if result.is_subtype_of("%s.staticmethod" % BUILTINS):
+ return "staticmethod"
return None
@@ -1048,9 +1071,10 @@ class Lambda(mixins.FilterStmtsMixin, LocalsDictNodeNG):
>>> node
<Lambda.<lambda> l.1 at 0x7f23b2e41518>
"""
- _astroid_fields = ('args', 'body',)
- _other_other_fields = ('locals',)
- name = '<lambda>'
+
+ _astroid_fields = ("args", "body")
+ _other_other_fields = ("locals",)
+ name = "<lambda>"
is_lambda = True
def implicit_parameters(self):
@@ -1065,10 +1089,10 @@ class Lambda(mixins.FilterStmtsMixin, LocalsDictNodeNG):
:rtype: str
"""
# pylint: disable=no-member
- if self.args.args and self.args.args[0].name == 'self':
+ if self.args.args and self.args.args[0].name == "self":
if isinstance(self.parent.scope(), ClassDef):
- return 'method'
- return 'function'
+ return "method"
+ return "function"
def __init__(self, lineno=None, col_offset=None, parent=None):
"""
@@ -1120,9 +1144,9 @@ class Lambda(mixins.FilterStmtsMixin, LocalsDictNodeNG):
:returns: The name of the type.
:rtype: str
"""
- if 'method' in self.type:
- return '%s.instancemethod' % BUILTINS
- return '%s.function' % BUILTINS
+ if "method" in self.type:
+ return "%s.instancemethod" % BUILTINS
+ return "%s.function" % BUILTINS
def display_type(self):
"""A human readable type of this node.
@@ -1130,9 +1154,9 @@ class Lambda(mixins.FilterStmtsMixin, LocalsDictNodeNG):
:returns: The type of this node.
:rtype: str
"""
- if 'method' in self.type:
- return 'Method'
- return 'Function'
+ if "method" in self.type:
+ return "Method"
+ return "Function"
def callable(self):
"""Whether this node defines something that is callable.
@@ -1154,7 +1178,7 @@ class Lambda(mixins.FilterStmtsMixin, LocalsDictNodeNG):
# args is in fact redefined later on by postinit. Can't be changed
# to None due to a strong interaction between Lambda and FunctionDef.
- if self.args.args: # maybe None with builtin functions
+ if self.args.args: # maybe None with builtin functions
names = _rec_get_names(self.args.args)
else:
names = []
@@ -1231,8 +1255,9 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
>>> node
<FunctionDef.my_func l.2 at 0x7f23b2e71e10>
"""
- _astroid_fields = ('decorators', 'args', 'returns', 'body')
- _multi_line_block_fields = ('body',)
+
+ _astroid_fields = ("decorators", "args", "returns", "body")
+ _multi_line_block_fields = ("body",)
returns = None
decorators = None
"""The decorators that are applied to this method or function.
@@ -1264,17 +1289,16 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
type_comment_returns = None
"""If present, this will contain the return type annotation, passed by a type comment"""
# attributes below are set by the builder module or by raw factories
- _other_fields = ('name', 'doc')
+ _other_fields = ("name", "doc")
_other_other_fields = (
- 'locals',
- '_type',
- 'type_comment_returns',
- 'type_comment_args',
+ "locals",
+ "_type",
+ "type_comment_returns",
+ "type_comment_args",
)
_type = None
- def __init__(self, name=None, doc=None, lineno=None,
- col_offset=None, parent=None):
+ def __init__(self, name=None, doc=None, lineno=None, col_offset=None, parent=None):
"""
:param name: The name of the function.
:type name: str or None
@@ -1311,11 +1335,15 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
frame.set_local(name, self)
# pylint: disable=arguments-differ; different than Lambdas
- def postinit(self, args, body,
- decorators=None,
- returns=None,
- type_comment_returns=None,
- type_comment_args=None):
+ def postinit(
+ self,
+ args,
+ body,
+ decorators=None,
+ returns=None,
+ type_comment_returns=None,
+ type_comment_args=None,
+ ):
"""Do some setup after initialisation.
:param args: The arguments that the function takes.
@@ -1340,7 +1368,7 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
self.type_comment_args = type_comment_args
if isinstance(self.parent.frame(), ClassDef):
- self.set_local('__class__', self.parent.frame())
+ self.set_local("__class__", self.parent.frame())
@decorators_mod.cachedproperty
def extra_decorators(self):
@@ -1359,8 +1387,9 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
decorators = []
for assign in frame._get_assign_nodes():
- if (isinstance(assign.value, node_classes.Call)
- and isinstance(assign.value.func, node_classes.Name)):
+ if isinstance(assign.value, node_classes.Call) and isinstance(
+ assign.value.func, node_classes.Name
+ ):
for assign_node in assign.targets:
if not isinstance(assign_node, node_classes.AssignName):
# Support only `name = callable(name)`
@@ -1377,8 +1406,10 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
else:
# Must be a function and in the same frame as the
# original method.
- if (isinstance(meth, FunctionDef)
- and assign_node.frame() == frame):
+ if (
+ isinstance(meth, FunctionDef)
+ and assign_node.frame() == frame
+ ):
decorators.append(assign.value)
return decorators
@@ -1390,21 +1421,21 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
:type: str
"""
- builtin_descriptors = {'classmethod', 'staticmethod'}
+ builtin_descriptors = {"classmethod", "staticmethod"}
for decorator in self.extra_decorators:
if decorator.func.name in builtin_descriptors:
return decorator.func.name
frame = self.parent.frame()
- type_name = 'function'
+ type_name = "function"
if isinstance(frame, ClassDef):
- if self.name == '__new__':
- return 'classmethod'
- if sys.version_info >= (3, 6) and self.name == '__init_subclass__':
- return 'classmethod'
+ if self.name == "__new__":
+ return "classmethod"
+ if sys.version_info >= (3, 6) and self.name == "__init_subclass__":
+ return "classmethod"
- type_name = 'method'
+ type_name = "method"
if not self.decorators:
return type_name
@@ -1439,10 +1470,10 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
for ancestor in inferred.ancestors():
if not isinstance(ancestor, ClassDef):
continue
- if ancestor.is_subtype_of('%s.classmethod' % BUILTINS):
- return 'classmethod'
- if ancestor.is_subtype_of('%s.staticmethod' % BUILTINS):
- return 'staticmethod'
+ if ancestor.is_subtype_of("%s.classmethod" % BUILTINS):
+ return "classmethod"
+ if ancestor.is_subtype_of("%s.staticmethod" % BUILTINS):
+ return "staticmethod"
except exceptions.InferenceError:
pass
return type_name
@@ -1457,8 +1488,9 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
# statement lineno
lineno = self.lineno
if self.decorators is not None:
- lineno += sum(node.tolineno - node.lineno + 1
- for node in self.decorators.nodes)
+ lineno += sum(
+ node.tolineno - node.lineno + 1 for node in self.decorators.nodes
+ )
return lineno
@@ -1494,14 +1526,10 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
def igetattr(self, name, context=None):
"""Inferred getattr, which returns an iterator of inferred statements."""
try:
- return bases._infer_stmts(self.getattr(name, context),
- context, frame=self)
+ return bases._infer_stmts(self.getattr(name, context), context, frame=self)
except exceptions.AttributeInferenceError as error:
raise exceptions.InferenceError(
- error.message,
- target=self,
- attribute=name,
- context=context,
+ error.message, target=self, attribute=name, context=context
) from error
def is_method(self):
@@ -1512,7 +1540,7 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
"""
# check we are defined in a ClassDef, because this is usually expected
# (e.g. pylint...) when is_method() return True
- return self.type != 'function' and isinstance(self.parent.frame(), ClassDef)
+ return self.type != "function" and isinstance(self.parent.frame(), ClassDef)
@decorators_mod.cached
def decoratornames(self):
@@ -1541,7 +1569,7 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
False otherwise.
:rtype: bool
"""
- return self.type == 'classmethod'
+ return self.type == "classmethod"
def is_abstract(self, pass_is_abstract=True):
"""Check if the method is abstract.
@@ -1560,8 +1588,10 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
inferred = next(node.infer())
except exceptions.InferenceError:
continue
- if inferred and inferred.qname() in ('abc.abstractproperty',
- 'abc.abstractmethod'):
+ if inferred and inferred.qname() in (
+ "abc.abstractproperty",
+ "abc.abstractmethod",
+ ):
return True
for child_node in self.body:
@@ -1601,13 +1631,15 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
# but does not contribute to the inheritance structure itself. We inject
# a fake class into the hierarchy here for several well-known metaclass
# generators, and filter it out later.
- if (self.name == 'with_metaclass' and
- len(self.args.args) == 1 and
- self.args.vararg is not None):
+ if (
+ self.name == "with_metaclass"
+ and len(self.args.args) == 1
+ and self.args.vararg is not None
+ ):
metaclass = next(caller.args[0].infer(context))
if isinstance(metaclass, ClassDef):
class_bases = [next(arg.infer(context)) for arg in caller.args[1:]]
- new_class = ClassDef(name='temporary_class')
+ new_class = ClassDef(name="temporary_class")
new_class.hide = True
new_class.parent = self
new_class.postinit(
@@ -1622,7 +1654,7 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
first_return = next(returns, None)
if not first_return:
- raise exceptions.InferenceError('Empty return iterator')
+ raise exceptions.InferenceError("Empty return iterator")
for returnnode in itertools.chain((first_return,), returns):
if returnnode.value is None:
@@ -1688,7 +1720,7 @@ def _is_metaclass(klass, seen=None):
""" Return if the given class can be
used as a metaclass.
"""
- if klass.name == 'type':
+ if klass.name == "type":
return True
if seen is None:
seen = set()
@@ -1709,7 +1741,7 @@ def _is_metaclass(klass, seen=None):
continue
if not isinstance(baseobj, ClassDef):
continue
- if baseobj._type == 'metaclass':
+ if baseobj._type == "metaclass":
return True
if _is_metaclass(baseobj, seen):
return True
@@ -1726,29 +1758,29 @@ def _class_type(klass, ancestors=None):
if klass._type is not None:
return klass._type
if _is_metaclass(klass):
- klass._type = 'metaclass'
- elif klass.name.endswith('Exception'):
- klass._type = 'exception'
+ klass._type = "metaclass"
+ elif klass.name.endswith("Exception"):
+ klass._type = "exception"
else:
if ancestors is None:
ancestors = set()
klass_name = klass.qname()
if klass_name in ancestors:
# XXX we are in loop ancestors, and have found no type
- klass._type = 'class'
- return 'class'
+ klass._type = "class"
+ return "class"
ancestors.add(klass_name)
for base in klass.ancestors(recurs=False):
name = _class_type(base, ancestors)
- if name != 'class':
- if name == 'metaclass' and not _is_metaclass(klass):
+ if name != "class":
+ if name == "metaclass" and not _is_metaclass(klass):
# don't propagate it if the current class
# can't be a metaclass
continue
klass._type = base.type
break
if klass._type is None:
- klass._type = 'class'
+ klass._type = "class"
return klass._type
@@ -1771,8 +1803,7 @@ def get_wrapping_class(node):
return klass
-class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
- node_classes.Statement):
+class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement):
"""Class representing an :class:`ast.ClassDef` node.
>>> node = astroid.extract_node('''
@@ -1788,7 +1819,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
# by a raw factories
# a dictionary of class instances attributes
- _astroid_fields = ('decorators', 'bases', 'body') # name
+ _astroid_fields = ("decorators", "bases", "body") # name
decorators = None
"""The decorators that are applied to this class.
@@ -1804,16 +1835,19 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
_type = None
_metaclass_hack = False
hide = False
- type = property(_class_type,
- doc=("The class type for this node.\n\n"
- "Possible values are: class, metaclass, exception.\n\n"
- ":type: str"))
- _other_fields = ('name', 'doc')
- _other_other_fields = ('locals', '_newstyle')
+ type = property(
+ _class_type,
+ doc=(
+ "The class type for this node.\n\n"
+ "Possible values are: class, metaclass, exception.\n\n"
+ ":type: str"
+ ),
+ )
+ _other_fields = ("name", "doc")
+ _other_other_fields = ("locals", "_newstyle")
_newstyle = None
- def __init__(self, name=None, doc=None, lineno=None,
- col_offset=None, parent=None):
+ def __init__(self, name=None, doc=None, lineno=None, col_offset=None, parent=None):
"""
:param name: The name of the class.
:type name: str or None
@@ -1886,14 +1920,16 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
:returns: the the name and Const pair for each local
:rtype: tuple(tuple(str, node_classes.Const), ...)
"""
- locals_ = (('__module__', self.special_attributes.py__module__),)
+ locals_ = (("__module__", self.special_attributes.py__module__),)
if sys.version_info >= (3, 3):
# __qualname__ is defined in PEP3155
locals_ += (("__qualname__", self.special_attributes.py__qualname__),)
return locals_
# pylint: disable=redefined-outer-name
- def postinit(self, bases, body, decorators, newstyle=None, metaclass=None, keywords=None):
+ def postinit(
+ self, bases, body, decorators, newstyle=None, metaclass=None, keywords=None
+ ):
"""Do some setup after initialisation.
:param bases: What the class inherits from.
@@ -1942,9 +1978,10 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
return self._newstyle
_newstyle = None
- newstyle = property(_newstyle_impl,
- doc=("Whether this is a new style class or not\n\n"
- ":type: bool or None"))
+ newstyle = property(
+ _newstyle_impl,
+ doc=("Whether this is a new style class or not\n\n" ":type: bool or None"),
+ )
@decorators_mod.cachedproperty
def blockstart_tolineno(self):
@@ -1975,8 +2012,8 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
:rtype: str
"""
if self.newstyle:
- return '%s.type' % BUILTINS
- return '%s.classobj' % BUILTINS
+ return "%s.type" % BUILTINS
+ return "%s.classobj" % BUILTINS
def display_type(self):
"""A human readable type of this node.
@@ -1984,7 +2021,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
:returns: The type of this node.
:rtype: str
"""
- return 'Class'
+ return "Class"
def callable(self):
"""Whether this node defines something that is callable.
@@ -2015,8 +2052,9 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
def _infer_type_call(self, caller, context):
name_node = next(caller.args[0].infer(context))
- if (isinstance(name_node, node_classes.Const) and
- isinstance(name_node.value, str)):
+ if isinstance(name_node, node_classes.Const) and isinstance(
+ name_node.value, str
+ ):
name = name_node.value
else:
return util.Uninferable
@@ -2041,8 +2079,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
if members and isinstance(members, node_classes.Dict):
for attr, value in members.items:
- if (isinstance(attr, node_classes.Const) and
- isinstance(attr.value, str)):
+ if isinstance(attr, node_classes.Const) and isinstance(attr.value, str):
result.locals[attr.value] = [value]
result.parent = caller.parent
@@ -2050,8 +2087,10 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
def infer_call_result(self, caller, context=None):
"""infer what a class is returning when called"""
- if (self.is_subtype_of('%s.type' % (BUILTINS,), context)
- and len(caller.args) == 3):
+ if (
+ self.is_subtype_of("%s.type" % (BUILTINS,), context)
+ and len(caller.args) == 3
+ ):
result = self._infer_type_call(caller, context)
yield result
return
@@ -2094,11 +2133,13 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
# decorator that it's poorly named after a builtin object
# inside this class.
lookup_upper_frame = (
- isinstance(node.parent, node_classes.Decorators) and
- name in MANAGER.astroid_cache[builtins.__name__]
+ isinstance(node.parent, node_classes.Decorators)
+ and name in MANAGER.astroid_cache[builtins.__name__]
)
- if any(node == base or base.parent_of(node)
- for base in self.bases) or lookup_upper_frame:
+ if (
+ any(node == base or base.parent_of(node) for base in self.bases)
+ or lookup_upper_frame
+ ):
# Handle the case where we have either a name
# in the bases of a class, which exists before
# the actual definition or the case where we have
@@ -2144,7 +2185,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
yielded = {self}
if context is None:
context = contextmod.InferenceContext()
- if not self.bases and self.qname() != 'builtins.object':
+ if not self.bases and self.qname() != "builtins.object":
yield builtin_lookup("object")[1][0]
return
@@ -2163,8 +2204,9 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
yielded.add(baseobj)
yield baseobj
if recurs:
- for grandpa in baseobj.ancestors(recurs=True,
- context=context):
+ for grandpa in baseobj.ancestors(
+ recurs=True, context=context
+ ):
if grandpa is self:
# This class is the ancestor of itself.
break
@@ -2242,8 +2284,9 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
result = [n for n in result if not isinstance(n, node_classes.DelAttr)]
if result:
return result
- raise exceptions.AttributeInferenceError(target=self, attribute=name,
- context=context)
+ raise exceptions.AttributeInferenceError(
+ target=self, attribute=name, context=context
+ )
def instance_attr(self, name, context=None):
"""Get the list of nodes associated to the given attribute name.
@@ -2265,8 +2308,9 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
values = [n for n in values if not isinstance(n, node_classes.DelAttr)]
if values:
return values
- raise exceptions.AttributeInferenceError(target=self, attribute=name,
- context=context)
+ raise exceptions.AttributeInferenceError(
+ target=self, attribute=name, context=context
+ )
def instantiate_class(self):
"""Get an :class:`Instance` of the :class:`ClassDef` node.
@@ -2306,7 +2350,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
values = self.locals.get(name, [])
if name in self.special_attributes and class_context and not values:
result = [self.special_attributes.lookup(name)]
- if name == '__bases__':
+ if name == "__bases__":
# Need special treatment, since they are mutable
# and we need to return all the values.
result += values
@@ -2321,8 +2365,9 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
values += self._metaclass_lookup_attribute(name, context)
if not values:
- raise exceptions.AttributeInferenceError(target=self, attribute=name,
- context=context)
+ raise exceptions.AttributeInferenceError(
+ target=self, attribute=name, context=context
+ )
return values
def _metaclass_lookup_attribute(self, name, context):
@@ -2332,15 +2377,13 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
metaclass = self.metaclass()
for cls in {implicit_meta, metaclass}:
if cls and cls != self and isinstance(cls, ClassDef):
- cls_attributes = self._get_attribute_from_metaclass(
- cls, name, context)
+ cls_attributes = self._get_attribute_from_metaclass(cls, name, context)
attrs.update(set(cls_attributes))
return attrs
def _get_attribute_from_metaclass(self, cls, name, context):
try:
- attrs = cls.getattr(name, context=context,
- class_context=True)
+ attrs = cls.getattr(name, context=context, class_context=True)
except exceptions.AttributeInferenceError:
return
@@ -2352,7 +2395,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
if bases._is_property(attr):
yield from attr.infer_call_result(self, context)
continue
- if attr.type == 'classmethod':
+ if attr.type == "classmethod":
# If the method is a classmethod, then it will
# be bound to the metaclass, not to the class
# from where the attribute is retrieved.
@@ -2360,7 +2403,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
# default to the current class.
frame = get_wrapping_class(attr) or self
yield bases.BoundMethod(attr, frame)
- elif attr.type == 'staticmethod':
+ elif attr.type == "staticmethod":
yield attr
else:
yield bases.BoundMethod(attr, self)
@@ -2382,10 +2425,11 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
attr = self.getattr(name, context, class_context=class_context)[0]
for inferred in bases._infer_stmts([attr], context, frame=self):
# yield Uninferable object instead of descriptors when necessary
- if (not isinstance(inferred, node_classes.Const)
- and isinstance(inferred, bases.Instance)):
+ if not isinstance(inferred, node_classes.Const) and isinstance(
+ inferred, bases.Instance
+ ):
try:
- inferred._proxied.getattr('__get__', context)
+ inferred._proxied.getattr("__get__", context)
except exceptions.AttributeInferenceError:
yield inferred
else:
@@ -2393,15 +2437,12 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
else:
yield function_to_method(inferred, self)
except exceptions.AttributeInferenceError as error:
- if not name.startswith('__') and self.has_dynamic_getattr(context):
+ if not name.startswith("__") and self.has_dynamic_getattr(context):
# class handle some dynamic attributes, return a Uninferable object
yield util.Uninferable
else:
raise exceptions.InferenceError(
- error.message,
- target=self,
- attribute=name,
- context=context,
+ error.message, target=self, attribute=name, context=context
)
def has_dynamic_getattr(self, context=None):
@@ -2415,16 +2456,17 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
__getattr__ or __getattribute__, False otherwise.
:rtype: bool
"""
+
def _valid_getattr(node):
root = node.root()
- return root.name != BUILTINS and getattr(root, 'pure_python', None)
+ return root.name != BUILTINS and getattr(root, "pure_python", None)
try:
- return _valid_getattr(self.getattr('__getattr__', context)[0])
+ return _valid_getattr(self.getattr("__getattr__", context)[0])
except exceptions.AttributeInferenceError:
- #if self.newstyle: XXX cause an infinite recursion error
+ # if self.newstyle: XXX cause an infinite recursion error
try:
- getattribute = self.getattr('__getattribute__', context)[0]
+ getattribute = self.getattr("__getattribute__", context)[0]
return _valid_getattr(getattribute)
except exceptions.AttributeInferenceError:
pass
@@ -2442,7 +2484,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
``__getitem__`` method.
"""
try:
- methods = dunder_lookup.lookup(self, '__getitem__')
+ methods = dunder_lookup.lookup(self, "__getitem__")
except exceptions.AttributeInferenceError as exc:
raise exceptions.AstroidTypeError(node=self, context=context) from exc
@@ -2492,10 +2534,11 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
:rtype: builtins.type or None
"""
if self.newstyle:
- return builtin_lookup('type')[1][0]
+ return builtin_lookup("type")[1][0]
return None
_metaclass = None
+
def declared_metaclass(self, context=None):
"""Return the explicit declared metaclass for the current class.
@@ -2522,8 +2565,11 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
if self._metaclass:
# Expects this from Py3k TreeRebuilder
try:
- return next(node for node in self._metaclass.infer(context=context)
- if node is not util.Uninferable)
+ return next(
+ node
+ for node in self._metaclass.infer(context=context)
+ if node is not util.Uninferable
+ )
except (exceptions.InferenceError, StopIteration):
return None
@@ -2560,9 +2606,9 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
def _islots(self):
""" Return an iterator with the inferred slots. """
- if '__slots__' not in self.locals:
+ if "__slots__" not in self.locals:
return None
- for slots in self.igetattr('__slots__'):
+ for slots in self.igetattr("__slots__"):
# check if __slots__ is a valid type
for meth in ITER_METHODS:
try:
@@ -2579,7 +2625,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
if slots.value:
yield slots
continue
- if not hasattr(slots, 'itered'):
+ if not hasattr(slots, "itered"):
# we can't obtain the values, maybe a .deque?
continue
@@ -2599,8 +2645,9 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
for inferred in elt.infer():
if inferred is util.Uninferable:
continue
- if (not isinstance(inferred, node_classes.Const) or
- not isinstance(inferred.value, str)):
+ if not isinstance(
+ inferred, node_classes.Const
+ ) or not isinstance(inferred.value, str):
continue
if not inferred.value:
continue
@@ -2613,14 +2660,15 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
def _slots(self):
if not self.newstyle:
raise NotImplementedError(
- "The concept of slots is undefined for old-style classes.")
+ "The concept of slots is undefined for old-style classes."
+ )
slots = self._islots()
try:
first = next(slots)
except StopIteration as exc:
# The class doesn't have a __slots__ definition or empty slots.
- if exc.args and exc.args[0] not in ('', None):
+ if exc.args and exc.args[0] not in ("", None):
return exc.args[0]
return None
return [first] + list(slots)
@@ -2636,6 +2684,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
Also, it will return None in the case the slots were not inferred.
:rtype: list(str) or None
"""
+
def grouped_slots():
# Not interested in object, since it can't have slots.
for cls in self.mro()[:-1]:
@@ -2650,7 +2699,8 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
if not self.newstyle:
raise NotImplementedError(
- "The concept of slots is undefined for old-style classes.")
+ "The concept of slots is undefined for old-style classes."
+ )
slots = list(grouped_slots())
if not all(slot is not None for slot in slots):
@@ -2674,7 +2724,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
if context is None:
context = contextmod.InferenceContext()
- if not self.bases and self.qname() != 'builtins.object':
+ if not self.bases and self.qname() != "builtins.object":
yield builtin_lookup("object")[1][0]
return
@@ -2711,7 +2761,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
ancestors = list(base.ancestors(context=context))
bases_mro.append(ancestors)
- unmerged_mro = ([[self]] + bases_mro + [inferred_bases])
+ unmerged_mro = [[self]] + bases_mro + [inferred_bases]
_verify_duplicates_mro(unmerged_mro, self, context)
return _c3_merge(unmerged_mro, self, context)
@@ -2728,8 +2778,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
"""
if not self.newstyle:
- raise NotImplementedError(
- "Could not obtain mro for old-style classes.")
+ raise NotImplementedError("Could not obtain mro for old-style classes.")
return self._compute_mro(context=context)
diff --git a/astroid/test_utils.py b/astroid/test_utils.py
index 757fe8de..55b7e848 100644
--- a/astroid/test_utils.py
+++ b/astroid/test_utils.py
@@ -21,13 +21,16 @@ def require_version(minver=None, maxver=None):
""" Compare version of python interpreter to the given one. Skip the test
if older.
"""
+
def parse(string, default=None):
string = string or default
try:
- return tuple(int(v) for v in string.split('.'))
+ return tuple(int(v) for v in string.split("."))
except ValueError as exc:
raise ValueError(
- '{string} is not a correct version : should be X.Y[.Z].'.format(string=string)
+ "{string} is not a correct version : should be X.Y[.Z].".format(
+ string=string
+ )
) from exc
def check_require_version(f):
@@ -35,30 +38,34 @@ def require_version(minver=None, maxver=None):
if parse(minver, "0") < current <= parse(maxver, "4"):
return f
- str_version = '.'.join(str(v) for v in sys.version_info)
+ str_version = ".".join(str(v) for v in sys.version_info)
+
@functools.wraps(f)
def new_f(self, *args, **kwargs):
if minver is not None:
- self.skipTest('Needs Python > %s. Current version is %s.'
- % (minver, str_version))
+ self.skipTest(
+ "Needs Python > %s. Current version is %s." % (minver, str_version)
+ )
elif maxver is not None:
- self.skipTest('Needs Python <= %s. Current version is %s.'
- % (maxver, str_version))
- return new_f
+ self.skipTest(
+ "Needs Python <= %s. Current version is %s." % (maxver, str_version)
+ )
+ return new_f
return check_require_version
+
def get_name_node(start_from, name, index=0):
return [n for n in start_from.nodes_of_class(nodes.Name) if n.name == name][index]
@contextlib.contextmanager
def enable_warning(warning):
- warnings.simplefilter('always', warning)
+ warnings.simplefilter("always", warning)
try:
yield
finally:
# Reset it to default value, so it will take
# into account the values from the -W flag.
- warnings.simplefilter('default', warning)
+ warnings.simplefilter("default", warning)
diff --git a/astroid/tests/resources.py b/astroid/tests/resources.py
index 290bbf0b..75c555d5 100644
--- a/astroid/tests/resources.py
+++ b/astroid/tests/resources.py
@@ -13,16 +13,18 @@ import pkg_resources
from astroid import builder
from astroid import MANAGER
-from astroid.bases import BUILTINS
+from astroid.bases import BUILTINS
from astroid import tests
-DATA_DIR = os.path.join('testdata', 'python{}'.format(sys.version_info[0]))
-RESOURCE_PATH = os.path.join(tests.__path__[0], DATA_DIR, 'data')
+DATA_DIR = os.path.join("testdata", "python{}".format(sys.version_info[0]))
+RESOURCE_PATH = os.path.join(tests.__path__[0], DATA_DIR, "data")
+
def find(name):
return pkg_resources.resource_filename(
- 'astroid.tests', os.path.normpath(os.path.join(DATA_DIR, name)))
+ "astroid.tests", os.path.normpath(os.path.join(DATA_DIR, name))
+ )
def build_file(path, modname=None):
@@ -31,11 +33,11 @@ def build_file(path, modname=None):
class SysPathSetup:
def setUp(self):
- sys.path.insert(0, find(''))
+ sys.path.insert(0, find(""))
def tearDown(self):
del sys.path[0]
- datadir = find('')
+ datadir = find("")
for key in list(sys.path_importer_cache):
if key.startswith(datadir):
del sys.path_importer_cache[key]
diff --git a/astroid/tests/unittest_brain.py b/astroid/tests/unittest_brain.py
index d7c75f9c..8d1eb534 100644
--- a/astroid/tests/unittest_brain.py
+++ b/astroid/tests/unittest_brain.py
@@ -23,7 +23,8 @@
import queue
try:
- import multiprocessing # pylint: disable=unused-import
+ import multiprocessing # pylint: disable=unused-import
+
HAS_MULTIPROCESSING = True
except ImportError:
HAS_MULTIPROCESSING = False
@@ -31,32 +32,38 @@ import sys
import unittest
try:
- import enum # pylint: disable=unused-import
+ import enum # pylint: disable=unused-import
+
HAS_ENUM = True
except ImportError:
try:
- import enum34 as enum # pylint: disable=unused-import
+ import enum34 as enum # pylint: disable=unused-import
+
HAS_ENUM = True
except ImportError:
HAS_ENUM = False
try:
- import nose # pylint: disable=unused-import
+ import nose # pylint: disable=unused-import
+
HAS_NOSE = True
except ImportError:
HAS_NOSE = False
try:
- import dateutil # pylint: disable=unused-import
+ import dateutil # pylint: disable=unused-import
+
HAS_DATEUTIL = True
except ImportError:
HAS_DATEUTIL = False
import pytest
+
HAS_PYTEST = True
try:
- import attr as attr_module # pylint: disable=unused-import
+ import attr as attr_module # pylint: disable=unused-import
+
HAS_ATTR = True
except ImportError:
HAS_ATTR = False
@@ -72,230 +79,259 @@ import astroid
class HashlibTest(unittest.TestCase):
def _assert_hashlib_class(self, class_obj):
- self.assertIn('update', class_obj)
- self.assertIn('digest', class_obj)
- self.assertIn('hexdigest', class_obj)
- self.assertIn('block_size', class_obj)
- self.assertIn('digest_size', class_obj)
- self.assertEqual(len(class_obj['__init__'].args.args), 2)
- self.assertEqual(len(class_obj['__init__'].args.defaults), 1)
- self.assertEqual(len(class_obj['update'].args.args), 2)
- self.assertEqual(len(class_obj['digest'].args.args), 1)
- self.assertEqual(len(class_obj['hexdigest'].args.args), 1)
+ self.assertIn("update", class_obj)
+ self.assertIn("digest", class_obj)
+ self.assertIn("hexdigest", class_obj)
+ self.assertIn("block_size", class_obj)
+ self.assertIn("digest_size", class_obj)
+ self.assertEqual(len(class_obj["__init__"].args.args), 2)
+ self.assertEqual(len(class_obj["__init__"].args.defaults), 1)
+ self.assertEqual(len(class_obj["update"].args.args), 2)
+ self.assertEqual(len(class_obj["digest"].args.args), 1)
+ self.assertEqual(len(class_obj["hexdigest"].args.args), 1)
def test_hashlib(self):
"""Tests that brain extensions for hashlib work."""
- hashlib_module = MANAGER.ast_from_module_name('hashlib')
- for class_name in ['md5', 'sha1']:
+ hashlib_module = MANAGER.ast_from_module_name("hashlib")
+ for class_name in ["md5", "sha1"]:
class_obj = hashlib_module[class_name]
self._assert_hashlib_class(class_obj)
- @test_utils.require_version(minver='3.6')
+ @test_utils.require_version(minver="3.6")
def test_hashlib_py36(self):
- hashlib_module = MANAGER.ast_from_module_name('hashlib')
- for class_name in ['sha3_224', 'sha3_512', 'shake_128']:
+ hashlib_module = MANAGER.ast_from_module_name("hashlib")
+ for class_name in ["sha3_224", "sha3_512", "shake_128"]:
class_obj = hashlib_module[class_name]
self._assert_hashlib_class(class_obj)
- for class_name in ['blake2b', 'blake2s']:
+ for class_name in ["blake2b", "blake2s"]:
class_obj = hashlib_module[class_name]
- self.assertEqual(len(class_obj['__init__'].args.args), 3)
+ self.assertEqual(len(class_obj["__init__"].args.args), 3)
class CollectionsDequeTests(unittest.TestCase):
def _inferred_queue_instance(self):
- node = builder.extract_node("""
+ node = builder.extract_node(
+ """
import collections
q = collections.deque([])
q
- """)
+ """
+ )
return next(node.infer())
def test_deque(self):
inferred = self._inferred_queue_instance()
- self.assertTrue(inferred.getattr('__len__'))
+ self.assertTrue(inferred.getattr("__len__"))
- @test_utils.require_version(minver='3.5')
+ @test_utils.require_version(minver="3.5")
def test_deque_py35methods(self):
inferred = self._inferred_queue_instance()
- self.assertIn('copy', inferred.locals)
- self.assertIn('insert', inferred.locals)
- self.assertIn('index', inferred.locals)
+ self.assertIn("copy", inferred.locals)
+ self.assertIn("insert", inferred.locals)
+ self.assertIn("index", inferred.locals)
class OrderedDictTest(unittest.TestCase):
def _inferred_ordered_dict_instance(self):
- node = builder.extract_node("""
+ node = builder.extract_node(
+ """
import collections
d = collections.OrderedDict()
d
- """)
+ """
+ )
return next(node.infer())
- @test_utils.require_version(minver='3.4')
+ @test_utils.require_version(minver="3.4")
def test_ordered_dict_py34method(self):
inferred = self._inferred_ordered_dict_instance()
- self.assertIn('move_to_end', inferred.locals)
+ self.assertIn("move_to_end", inferred.locals)
class NamedTupleTest(unittest.TestCase):
-
def test_namedtuple_base(self):
- klass = builder.extract_node("""
+ klass = builder.extract_node(
+ """
from collections import namedtuple
class X(namedtuple("X", ["a", "b", "c"])):
pass
- """)
+ """
+ )
self.assertEqual(
- [anc.name for anc in klass.ancestors()],
- ['X', 'tuple', 'object'])
+ [anc.name for anc in klass.ancestors()], ["X", "tuple", "object"]
+ )
for anc in klass.ancestors():
self.assertFalse(anc.parent is None)
def test_namedtuple_inference(self):
- klass = builder.extract_node("""
+ klass = builder.extract_node(
+ """
from collections import namedtuple
name = "X"
fields = ["a", "b", "c"]
class X(namedtuple(name, fields)):
pass
- """)
- base = next(base for base in klass.ancestors()
- if base.name == 'X')
+ """
+ )
+ base = next(base for base in klass.ancestors() if base.name == "X")
self.assertSetEqual({"a", "b", "c"}, set(base.instance_attrs))
def test_namedtuple_inference_failure(self):
- klass = builder.extract_node("""
+ klass = builder.extract_node(
+ """
from collections import namedtuple
def foo(fields):
return __(namedtuple("foo", fields))
- """)
+ """
+ )
self.assertIs(util.Uninferable, next(klass.infer()))
def test_namedtuple_advanced_inference(self):
# urlparse return an object of class ParseResult, which has a
# namedtuple call and a mixin as base classes
- result = builder.extract_node("""
+ result = builder.extract_node(
+ """
import six
result = __(six.moves.urllib.parse.urlparse('gopher://'))
- """)
+ """
+ )
instance = next(result.infer())
- self.assertGreaterEqual(len(instance.getattr('scheme')), 1)
- self.assertGreaterEqual(len(instance.getattr('port')), 1)
+ self.assertGreaterEqual(len(instance.getattr("scheme")), 1)
+ self.assertGreaterEqual(len(instance.getattr("port")), 1)
with self.assertRaises(astroid.AttributeInferenceError):
- instance.getattr('foo')
- self.assertGreaterEqual(len(instance.getattr('geturl')), 1)
- self.assertEqual(instance.name, 'ParseResult')
+ instance.getattr("foo")
+ self.assertGreaterEqual(len(instance.getattr("geturl")), 1)
+ self.assertEqual(instance.name, "ParseResult")
def test_namedtuple_instance_attrs(self):
- result = builder.extract_node('''
+ result = builder.extract_node(
+ """
from collections import namedtuple
namedtuple('a', 'a b c')(1, 2, 3) #@
- ''')
+ """
+ )
inferred = next(result.infer())
for name, attr in inferred.instance_attrs.items():
self.assertEqual(attr[0].attrname, name)
def test_namedtuple_uninferable_fields(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
x = [A] * 2
from collections import namedtuple
l = namedtuple('a', x)
l(1)
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIs(util.Uninferable, inferred)
def test_namedtuple_access_class_fields(self):
- node = builder.extract_node("""
+ node = builder.extract_node(
+ """
from collections import namedtuple
Tuple = namedtuple("Tuple", "field other")
Tuple #@
- """)
+ """
+ )
inferred = next(node.infer())
- self.assertIn('field', inferred.locals)
- self.assertIn('other', inferred.locals)
+ self.assertIn("field", inferred.locals)
+ self.assertIn("other", inferred.locals)
def test_namedtuple_rename_keywords(self):
- node = builder.extract_node("""
+ node = builder.extract_node(
+ """
from collections import namedtuple
Tuple = namedtuple("Tuple", "abc def", rename=True)
Tuple #@
- """)
+ """
+ )
inferred = next(node.infer())
- self.assertIn('abc', inferred.locals)
- self.assertIn('_1', inferred.locals)
+ self.assertIn("abc", inferred.locals)
+ self.assertIn("_1", inferred.locals)
def test_namedtuple_rename_duplicates(self):
- node = builder.extract_node("""
+ node = builder.extract_node(
+ """
from collections import namedtuple
Tuple = namedtuple("Tuple", "abc abc abc", rename=True)
Tuple #@
- """)
+ """
+ )
inferred = next(node.infer())
- self.assertIn('abc', inferred.locals)
- self.assertIn('_1', inferred.locals)
- self.assertIn('_2', inferred.locals)
+ self.assertIn("abc", inferred.locals)
+ self.assertIn("_1", inferred.locals)
+ self.assertIn("_2", inferred.locals)
def test_namedtuple_rename_uninferable(self):
- node = builder.extract_node("""
+ node = builder.extract_node(
+ """
from collections import namedtuple
Tuple = namedtuple("Tuple", "a b c", rename=UNINFERABLE)
Tuple #@
- """)
+ """
+ )
inferred = next(node.infer())
- self.assertIn('a', inferred.locals)
- self.assertIn('b', inferred.locals)
- self.assertIn('c', inferred.locals)
+ self.assertIn("a", inferred.locals)
+ self.assertIn("b", inferred.locals)
+ self.assertIn("c", inferred.locals)
def test_namedtuple_func_form(self):
- node = builder.extract_node("""
+ node = builder.extract_node(
+ """
from collections import namedtuple
Tuple = namedtuple(typename="Tuple", field_names="a b c", rename=UNINFERABLE)
Tuple #@
- """)
+ """
+ )
inferred = next(node.infer())
- self.assertEqual(inferred.name, 'Tuple')
- self.assertIn('a', inferred.locals)
- self.assertIn('b', inferred.locals)
- self.assertIn('c', inferred.locals)
+ self.assertEqual(inferred.name, "Tuple")
+ self.assertIn("a", inferred.locals)
+ self.assertIn("b", inferred.locals)
+ self.assertIn("c", inferred.locals)
def test_namedtuple_func_form_args_and_kwargs(self):
- node = builder.extract_node("""
+ node = builder.extract_node(
+ """
from collections import namedtuple
Tuple = namedtuple("Tuple", field_names="a b c", rename=UNINFERABLE)
Tuple #@
- """)
+ """
+ )
inferred = next(node.infer())
- self.assertEqual(inferred.name, 'Tuple')
- self.assertIn('a', inferred.locals)
- self.assertIn('b', inferred.locals)
- self.assertIn('c', inferred.locals)
+ self.assertEqual(inferred.name, "Tuple")
+ self.assertIn("a", inferred.locals)
+ self.assertIn("b", inferred.locals)
+ self.assertIn("c", inferred.locals)
def test_namedtuple_bases_are_actually_names_not_nodes(self):
- node = builder.extract_node("""
+ node = builder.extract_node(
+ """
from collections import namedtuple
Tuple = namedtuple("Tuple", field_names="a b c", rename=UNINFERABLE)
Tuple #@
- """)
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, astroid.ClassDef)
self.assertIsInstance(inferred.bases[0], astroid.Name)
- self.assertEqual(inferred.bases[0].name, 'tuple')
+ self.assertEqual(inferred.bases[0].name, "tuple")
class DefaultDictTest(unittest.TestCase):
-
def test_1(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
from collections import defaultdict
X = defaultdict(int)
X[0]
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIs(util.Uninferable, inferred)
@@ -304,22 +340,23 @@ class ModuleExtenderTest(unittest.TestCase):
def testExtensionModules(self):
transformer = MANAGER._transform
for extender, _ in transformer.transforms[nodes.Module]:
- n = nodes.Module('__main__', None)
+ n = nodes.Module("__main__", None)
extender(n)
@unittest.skipUnless(HAS_NOSE, "This test requires nose library.")
class NoseBrainTest(unittest.TestCase):
-
def test_nose_tools(self):
- methods = builder.extract_node("""
+ methods = builder.extract_node(
+ """
from nose.tools import assert_equal
from nose.tools import assert_equals
from nose.tools import assert_true
assert_equal = assert_equal #@
assert_true = assert_true #@
assert_equals = assert_equals #@
- """)
+ """
+ )
assert_equal = next(methods[0].value.infer())
assert_true = next(methods[1].value.infer())
assert_equals = next(methods[2].value.infer())
@@ -327,64 +364,64 @@ class NoseBrainTest(unittest.TestCase):
self.assertIsInstance(assert_equal, astroid.BoundMethod)
self.assertIsInstance(assert_true, astroid.BoundMethod)
self.assertIsInstance(assert_equals, astroid.BoundMethod)
- self.assertEqual(assert_equal.qname(),
- 'unittest.case.TestCase.assertEqual')
- self.assertEqual(assert_true.qname(),
- 'unittest.case.TestCase.assertTrue')
- self.assertEqual(assert_equals.qname(),
- 'unittest.case.TestCase.assertEqual')
+ self.assertEqual(assert_equal.qname(), "unittest.case.TestCase.assertEqual")
+ self.assertEqual(assert_true.qname(), "unittest.case.TestCase.assertTrue")
+ self.assertEqual(assert_equals.qname(), "unittest.case.TestCase.assertEqual")
class SixBrainTest(unittest.TestCase):
-
def test_attribute_access(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
import six
six.moves.http_client #@
six.moves.urllib_parse #@
six.moves.urllib_error #@
six.moves.urllib.request #@
- ''')
+ """
+ )
http_client = next(ast_nodes[0].infer())
self.assertIsInstance(http_client, nodes.Module)
- self.assertEqual(http_client.name, 'http.client')
+ self.assertEqual(http_client.name, "http.client")
urllib_parse = next(ast_nodes[1].infer())
self.assertIsInstance(urllib_parse, nodes.Module)
- self.assertEqual(urllib_parse.name, 'urllib.parse')
- urljoin = next(urllib_parse.igetattr('urljoin'))
- urlencode = next(urllib_parse.igetattr('urlencode'))
+ self.assertEqual(urllib_parse.name, "urllib.parse")
+ urljoin = next(urllib_parse.igetattr("urljoin"))
+ urlencode = next(urllib_parse.igetattr("urlencode"))
self.assertIsInstance(urljoin, nodes.FunctionDef)
- self.assertEqual(urljoin.qname(), 'urllib.parse.urljoin')
+ self.assertEqual(urljoin.qname(), "urllib.parse.urljoin")
self.assertIsInstance(urlencode, nodes.FunctionDef)
- self.assertEqual(urlencode.qname(), 'urllib.parse.urlencode')
+ self.assertEqual(urlencode.qname(), "urllib.parse.urlencode")
urllib_error = next(ast_nodes[2].infer())
self.assertIsInstance(urllib_error, nodes.Module)
- self.assertEqual(urllib_error.name, 'urllib.error')
- urlerror = next(urllib_error.igetattr('URLError'))
+ self.assertEqual(urllib_error.name, "urllib.error")
+ urlerror = next(urllib_error.igetattr("URLError"))
self.assertIsInstance(urlerror, nodes.ClassDef)
- content_too_short = next(urllib_error.igetattr('ContentTooShortError'))
+ content_too_short = next(urllib_error.igetattr("ContentTooShortError"))
self.assertIsInstance(content_too_short, nodes.ClassDef)
urllib_request = next(ast_nodes[3].infer())
self.assertIsInstance(urllib_request, nodes.Module)
- self.assertEqual(urllib_request.name, 'urllib.request')
- urlopen = next(urllib_request.igetattr('urlopen'))
- urlretrieve = next(urllib_request.igetattr('urlretrieve'))
+ self.assertEqual(urllib_request.name, "urllib.request")
+ urlopen = next(urllib_request.igetattr("urlopen"))
+ urlretrieve = next(urllib_request.igetattr("urlretrieve"))
self.assertIsInstance(urlopen, nodes.FunctionDef)
- self.assertEqual(urlopen.qname(), 'urllib.request.urlopen')
+ self.assertEqual(urlopen.qname(), "urllib.request.urlopen")
self.assertIsInstance(urlretrieve, nodes.FunctionDef)
- self.assertEqual(urlretrieve.qname(), 'urllib.request.urlretrieve')
+ self.assertEqual(urlretrieve.qname(), "urllib.request.urlretrieve")
def test_from_imports(self):
- ast_node = builder.extract_node('''
+ ast_node = builder.extract_node(
+ """
from six.moves import http_client
http_client.HTTPSConnection #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.ClassDef)
- qname = 'http.client.HTTPSConnection'
+ qname = "http.client.HTTPSConnection"
self.assertEqual(inferred.qname(), qname)
def test_from_submodule_imports(self):
@@ -392,47 +429,55 @@ class SixBrainTest(unittest.TestCase):
See PyCQA/pylint#1640 for relevant issue
"""
- ast_node = builder.extract_node('''
+ ast_node = builder.extract_node(
+ """
from six.moves.urllib.parse import urlparse
urlparse #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.FunctionDef)
-@unittest.skipUnless(HAS_MULTIPROCESSING,
- 'multiprocesing is required for this test, but '
- 'on some platforms it is missing '
- '(Jython for instance)')
+@unittest.skipUnless(
+ HAS_MULTIPROCESSING,
+ "multiprocesing is required for this test, but "
+ "on some platforms it is missing "
+ "(Jython for instance)",
+)
class MultiprocessingBrainTest(unittest.TestCase):
-
def test_multiprocessing_module_attributes(self):
# Test that module attributes are working,
# especially on Python 3.4+, where they are obtained
# from a context.
- module = builder.extract_node("""
+ module = builder.extract_node(
+ """
import multiprocessing
- """)
- module = module.do_import_module('multiprocessing')
- cpu_count = next(module.igetattr('cpu_count'))
+ """
+ )
+ module = module.do_import_module("multiprocessing")
+ cpu_count = next(module.igetattr("cpu_count"))
if sys.version_info < (3, 4):
self.assertIsInstance(cpu_count, nodes.FunctionDef)
else:
self.assertIsInstance(cpu_count, astroid.BoundMethod)
def test_module_name(self):
- module = builder.extract_node("""
+ module = builder.extract_node(
+ """
import multiprocessing
multiprocessing.SyncManager()
- """)
+ """
+ )
inferred_sync_mgr = next(module.infer())
module = inferred_sync_mgr.root()
- self.assertEqual(module.name, 'multiprocessing.managers')
+ self.assertEqual(module.name, "multiprocessing.managers")
def test_multiprocessing_manager(self):
# Test that we have the proper attributes
# for a multiprocessing.managers.SyncManager
- module = builder.parse("""
+ module = builder.parse(
+ """
import multiprocessing
manager = multiprocessing.Manager()
queue = manager.Queue()
@@ -448,91 +493,96 @@ class MultiprocessingBrainTest(unittest.TestCase):
value = manager.Value()
array = manager.Array()
namespace = manager.Namespace()
- """)
- ast_queue = next(module['queue'].infer())
+ """
+ )
+ ast_queue = next(module["queue"].infer())
self.assertEqual(ast_queue.qname(), "{}.Queue".format(queue.__name__))
- joinable_queue = next(module['joinable_queue'].infer())
- self.assertEqual(joinable_queue.qname(),
- "{}.Queue".format(queue.__name__))
+ joinable_queue = next(module["joinable_queue"].infer())
+ self.assertEqual(joinable_queue.qname(), "{}.Queue".format(queue.__name__))
- event = next(module['event'].infer())
+ event = next(module["event"].infer())
event_name = "threading.Event"
self.assertEqual(event.qname(), event_name)
- rlock = next(module['rlock'].infer())
+ rlock = next(module["rlock"].infer())
rlock_name = "threading._RLock"
self.assertEqual(rlock.qname(), rlock_name)
- bounded_semaphore = next(module['bounded_semaphore'].infer())
+ bounded_semaphore = next(module["bounded_semaphore"].infer())
semaphore_name = "threading.BoundedSemaphore"
self.assertEqual(bounded_semaphore.qname(), semaphore_name)
- pool = next(module['pool'].infer())
+ pool = next(module["pool"].infer())
pool_name = "multiprocessing.pool.Pool"
self.assertEqual(pool.qname(), pool_name)
- for attr in ('list', 'dict'):
+ for attr in ("list", "dict"):
obj = next(module[attr].infer())
- self.assertEqual(obj.qname(),
- "{}.{}".format(bases.BUILTINS, attr))
+ self.assertEqual(obj.qname(), "{}.{}".format(bases.BUILTINS, attr))
- array = next(module['array'].infer())
+ array = next(module["array"].infer())
self.assertEqual(array.qname(), "array.array")
- manager = next(module['manager'].infer())
+ manager = next(module["manager"].infer())
# Verify that we have these attributes
- self.assertTrue(manager.getattr('start'))
- self.assertTrue(manager.getattr('shutdown'))
+ self.assertTrue(manager.getattr("start"))
+ self.assertTrue(manager.getattr("shutdown"))
class ThreadingBrainTest(unittest.TestCase):
def test_lock(self):
- lock_instance = builder.extract_node("""
+ lock_instance = builder.extract_node(
+ """
import threading
threading.Lock()
- """)
+ """
+ )
inferred = next(lock_instance.infer())
self.assert_is_valid_lock(inferred)
- acquire_method = inferred.getattr('acquire')[0]
- parameters = [
- param.name for param in acquire_method.args.args[1:]
- ]
- assert parameters == ['blocking', 'timeout']
+ acquire_method = inferred.getattr("acquire")[0]
+ parameters = [param.name for param in acquire_method.args.args[1:]]
+ assert parameters == ["blocking", "timeout"]
def test_rlock(self):
- self._test_lock_object('RLock')
+ self._test_lock_object("RLock")
def test_semaphore(self):
- self._test_lock_object('Semaphore')
+ self._test_lock_object("Semaphore")
def test_boundedsemaphore(self):
- self._test_lock_object('BoundedSemaphore')
+ self._test_lock_object("BoundedSemaphore")
def _test_lock_object(self, object_name):
- lock_instance = builder.extract_node("""
+ lock_instance = builder.extract_node(
+ """
import threading
threading.{}()
- """.format(object_name))
+ """.format(
+ object_name
+ )
+ )
inferred = next(lock_instance.infer())
self.assert_is_valid_lock(inferred)
def assert_is_valid_lock(self, inferred):
self.assertIsInstance(inferred, astroid.Instance)
- self.assertEqual(inferred.root().name, 'threading')
- for method in {'acquire', 'release', '__enter__', '__exit__'}:
+ self.assertEqual(inferred.root().name, "threading")
+ for method in {"acquire", "release", "__enter__", "__exit__"}:
self.assertIsInstance(next(inferred.igetattr(method)), astroid.BoundMethod)
-@unittest.skipUnless(HAS_ENUM,
- 'The enum module was only added in Python 3.4. Support for '
- 'older Python versions may be available through the enum34 '
- 'compatibility module.')
+@unittest.skipUnless(
+ HAS_ENUM,
+ "The enum module was only added in Python 3.4. Support for "
+ "older Python versions may be available through the enum34 "
+ "compatibility module.",
+)
class EnumBrainTest(unittest.TestCase):
-
def test_simple_enum(self):
- module = builder.parse("""
+ module = builder.parse(
+ """
import enum
class MyEnum(enum.Enum):
@@ -542,34 +592,38 @@ class EnumBrainTest(unittest.TestCase):
def mymethod(self, x):
return 5
- """)
+ """
+ )
- enumeration = next(module['MyEnum'].infer())
- one = enumeration['one']
- self.assertEqual(one.pytype(), '.MyEnum.one')
+ enumeration = next(module["MyEnum"].infer())
+ one = enumeration["one"]
+ self.assertEqual(one.pytype(), ".MyEnum.one")
- property_type = '{}.property'.format(bases.BUILTINS)
- for propname in ('name', 'value'):
+ property_type = "{}.property".format(bases.BUILTINS)
+ for propname in ("name", "value"):
prop = next(iter(one.getattr(propname)))
self.assertIn(property_type, prop.decoratornames())
- meth = one.getattr('mymethod')[0]
+ meth = one.getattr("mymethod")[0]
self.assertIsInstance(meth, astroid.FunctionDef)
def test_looks_like_enum_false_positive(self):
# Test that a class named Enumeration is not considered a builtin enum.
- module = builder.parse('''
+ module = builder.parse(
+ """
class Enumeration(object):
def __init__(self, name, enum_list):
pass
test = 42
- ''')
- enumeration = module['Enumeration']
- test = next(enumeration.igetattr('test'))
+ """
+ )
+ enumeration = module["Enumeration"]
+ test = next(enumeration.igetattr("test"))
self.assertEqual(test.value, 42)
def test_enum_multiple_base_classes(self):
- module = builder.parse("""
+ module = builder.parse(
+ """
import enum
class Mixin:
@@ -577,61 +631,74 @@ class EnumBrainTest(unittest.TestCase):
class MyEnum(Mixin, enum.Enum):
one = 1
- """)
- enumeration = next(module['MyEnum'].infer())
- one = enumeration['one']
+ """
+ )
+ enumeration = next(module["MyEnum"].infer())
+ one = enumeration["one"]
- clazz = one.getattr('__class__')[0]
- self.assertTrue(clazz.is_subtype_of('.Mixin'),
- 'Enum instance should share base classes with generating class')
+ clazz = one.getattr("__class__")[0]
+ self.assertTrue(
+ clazz.is_subtype_of(".Mixin"),
+ "Enum instance should share base classes with generating class",
+ )
def test_int_enum(self):
- module = builder.parse("""
+ module = builder.parse(
+ """
import enum
class MyEnum(enum.IntEnum):
one = 1
- """)
+ """
+ )
- enumeration = next(module['MyEnum'].infer())
- one = enumeration['one']
+ enumeration = next(module["MyEnum"].infer())
+ one = enumeration["one"]
- clazz = one.getattr('__class__')[0]
- int_type = '{}.{}'.format(bases.BUILTINS, 'int')
- self.assertTrue(clazz.is_subtype_of(int_type),
- 'IntEnum based enums should be a subtype of int')
+ clazz = one.getattr("__class__")[0]
+ int_type = "{}.{}".format(bases.BUILTINS, "int")
+ self.assertTrue(
+ clazz.is_subtype_of(int_type),
+ "IntEnum based enums should be a subtype of int",
+ )
def test_enum_func_form_is_class_not_instance(self):
- cls, instance = builder.extract_node('''
+ cls, instance = builder.extract_node(
+ """
from enum import Enum
f = Enum('Audience', ['a', 'b', 'c'])
f #@
f(1) #@
- ''')
+ """
+ )
inferred_cls = next(cls.infer())
self.assertIsInstance(inferred_cls, bases.Instance)
inferred_instance = next(instance.infer())
self.assertIsInstance(inferred_instance, bases.Instance)
- self.assertIsInstance(next(inferred_instance.igetattr('name')), nodes.Const)
- self.assertIsInstance(next(inferred_instance.igetattr('value')), nodes.Const)
+ self.assertIsInstance(next(inferred_instance.igetattr("name")), nodes.Const)
+ self.assertIsInstance(next(inferred_instance.igetattr("value")), nodes.Const)
def test_enum_func_form_iterable(self):
- instance = builder.extract_node('''
+ instance = builder.extract_node(
+ """
from enum import Enum
Animal = Enum('Animal', 'ant bee cat dog')
Animal
- ''')
+ """
+ )
inferred = next(instance.infer())
self.assertIsInstance(inferred, astroid.Instance)
- self.assertTrue(inferred.getattr('__iter__'))
+ self.assertTrue(inferred.getattr("__iter__"))
def test_enum_func_form_subscriptable(self):
- instance, name = builder.extract_node('''
+ instance, name = builder.extract_node(
+ """
from enum import Enum
Animal = Enum('Animal', 'ant bee cat dog')
Animal['ant'] #@
Animal['ant'].name #@
- ''')
+ """
+ )
instance = next(instance.infer())
self.assertIsInstance(instance, astroid.Instance)
@@ -639,59 +706,81 @@ class EnumBrainTest(unittest.TestCase):
self.assertIsInstance(inferred, astroid.Const)
def test_enum_func_form_has_dunder_members(self):
- instance = builder.extract_node('''
+ instance = builder.extract_node(
+ """
from enum import Enum
Animal = Enum('Animal', 'ant bee cat dog')
for i in Animal.__members__:
i #@
- ''')
+ """
+ )
instance = next(instance.infer())
self.assertIsInstance(instance, astroid.Const)
self.assertIsInstance(instance.value, str)
def test_infer_enum_value_as_the_right_type(self):
- string_value, int_value = builder.extract_node('''
+ string_value, int_value = builder.extract_node(
+ """
from enum import Enum
class A(Enum):
a = 'a'
b = 1
A.a.value #@
A.b.value #@
- ''')
+ """
+ )
inferred_string = string_value.inferred()
- assert any(isinstance(elem, astroid.Const) and elem.value == 'a'
- for elem in inferred_string)
+ assert any(
+ isinstance(elem, astroid.Const) and elem.value == "a"
+ for elem in inferred_string
+ )
inferred_int = int_value.inferred()
- assert any(isinstance(elem, astroid.Const) and elem.value == 1
- for elem in inferred_int)
+ assert any(
+ isinstance(elem, astroid.Const) and elem.value == 1 for elem in inferred_int
+ )
@unittest.skipUnless(HAS_DATEUTIL, "This test requires the dateutil library.")
class DateutilBrainTest(unittest.TestCase):
def test_parser(self):
- module = builder.parse("""
+ module = builder.parse(
+ """
from dateutil.parser import parse
d = parse('2000-01-01')
- """)
- d_type = next(module['d'].infer())
+ """
+ )
+ d_type = next(module["d"].infer())
self.assertEqual(d_type.qname(), "datetime.datetime")
@unittest.skipUnless(HAS_PYTEST, "This test requires the pytest library.")
class PytestBrainTest(unittest.TestCase):
-
def test_pytest(self):
- ast_node = builder.extract_node('''
+ ast_node = builder.extract_node(
+ """
import pytest
pytest #@
- ''')
+ """
+ )
module = next(ast_node.infer())
- attrs = ['deprecated_call', 'warns', 'exit', 'fail', 'skip',
- 'importorskip', 'xfail', 'mark', 'raises', 'freeze_includes',
- 'set_trace', 'fixture', 'yield_fixture']
- if pytest.__version__.split('.')[0] == '3':
- attrs += ['approx', 'register_assert_rewrite']
+ attrs = [
+ "deprecated_call",
+ "warns",
+ "exit",
+ "fail",
+ "skip",
+ "importorskip",
+ "xfail",
+ "mark",
+ "raises",
+ "freeze_includes",
+ "set_trace",
+ "fixture",
+ "yield_fixture",
+ ]
+ if pytest.__version__.split(".")[0] == "3":
+ attrs += ["approx", "register_assert_rewrite"]
for attr in attrs:
self.assertIn(attr, module)
@@ -706,6 +795,7 @@ def streams_are_fine():
PY3 only
"""
import io
+
for stream in (sys.stdout, sys.stderr, sys.stdin):
if not isinstance(stream, io.IOBase):
return False
@@ -716,40 +806,47 @@ class IOBrainTest(unittest.TestCase):
@unittest.skipUnless(
streams_are_fine(),
"Needs Python 3 io model / doesn't work with plain pytest."
- "use pytest -s for this test to work")
+ "use pytest -s for this test to work",
+ )
def test_sys_streams(self):
- for name in {'stdout', 'stderr', 'stdin'}:
- node = astroid.extract_node('''
+ for name in {"stdout", "stderr", "stdin"}:
+ node = astroid.extract_node(
+ """
import sys
sys.{}
- '''.format(name))
+ """.format(
+ name
+ )
+ )
inferred = next(node.infer())
- buffer_attr = next(inferred.igetattr('buffer'))
+ buffer_attr = next(inferred.igetattr("buffer"))
self.assertIsInstance(buffer_attr, astroid.Instance)
- self.assertEqual(buffer_attr.name, 'BufferedWriter')
- raw = next(buffer_attr.igetattr('raw'))
+ self.assertEqual(buffer_attr.name, "BufferedWriter")
+ raw = next(buffer_attr.igetattr("raw"))
self.assertIsInstance(raw, astroid.Instance)
- self.assertEqual(raw.name, 'FileIO')
+ self.assertEqual(raw.name, "FileIO")
-@test_utils.require_version('3.6')
+@test_utils.require_version("3.6")
class TypingBrain(unittest.TestCase):
-
def test_namedtuple_base(self):
- klass = builder.extract_node("""
+ klass = builder.extract_node(
+ """
from typing import NamedTuple
class X(NamedTuple("X", [("a", int), ("b", str), ("c", bytes)])):
pass
- """)
+ """
+ )
self.assertEqual(
- [anc.name for anc in klass.ancestors()],
- ['X', 'tuple', 'object'])
+ [anc.name for anc in klass.ancestors()], ["X", "tuple", "object"]
+ )
for anc in klass.ancestors():
self.assertFalse(anc.parent is None)
def test_namedtuple_can_correctly_access_methods(self):
- klass, called = builder.extract_node("""
+ klass, called = builder.extract_node(
+ """
from typing import NamedTuple
class X(NamedTuple): #@
@@ -760,86 +857,101 @@ class TypingBrain(unittest.TestCase):
def as_integer(self):
return 2 + 3
X().as_integer() #@
- """)
- self.assertEqual(len(klass.getattr('as_string')), 1)
+ """
+ )
+ self.assertEqual(len(klass.getattr("as_string")), 1)
inferred = next(called.infer())
self.assertIsInstance(inferred, astroid.Const)
self.assertEqual(inferred.value, 5)
def test_namedtuple_inference(self):
- klass = builder.extract_node("""
+ klass = builder.extract_node(
+ """
from typing import NamedTuple
class X(NamedTuple("X", [("a", int), ("b", str), ("c", bytes)])):
pass
- """)
- base = next(base for base in klass.ancestors()
- if base.name == 'X')
+ """
+ )
+ base = next(base for base in klass.ancestors() if base.name == "X")
self.assertSetEqual({"a", "b", "c"}, set(base.instance_attrs))
def test_namedtuple_inference_nonliteral(self):
# Note: NamedTuples in mypy only work with literals.
- klass = builder.extract_node("""
+ klass = builder.extract_node(
+ """
from typing import NamedTuple
name = "X"
fields = [("a", int), ("b", str), ("c", bytes)]
NamedTuple(name, fields)
- """)
+ """
+ )
inferred = next(klass.infer())
self.assertIsInstance(inferred, astroid.Instance)
self.assertEqual(inferred.qname(), "typing.NamedTuple")
def test_namedtuple_instance_attrs(self):
- result = builder.extract_node('''
+ result = builder.extract_node(
+ """
from typing import NamedTuple
NamedTuple("A", [("a", int), ("b", str), ("c", bytes)])(1, 2, 3) #@
- ''')
+ """
+ )
inferred = next(result.infer())
for name, attr in inferred.instance_attrs.items():
self.assertEqual(attr[0].attrname, name)
def test_namedtuple_simple(self):
- result = builder.extract_node('''
+ result = builder.extract_node(
+ """
from typing import NamedTuple
NamedTuple("A", [("a", int), ("b", str), ("c", bytes)])
- ''')
+ """
+ )
inferred = next(result.infer())
self.assertIsInstance(inferred, nodes.ClassDef)
self.assertSetEqual({"a", "b", "c"}, set(inferred.instance_attrs))
def test_namedtuple_few_args(self):
- result = builder.extract_node('''
+ result = builder.extract_node(
+ """
from typing import NamedTuple
NamedTuple("A")
- ''')
+ """
+ )
inferred = next(result.infer())
self.assertIsInstance(inferred, astroid.Instance)
self.assertEqual(inferred.qname(), "typing.NamedTuple")
def test_namedtuple_few_fields(self):
- result = builder.extract_node('''
+ result = builder.extract_node(
+ """
from typing import NamedTuple
NamedTuple("A", [("a",), ("b", str), ("c", bytes)])
- ''')
+ """
+ )
inferred = next(result.infer())
self.assertIsInstance(inferred, astroid.Instance)
self.assertEqual(inferred.qname(), "typing.NamedTuple")
def test_namedtuple_class_form(self):
- result = builder.extract_node('''
+ result = builder.extract_node(
+ """
from typing import NamedTuple
class Example(NamedTuple):
mything: int
Example(mything=1)
- ''')
+ """
+ )
inferred = next(result.infer())
self.assertIsInstance(inferred, astroid.Instance)
def test_typing_types(self):
- ast_nodes = builder.extract_node("""
+ ast_nodes = builder.extract_node(
+ """
from typing import TypeVar, Iterable, Tuple, NewType, Dict, Union
TypeVar('MyTypeVar', int, float, complex) #@
Iterable[Tuple[MyTypeVar, MyTypeVar]] #@
@@ -847,7 +959,8 @@ class TypingBrain(unittest.TestCase):
NewType('UserId', str) #@
Dict[str, str] #@
Union[int, str] #@
- """)
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.ClassDef, node.as_string())
@@ -856,18 +969,19 @@ class TypingBrain(unittest.TestCase):
class ReBrainTest(unittest.TestCase):
def test_regex_flags(self):
import re
+
names = [name for name in dir(re) if name.isupper()]
- re_ast = MANAGER.ast_from_module_name('re')
+ re_ast = MANAGER.ast_from_module_name("re")
for name in names:
self.assertIn(name, re_ast)
self.assertEqual(next(re_ast[name].infer()).value, getattr(re, name))
-@test_utils.require_version('3.6')
+@test_utils.require_version("3.6")
class BrainFStrings(unittest.TestCase):
-
def test_no_crash_on_const_reconstruction(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
max_width = 10
test1 = f'{" ":{max_width+4}}'
@@ -875,34 +989,37 @@ class BrainFStrings(unittest.TestCase):
test2 = f'[{"7":>{max_width}}:0]'
test2
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIs(inferred, util.Uninferable)
-@test_utils.require_version('3.6')
+@test_utils.require_version("3.6")
class BrainNamedtupleAnnAssignTest(unittest.TestCase):
-
def test_no_crash_on_ann_assign_in_namedtuple(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
from enum import Enum
from typing import Optional
class A(Enum):
B: str = 'B'
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.ClassDef)
class BrainUUIDTest(unittest.TestCase):
-
def test_uuid_has_int_member(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
import uuid
u = uuid.UUID('{12345678-1234-5678-1234-567812345678}')
u.int
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Const)
@@ -910,7 +1027,8 @@ class BrainUUIDTest(unittest.TestCase):
@unittest.skipUnless(HAS_ATTR, "These tests require the attr library")
class AttrsTest(unittest.TestCase):
def test_attr_transform(self):
- module = astroid.parse("""
+ module = astroid.parse(
+ """
import attr
@attr.s
@@ -927,10 +1045,11 @@ class AttrsTest(unittest.TestCase):
g = Bar()
g.d['answer'] = 42
- """)
+ """
+ )
- for name in ('f', 'g'):
- should_be_unknown = next(module.getattr(name)[0].infer()).getattr('d')[0]
+ for name in ("f", "g"):
+ should_be_unknown = next(module.getattr(name)[0].infer()).getattr("d")[0]
self.assertIsInstance(should_be_unknown, astroid.Unknown)
def test_special_attributes(self):
@@ -950,7 +1069,7 @@ class AttrsTest(unittest.TestCase):
assert isinstance(attr_node, nodes.Unknown)
def test_dont_consider_assignments_but_without_attrs(self):
- code = '''
+ code = """
import attr
class Cls: pass
@@ -960,17 +1079,18 @@ class AttrsTest(unittest.TestCase):
temp.prop = 5
bar_thing = attr.ib(default=temp)
Foo()
- '''
+ """
next(astroid.extract_node(code).infer())
class RandomSampleTest(unittest.TestCase):
-
def test_inferred_successfully(self):
- node = astroid.extract_node('''
+ node = astroid.extract_node(
+ """
import random
random.sample([1, 2], 2) #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, astroid.List)
elems = sorted(elem.value for elem in inferred.elts)
@@ -979,17 +1099,21 @@ class RandomSampleTest(unittest.TestCase):
class SubprocessTest(unittest.TestCase):
"""Test subprocess brain"""
- @unittest.skipIf(sys.version_info < (3, 3),
- reason="Python 2.7 subprocess doesnt have args")
+
+ @unittest.skipIf(
+ sys.version_info < (3, 3), reason="Python 2.7 subprocess doesnt have args"
+ )
def test_subprocess_args(self):
"""Make sure the args attribute exists for Popen
Test for https://github.com/PyCQA/pylint/issues/1860"""
- name = astroid.extract_node("""
+ name = astroid.extract_node(
+ """
import subprocess
p = subprocess.Popen(['ls'])
p #@
- """)
+ """
+ )
[inst] = name.inferred()
self.assertIsInstance(next(inst.igetattr("args")), nodes.List)
@@ -1014,34 +1138,54 @@ class TestIsinstanceInference:
assert _get_result("isinstance('a', int)") == "False"
def test_isinstance_object_true(self):
- assert _get_result("""
+ assert (
+ _get_result(
+ """
class Bar(object):
pass
isinstance(Bar(), object)
- """) == "True"
+ """
+ )
+ == "True"
+ )
def test_isinstance_object_true3(self):
- assert _get_result("""
+ assert (
+ _get_result(
+ """
class Bar(object):
pass
isinstance(Bar(), Bar)
- """) == "True"
+ """
+ )
+ == "True"
+ )
def test_isinstance_class_false(self):
- assert _get_result("""
+ assert (
+ _get_result(
+ """
class Foo(object):
pass
class Bar(object):
pass
isinstance(Bar(), Foo)
- """) == "False"
+ """
+ )
+ == "False"
+ )
def test_isinstance_type_false(self):
- assert _get_result("""
+ assert (
+ _get_result(
+ """
class Bar(object):
pass
isinstance(Bar(), type)
- """) == "False"
+ """
+ )
+ == "False"
+ )
def test_isinstance_str_true(self):
"""Make sure isinstance can check bultin str types"""
@@ -1055,25 +1199,40 @@ class TestIsinstanceInference:
assert _get_result("isinstance(1, (str, int))") == "True"
def test_isinstance_type_false2(self):
- assert _get_result("""
+ assert (
+ _get_result(
+ """
isinstance(1, type)
- """) == "False"
+ """
+ )
+ == "False"
+ )
def test_isinstance_object_true2(self):
- assert _get_result("""
+ assert (
+ _get_result(
+ """
class Bar(type):
pass
mainbar = Bar("Bar", tuple(), {})
isinstance(mainbar, object)
- """) == "True"
+ """
+ )
+ == "True"
+ )
def test_isinstance_type_true(self):
- assert _get_result("""
+ assert (
+ _get_result(
+ """
class Bar(type):
pass
mainbar = Bar("Bar", tuple(), {})
isinstance(mainbar, type)
- """) == "True"
+ """
+ )
+ == "True"
+ )
def test_isinstance_edge_case(self):
"""isinstance allows bad type short-circuting"""
@@ -1096,7 +1255,7 @@ class TestIsinstanceInference:
def test_first_param_is_uninferable(self):
with pytest.raises(astroid.InferenceError):
- _get_result_node('isinstance(something, int)')
+ _get_result_node("isinstance(something, int)")
class TestIssubclassBrain:
@@ -1118,45 +1277,70 @@ class TestIssubclassBrain:
assert _get_result("issubclass(str, int)") == "False"
def test_issubclass_object_true(self):
- assert _get_result("""
+ assert (
+ _get_result(
+ """
class Bar(object):
pass
issubclass(Bar, object)
- """) == "True"
+ """
+ )
+ == "True"
+ )
def test_issubclass_same_user_defined_class(self):
- assert _get_result("""
+ assert (
+ _get_result(
+ """
class Bar(object):
pass
issubclass(Bar, Bar)
- """) == "True"
+ """
+ )
+ == "True"
+ )
def test_issubclass_different_user_defined_classes(self):
- assert _get_result("""
+ assert (
+ _get_result(
+ """
class Foo(object):
pass
class Bar(object):
pass
issubclass(Bar, Foo)
- """) == "False"
+ """
+ )
+ == "False"
+ )
def test_issubclass_type_false(self):
- assert _get_result("""
+ assert (
+ _get_result(
+ """
class Bar(object):
pass
issubclass(Bar, type)
- """) == "False"
+ """
+ )
+ == "False"
+ )
def test_isinstance_tuple_argument(self):
"""obj just has to be a subclass of ANY class/type on the right"""
assert _get_result("issubclass(int, (str, int))") == "True"
def test_isinstance_object_true2(self):
- assert _get_result("""
+ assert (
+ _get_result(
+ """
class Bar(type):
pass
issubclass(Bar, object)
- """) == "True"
+ """
+ )
+ == "True"
+ )
def test_issubclass_short_circuit(self):
"""issubclasss allows bad type short-circuting"""
@@ -1191,59 +1375,72 @@ def _get_result(code):
class TestLenBuiltinInference:
def test_len_list(self):
# Uses .elts
- node = astroid.extract_node("""
+ node = astroid.extract_node(
+ """
len(['a','b','c'])
- """)
+ """
+ )
node = next(node.infer())
- assert node.as_string() == '3'
+ assert node.as_string() == "3"
assert isinstance(node, nodes.Const)
def test_len_tuple(self):
- node = astroid.extract_node("""
+ node = astroid.extract_node(
+ """
len(('a','b','c'))
- """)
+ """
+ )
node = next(node.infer())
- assert node.as_string() == '3'
+ assert node.as_string() == "3"
def test_len_var(self):
# Make sure argument is inferred
- node = astroid.extract_node("""
+ node = astroid.extract_node(
+ """
a = [1,2,'a','b','c']
len(a)
- """)
+ """
+ )
node = next(node.infer())
- assert node.as_string() == '5'
+ assert node.as_string() == "5"
def test_len_dict(self):
# Uses .items
- node = astroid.extract_node("""
+ node = astroid.extract_node(
+ """
a = {'a': 1, 'b': 2}
len(a)
- """)
+ """
+ )
node = next(node.infer())
- assert node.as_string() == '2'
+ assert node.as_string() == "2"
def test_len_set(self):
- node = astroid.extract_node("""
+ node = astroid.extract_node(
+ """
len({'a'})
- """)
+ """
+ )
inferred_node = next(node.infer())
- assert inferred_node.as_string() == '1'
+ assert inferred_node.as_string() == "1"
def test_len_object(self):
"""Test len with objects that implement the len protocol"""
- node = astroid.extract_node("""
+ node = astroid.extract_node(
+ """
class A:
def __len__(self):
return 57
len(A())
- """)
+ """
+ )
inferred_node = next(node.infer())
- assert inferred_node.as_string() == '57'
+ assert inferred_node.as_string() == "57"
def test_len_class_with_metaclass(self):
"""Make sure proper len method is located"""
- cls_node, inst_node = astroid.extract_node("""
+ cls_node, inst_node = astroid.extract_node(
+ """
class F2(type):
def __new__(cls, name, bases, attrs):
return super().__new__(cls, name, bases, {})
@@ -1254,56 +1451,67 @@ class TestLenBuiltinInference:
return 4
len(F) #@
len(F()) #@
- """)
- assert next(cls_node.infer()).as_string() == '57'
- assert next(inst_node.infer()).as_string() == '4'
+ """
+ )
+ assert next(cls_node.infer()).as_string() == "57"
+ assert next(inst_node.infer()).as_string() == "4"
def test_len_object_failure(self):
"""If taking the length of a class, do not use an instance method"""
- node = astroid.extract_node("""
+ node = astroid.extract_node(
+ """
class F:
def __len__(self):
return 57
len(F)
- """)
+ """
+ )
with pytest.raises(astroid.InferenceError):
next(node.infer())
def test_len_string(self):
- node = astroid.extract_node("""
+ node = astroid.extract_node(
+ """
len("uwu")
- """)
+ """
+ )
assert next(node.infer()).as_string() == "3"
def test_len_generator_failure(self):
- node = astroid.extract_node("""
+ node = astroid.extract_node(
+ """
def gen():
yield 'a'
yield 'b'
len(gen())
- """)
+ """
+ )
with pytest.raises(astroid.InferenceError):
next(node.infer())
def test_len_failure_missing_variable(self):
- node = astroid.extract_node("""
+ node = astroid.extract_node(
+ """
len(a)
- """)
+ """
+ )
with pytest.raises(astroid.InferenceError):
next(node.infer())
def test_len_bytes(self):
- node = astroid.extract_node("""
+ node = astroid.extract_node(
+ """
len(b'uwu')
- """)
- assert next(node.infer()).as_string() == '3'
-
+ """
+ )
+ assert next(node.infer()).as_string() == "3"
@pytest.mark.xfail(reason="Can't retrieve subclassed type value ")
def test_int_subclass_result(self):
"""I am unable to figure out the value of an
object which subclasses int"""
- node = astroid.extract_node("""
+ node = astroid.extract_node(
+ """
class IntSubclass(int):
pass
@@ -1311,19 +1519,22 @@ class TestLenBuiltinInference:
def __len__(self):
return IntSubclass(5)
len(F())
- """)
- assert next(node.infer()).as_string() == '5'
+ """
+ )
+ assert next(node.infer()).as_string() == "5"
@pytest.mark.xfail(reason="Can't use list special astroid fields")
def test_int_subclass_argument(self):
"""I am unable to access the length of an object which
subclasses list"""
- node = astroid.extract_node("""
+ node = astroid.extract_node(
+ """
class ListSubclass(list):
pass
len(ListSubclass([1,2,3,4,4]))
- """)
- assert next(node.infer()).as_string() == '5'
+ """
+ )
+ assert next(node.infer()).as_string() == "5"
def test_len_builtin_inference_attribute_error_str(self):
"""Make sure len builtin doesn't raise an AttributeError
@@ -1339,63 +1550,75 @@ class TestLenBuiltinInference:
def test_infer_str():
- ast_nodes = astroid.extract_node('''
+ ast_nodes = astroid.extract_node(
+ """
str(s) #@
str('a') #@
str(some_object()) #@
- ''')
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
assert isinstance(inferred, astroid.Const)
- node = astroid.extract_node('''
+ node = astroid.extract_node(
+ """
str(s='') #@
- ''')
+ """
+ )
inferred = next(node.infer())
assert isinstance(inferred, astroid.Instance)
- assert inferred.qname() == 'builtins.str'
+ assert inferred.qname() == "builtins.str"
def test_infer_int():
- ast_nodes = astroid.extract_node('''
+ ast_nodes = astroid.extract_node(
+ """
int(0) #@
int('1') #@
- ''')
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
assert isinstance(inferred, astroid.Const)
- ast_nodes = astroid.extract_node('''
+ ast_nodes = astroid.extract_node(
+ """
int(s='') #@
int('2.5') #@
int('something else') #@
int(unknown) #@
int(b'a') #@
- ''')
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
assert isinstance(inferred, astroid.Instance)
- assert inferred.qname() == 'builtins.int'
+ assert inferred.qname() == "builtins.int"
def test_infer_dict_from_keys():
- bad_nodes = astroid.extract_node('''
+ bad_nodes = astroid.extract_node(
+ """
dict.fromkeys() #@
dict.fromkeys(1, 2, 3) #@
dict.fromkeys(a=1) #@
- ''')
+ """
+ )
for node in bad_nodes:
with pytest.raises(astroid.InferenceError):
next(node.infer())
# Test uninferable values
- good_nodes = astroid.extract_node('''
+ good_nodes = astroid.extract_node(
+ """
from unknown import Unknown
dict.fromkeys(some_value) #@
dict.fromkeys(some_other_value) #@
dict.fromkeys([Unknown(), Unknown()]) #@
dict.fromkeys([Unknown(), Unknown()]) #@
- ''')
+ """
+ )
for node in good_nodes:
inferred = next(node.infer())
assert isinstance(inferred, astroid.Dict)
@@ -1404,31 +1627,37 @@ def test_infer_dict_from_keys():
# Test inferrable values
# from a dictionary's keys
- from_dict = astroid.extract_node('''
+ from_dict = astroid.extract_node(
+ """
dict.fromkeys({'a':2, 'b': 3, 'c': 3}) #@
- ''')
+ """
+ )
inferred = next(from_dict.infer())
assert isinstance(inferred, astroid.Dict)
itered = inferred.itered()
assert all(isinstance(elem, astroid.Const) for elem in itered)
actual_values = [elem.value for elem in itered]
- assert sorted(actual_values) == ['a', 'b', 'c']
+ assert sorted(actual_values) == ["a", "b", "c"]
# from a string
- from_string = astroid.extract_node('''
+ from_string = astroid.extract_node(
+ """
dict.fromkeys('abc')
- ''')
+ """
+ )
inferred = next(from_string.infer())
assert isinstance(inferred, astroid.Dict)
itered = inferred.itered()
assert all(isinstance(elem, astroid.Const) for elem in itered)
actual_values = [elem.value for elem in itered]
- assert sorted(actual_values) == ['a', 'b', 'c']
+ assert sorted(actual_values) == ["a", "b", "c"]
# from bytes
- from_bytes = astroid.extract_node('''
+ from_bytes = astroid.extract_node(
+ """
dict.fromkeys(b'abc')
- ''')
+ """
+ )
inferred = next(from_bytes.infer())
assert isinstance(inferred, astroid.Dict)
itered = inferred.itered()
@@ -1437,24 +1666,26 @@ def test_infer_dict_from_keys():
assert sorted(actual_values) == [97, 98, 99]
# From list/set/tuple
- from_others = astroid.extract_node('''
+ from_others = astroid.extract_node(
+ """
dict.fromkeys(('a', 'b', 'c')) #@
dict.fromkeys(['a', 'b', 'c']) #@
dict.fromkeys({'a', 'b', 'c'}) #@
- ''')
+ """
+ )
for node in from_others:
inferred = next(node.infer())
assert isinstance(inferred, astroid.Dict)
itered = inferred.itered()
assert all(isinstance(elem, astroid.Const) for elem in itered)
actual_values = [elem.value for elem in itered]
- assert sorted(actual_values) == ['a', 'b', 'c']
+ assert sorted(actual_values) == ["a", "b", "c"]
class TestFunctoolsPartial:
-
def test_invalid_functools_partial_calls(self):
- ast_nodes = astroid.extract_node('''
+ ast_nodes = astroid.extract_node(
+ """
from functools import partial
from unknown import Unknown
@@ -1468,14 +1699,19 @@ class TestFunctoolsPartial:
partial(Unknown, a=1) #@
partial(2, a=1) #@
partial(test, unknown=1) #@
- ''')
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
assert isinstance(inferred, (astroid.FunctionDef, astroid.Instance))
- assert inferred.qname() in ('functools.partial', 'functools.partial.newfunc')
+ assert inferred.qname() in (
+ "functools.partial",
+ "functools.partial.newfunc",
+ )
def test_inferred_partial_function_calls(self):
- ast_nodes = astroid.extract_node('''
+ ast_nodes = astroid.extract_node(
+ """
from functools import partial
def test(a, b):
return a + b
@@ -1490,15 +1726,14 @@ class TestFunctoolsPartial:
partial(other_test, c=4)(1, 3) #@
partial(other_test, 4, c=4)(4) #@
partial(other_test, 4, c=4)(b=5) #@
- ''')
- expected_values = [
- 4, 7, 7, 3, 12, 16, 32, 36,
- ]
+ """
+ )
+ expected_values = [4, 7, 7, 3, 12, 16, 32, 36]
for node, expected_value in zip(ast_nodes, expected_values):
inferred = next(node.infer())
assert isinstance(inferred, astroid.Const)
assert inferred.value == expected_value
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/tests/unittest_brain_numpy.py b/astroid/tests/unittest_brain_numpy.py
index 175fbeb0..141e5335 100644
--- a/astroid/tests/unittest_brain_numpy.py
+++ b/astroid/tests/unittest_brain_numpy.py
@@ -1,4 +1,4 @@
-#-*- encoding=utf-8 -*-
+# -*- encoding=utf-8 -*-
# Copyright (c) 2017-2018 hippo91 <guillaume.peillex@gmail.com>
# Copyright (c) 2017 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2018 Bryce Guinta <bryce.paul.guinta@gmail.com>
@@ -9,7 +9,8 @@ import unittest
import contextlib
try:
- import numpy # pylint: disable=unused-import
+ import numpy # pylint: disable=unused-import
+
HAS_NUMPY = True
except ImportError:
HAS_NUMPY = False
@@ -22,12 +23,13 @@ class SubTestWrapper(unittest.TestCase):
"""
A class for supporting all unittest version wether or not subTest is available
"""
+
def subTest(self, msg=None, **params):
try:
# For python versions above 3.5 this should be ok
return super(SubTestWrapper, self).subTest(msg, **params)
except AttributeError:
- # For python versions below 3.5
+ #  For python versions below 3.5
return subTestMock(msg)
@@ -44,37 +46,95 @@ class NumpyBrainCoreUmathTest(SubTestWrapper):
"""
Test of all members of numpy.core.umath module
"""
- no_arg_ufunc = ('geterrobj',)
- one_arg_ufunc_spec = ('seterrobj',)
+ no_arg_ufunc = ("geterrobj",)
+
+ one_arg_ufunc_spec = ("seterrobj",)
one_arg_ufunc = (
- 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctanh',
- 'cbrt', 'conj', 'conjugate', 'cosh', 'deg2rad',
- 'degrees', 'exp2', 'expm1', 'fabs', 'frexp', 'isfinite',
- 'isinf', 'log', 'log1p', 'log2', 'logical_not', 'modf',
- 'negative', 'rad2deg', 'radians', 'reciprocal', 'rint',
- 'sign', 'signbit', 'spacing', 'square', 'tan', 'tanh',
- 'trunc',)
+ "arccos",
+ "arccosh",
+ "arcsin",
+ "arcsinh",
+ "arctan",
+ "arctanh",
+ "cbrt",
+ "conj",
+ "conjugate",
+ "cosh",
+ "deg2rad",
+ "degrees",
+ "exp2",
+ "expm1",
+ "fabs",
+ "frexp",
+ "isfinite",
+ "isinf",
+ "log",
+ "log1p",
+ "log2",
+ "logical_not",
+ "modf",
+ "negative",
+ "rad2deg",
+ "radians",
+ "reciprocal",
+ "rint",
+ "sign",
+ "signbit",
+ "spacing",
+ "square",
+ "tan",
+ "tanh",
+ "trunc",
+ )
two_args_ufunc = (
- 'bitwise_and', 'bitwise_or', 'bitwise_xor',
- 'copysign', 'divide', 'equal', 'float_power',
- 'floor_divide', 'fmax', 'fmin', 'fmod', 'greater',
- 'hypot', 'ldexp', 'left_shift', 'less', 'logaddexp',
- 'logaddexp2', 'logical_and', 'logical_or', 'logical_xor',
- 'maximum', 'minimum', 'nextafter', 'not_equal', 'power',
- 'remainder', 'right_shift', 'subtract', 'true_divide',)
+ "bitwise_and",
+ "bitwise_or",
+ "bitwise_xor",
+ "copysign",
+ "divide",
+ "equal",
+ "float_power",
+ "floor_divide",
+ "fmax",
+ "fmin",
+ "fmod",
+ "greater",
+ "hypot",
+ "ldexp",
+ "left_shift",
+ "less",
+ "logaddexp",
+ "logaddexp2",
+ "logical_and",
+ "logical_or",
+ "logical_xor",
+ "maximum",
+ "minimum",
+ "nextafter",
+ "not_equal",
+ "power",
+ "remainder",
+ "right_shift",
+ "subtract",
+ "true_divide",
+ )
all_ufunc = no_arg_ufunc + one_arg_ufunc_spec + one_arg_ufunc + two_args_ufunc
- constants = ('e', 'euler_gamma')
+ constants = ("e", "euler_gamma")
def _inferred_numpy_attribute(self, func_name):
- node = builder.extract_node("""
+ node = builder.extract_node(
+ """
import numpy.core.umath as tested_module
func = tested_module.{:s}
- func""".format(func_name))
+ func""".format(
+ func_name
+ )
+ )
return next(node.infer())
def test_numpy_core_umath_constants(self):
@@ -90,8 +150,7 @@ class NumpyBrainCoreUmathTest(SubTestWrapper):
"""
Test the values of the constants.
"""
- exact_values = {'e': 2.718281828459045,
- 'euler_gamma': 0.5772156649015329}
+ exact_values = {"e": 2.718281828459045, "euler_gamma": 0.5772156649015329}
for const in self.constants:
with self.subTest(const=const):
inferred = self._inferred_numpy_attribute(const)
@@ -119,7 +178,7 @@ class NumpyBrainCoreUmathTest(SubTestWrapper):
"""
Test the arguments names of functions.
"""
- exact_arg_names = ['errobj']
+ exact_arg_names = ["errobj"]
for func in self.one_arg_ufunc_spec:
with self.subTest(func=func):
inferred = self._inferred_numpy_attribute(func)
@@ -129,7 +188,7 @@ class NumpyBrainCoreUmathTest(SubTestWrapper):
"""
Test the arguments names of functions.
"""
- exact_arg_names = ['x', 'out', 'where', 'casting', 'order', 'dtype', 'subok']
+ exact_arg_names = ["x", "out", "where", "casting", "order", "dtype", "subok"]
for func in self.one_arg_ufunc:
with self.subTest(func=func):
inferred = self._inferred_numpy_attribute(func)
@@ -139,7 +198,16 @@ class NumpyBrainCoreUmathTest(SubTestWrapper):
"""
Test the arguments names of functions.
"""
- exact_arg_names = ['x1', 'x2', 'out', 'where', 'casting', 'order', 'dtype', 'subok']
+ exact_arg_names = [
+ "x1",
+ "x2",
+ "out",
+ "where",
+ "casting",
+ "order",
+ "dtype",
+ "subok",
+ ]
for func in self.two_args_ufunc:
with self.subTest(func=func):
inferred = self._inferred_numpy_attribute(func)
@@ -149,11 +217,13 @@ class NumpyBrainCoreUmathTest(SubTestWrapper):
"""
Test the default values for keyword arguments.
"""
- exact_kwargs_default_values = [None, True, 'same_kind', 'K', None, True]
+ exact_kwargs_default_values = [None, True, "same_kind", "K", None, True]
for func in self.one_arg_ufunc + self.two_args_ufunc:
with self.subTest(func=func):
inferred = self._inferred_numpy_attribute(func)
- default_args_values = [default.value for default in inferred.args.defaults]
+ default_args_values = [
+ default.value for default in inferred.args.defaults
+ ]
self.assertEqual(default_args_values, exact_kwargs_default_values)
@@ -162,61 +232,67 @@ class NumpyBrainRandomMtrandTest(SubTestWrapper):
"""
Test of all the functions of numpy.random.mtrand module.
"""
- # Map between functions names and arguments names and default values
+
+ #  Map between functions names and arguments names and default values
all_mtrand = {
- 'beta': (['a', 'b', 'size'], [None]),
- 'binomial': (['n', 'p', 'size'], [None]),
- 'bytes': (['length',], []),
- 'chisquare': (['df', 'size'], [None]),
- 'choice': (['a', 'size', 'replace', 'p'], [None, True, None]),
- 'dirichlet': (['alpha', 'size'], [None]),
- 'exponential': (['scale', 'size'], [1.0, None]),
- 'f': (['dfnum', 'dfden', 'size'], [None]),
- 'gamma': (['shape', 'scale', 'size'], [1.0, None]),
- 'geometric': (['p', 'size'], [None]),
- 'get_state': ([], []),
- 'gumbel': (['loc', 'scale', 'size'], [0.0, 1.0, None]),
- 'hypergeometric': (['ngood', 'nbad', 'nsample', 'size'], [None]),
- 'laplace': (['loc', 'scale', 'size'], [0.0, 1.0, None]),
- 'logistic': (['loc', 'scale', 'size'], [0.0, 1.0, None]),
- 'lognormal': (['mean', 'sigma', 'size'], [0.0, 1.0, None]),
- 'logseries': (['p', 'size'], [None]),
- 'multinomial': (['n', 'pvals', 'size'], [None]),
- 'multivariate_normal': (['mean', 'cov', 'size'], [None]),
- 'negative_binomial': (['n', 'p', 'size'], [None]),
- 'noncentral_chisquare': (['df', 'nonc', 'size'], [None]),
- 'noncentral_f': (['dfnum', 'dfden', 'nonc', 'size'], [None]),
- 'normal': (['loc', 'scale', 'size'], [0.0, 1.0, None]),
- 'pareto': (['a', 'size'], [None]),
- 'permutation': (['x'], []),
- 'poisson': (['lam', 'size'], [1.0, None]),
- 'power': (['a', 'size'], [None]),
- 'rand': (['args'], []),
- 'randint': (['low', 'high', 'size', 'dtype'], [None, None, 'l']),
- 'randn': (['args'], []),
- 'random_integers': (['low', 'high', 'size'], [None, None]),
- 'random_sample': (['size'], [None]),
- 'rayleigh': (['scale', 'size'], [1.0, None]),
- 'seed': (['seed'], [None]),
- 'set_state': (['state'], []),
- 'shuffle': (['x'], []),
- 'standard_cauchy': (['size'], [None]),
- 'standard_exponential': (['size'], [None]),
- 'standard_gamma': (['shape', 'size'], [None]),
- 'standard_normal': (['size'], [None]),
- 'standard_t': (['df', 'size'], [None]),
- 'triangular': (['left', 'mode', 'right', 'size'], [None]),
- 'uniform': (['low', 'high', 'size'], [0.0, 1.0, None]),
- 'vonmises': (['mu', 'kappa', 'size'], [None]),
- 'wald': (['mean', 'scale', 'size'], [None]),
- 'weibull': (['a', 'size'], [None]),
- 'zipf': (['a', 'size'], [None])}
+ "beta": (["a", "b", "size"], [None]),
+ "binomial": (["n", "p", "size"], [None]),
+ "bytes": (["length"], []),
+ "chisquare": (["df", "size"], [None]),
+ "choice": (["a", "size", "replace", "p"], [None, True, None]),
+ "dirichlet": (["alpha", "size"], [None]),
+ "exponential": (["scale", "size"], [1.0, None]),
+ "f": (["dfnum", "dfden", "size"], [None]),
+ "gamma": (["shape", "scale", "size"], [1.0, None]),
+ "geometric": (["p", "size"], [None]),
+ "get_state": ([], []),
+ "gumbel": (["loc", "scale", "size"], [0.0, 1.0, None]),
+ "hypergeometric": (["ngood", "nbad", "nsample", "size"], [None]),
+ "laplace": (["loc", "scale", "size"], [0.0, 1.0, None]),
+ "logistic": (["loc", "scale", "size"], [0.0, 1.0, None]),
+ "lognormal": (["mean", "sigma", "size"], [0.0, 1.0, None]),
+ "logseries": (["p", "size"], [None]),
+ "multinomial": (["n", "pvals", "size"], [None]),
+ "multivariate_normal": (["mean", "cov", "size"], [None]),
+ "negative_binomial": (["n", "p", "size"], [None]),
+ "noncentral_chisquare": (["df", "nonc", "size"], [None]),
+ "noncentral_f": (["dfnum", "dfden", "nonc", "size"], [None]),
+ "normal": (["loc", "scale", "size"], [0.0, 1.0, None]),
+ "pareto": (["a", "size"], [None]),
+ "permutation": (["x"], []),
+ "poisson": (["lam", "size"], [1.0, None]),
+ "power": (["a", "size"], [None]),
+ "rand": (["args"], []),
+ "randint": (["low", "high", "size", "dtype"], [None, None, "l"]),
+ "randn": (["args"], []),
+ "random_integers": (["low", "high", "size"], [None, None]),
+ "random_sample": (["size"], [None]),
+ "rayleigh": (["scale", "size"], [1.0, None]),
+ "seed": (["seed"], [None]),
+ "set_state": (["state"], []),
+ "shuffle": (["x"], []),
+ "standard_cauchy": (["size"], [None]),
+ "standard_exponential": (["size"], [None]),
+ "standard_gamma": (["shape", "size"], [None]),
+ "standard_normal": (["size"], [None]),
+ "standard_t": (["df", "size"], [None]),
+ "triangular": (["left", "mode", "right", "size"], [None]),
+ "uniform": (["low", "high", "size"], [0.0, 1.0, None]),
+ "vonmises": (["mu", "kappa", "size"], [None]),
+ "wald": (["mean", "scale", "size"], [None]),
+ "weibull": (["a", "size"], [None]),
+ "zipf": (["a", "size"], [None]),
+ }
def _inferred_numpy_attribute(self, func_name):
- node = builder.extract_node("""
+ node = builder.extract_node(
+ """
import numpy.random.mtrand as tested_module
func = tested_module.{:s}
- func""".format(func_name))
+ func""".format(
+ func_name
+ )
+ )
return next(node.infer())
def test_numpy_random_mtrand_functions(self):
@@ -232,11 +308,16 @@ class NumpyBrainRandomMtrandTest(SubTestWrapper):
"""
Test the arguments names and default values.
"""
- for func, (exact_arg_names, exact_kwargs_default_values) in self.all_mtrand.items():
+ for (
+ func,
+ (exact_arg_names, exact_kwargs_default_values),
+ ) in self.all_mtrand.items():
with self.subTest(func=func):
inferred = self._inferred_numpy_attribute(func)
self.assertEqual(inferred.argnames(), exact_arg_names)
- default_args_values = [default.value for default in inferred.args.defaults]
+ default_args_values = [
+ default.value for default in inferred.args.defaults
+ ]
self.assertEqual(default_args_values, exact_kwargs_default_values)
@@ -245,23 +326,68 @@ class NumpyBrainCoreNumericTypesTest(SubTestWrapper):
"""
Test of all the missing types defined in numerictypes module.
"""
- all_types = ['uint16', 'uint32', 'uint64',
- 'float16', 'float32', 'float64', 'float96',
- 'complex64', 'complex128',
- 'complex192', 'timedelta64', 'datetime64', 'unicode_',
- 'str_', 'bool_', 'bool8', 'byte', 'int8', 'bytes0', 'bytes_',
- 'cdouble', 'cfloat', 'character', 'clongdouble',
- 'clongfloat', 'complexfloating', 'csingle', 'double',
- 'flexible', 'floating', 'half', 'inexact', 'int0',
- 'longcomplex', 'longdouble', 'longfloat',
- 'short', 'signedinteger', 'single', 'singlecomplex',
- 'str0', 'ubyte', 'uint', 'uint0', 'uintc', 'uintp',
- 'ulonglong', 'unsignedinteger', 'ushort', 'void0']
+
+ all_types = [
+ "uint16",
+ "uint32",
+ "uint64",
+ "float16",
+ "float32",
+ "float64",
+ "float96",
+ "complex64",
+ "complex128",
+ "complex192",
+ "timedelta64",
+ "datetime64",
+ "unicode_",
+ "str_",
+ "bool_",
+ "bool8",
+ "byte",
+ "int8",
+ "bytes0",
+ "bytes_",
+ "cdouble",
+ "cfloat",
+ "character",
+ "clongdouble",
+ "clongfloat",
+ "complexfloating",
+ "csingle",
+ "double",
+ "flexible",
+ "floating",
+ "half",
+ "inexact",
+ "int0",
+ "longcomplex",
+ "longdouble",
+ "longfloat",
+ "short",
+ "signedinteger",
+ "single",
+ "singlecomplex",
+ "str0",
+ "ubyte",
+ "uint",
+ "uint0",
+ "uintc",
+ "uintp",
+ "ulonglong",
+ "unsignedinteger",
+ "ushort",
+ "void0",
+ ]
def _inferred_numpy_attribute(self, attrib):
- node = builder.extract_node("""
+ node = builder.extract_node(
+ """
import numpy.core.numerictypes as tested_module
- missing_type = tested_module.{:s}""".format(attrib))
+ missing_type = tested_module.{:s}""".format(
+ attrib
+ )
+ )
return next(node.value.infer())
def test_numpy_core_types(self):
@@ -277,31 +403,110 @@ class NumpyBrainCoreNumericTypesTest(SubTestWrapper):
"""
Test that all generic derived types have specified methods
"""
- generic_methods = ['all', 'any', 'argmax', 'argmin', 'argsort',
- 'astype', 'base', 'byteswap', 'choose',
- 'clip', 'compress', 'conj', 'conjugate',
- 'copy', 'cumprod', 'cumsum', 'data',
- 'diagonal', 'dtype', 'dump', 'dumps', 'fill',
- 'flags', 'flat', 'flatten', 'getfield',
- 'imag', 'item', 'itemset', 'itemsize', 'max',
- 'mean', 'min', 'nbytes', 'ndim',
- 'newbyteorder', 'nonzero', 'prod', 'ptp',
- 'put', 'ravel', 'real', 'repeat', 'reshape',
- 'resize', 'round', 'searchsorted',
- 'setfield', 'setflags', 'shape', 'size',
- 'sort', 'squeeze', 'std', 'strides', 'sum',
- 'swapaxes', 'take', 'tobytes', 'tofile',
- 'tolist', 'tostring', 'trace', 'transpose',
- 'var', 'view']
-
- for type_ in ('bool_', 'bytes_', 'character', 'complex128',
- 'complex192', 'complex64', 'complexfloating',
- 'datetime64', 'flexible', 'float16', 'float32',
- 'float64', 'float96', 'floating', 'generic', 'inexact',
- 'int16', 'int32', 'int32', 'int64', 'int8', 'integer',
- 'number', 'signedinteger', 'str_',
- 'timedelta64', 'uint16', 'uint32', 'uint32', 'uint64',
- 'uint8', 'unsignedinteger', 'void'):
+ generic_methods = [
+ "all",
+ "any",
+ "argmax",
+ "argmin",
+ "argsort",
+ "astype",
+ "base",
+ "byteswap",
+ "choose",
+ "clip",
+ "compress",
+ "conj",
+ "conjugate",
+ "copy",
+ "cumprod",
+ "cumsum",
+ "data",
+ "diagonal",
+ "dtype",
+ "dump",
+ "dumps",
+ "fill",
+ "flags",
+ "flat",
+ "flatten",
+ "getfield",
+ "imag",
+ "item",
+ "itemset",
+ "itemsize",
+ "max",
+ "mean",
+ "min",
+ "nbytes",
+ "ndim",
+ "newbyteorder",
+ "nonzero",
+ "prod",
+ "ptp",
+ "put",
+ "ravel",
+ "real",
+ "repeat",
+ "reshape",
+ "resize",
+ "round",
+ "searchsorted",
+ "setfield",
+ "setflags",
+ "shape",
+ "size",
+ "sort",
+ "squeeze",
+ "std",
+ "strides",
+ "sum",
+ "swapaxes",
+ "take",
+ "tobytes",
+ "tofile",
+ "tolist",
+ "tostring",
+ "trace",
+ "transpose",
+ "var",
+ "view",
+ ]
+
+ for type_ in (
+ "bool_",
+ "bytes_",
+ "character",
+ "complex128",
+ "complex192",
+ "complex64",
+ "complexfloating",
+ "datetime64",
+ "flexible",
+ "float16",
+ "float32",
+ "float64",
+ "float96",
+ "floating",
+ "generic",
+ "inexact",
+ "int16",
+ "int32",
+ "int32",
+ "int64",
+ "int8",
+ "integer",
+ "number",
+ "signedinteger",
+ "str_",
+ "timedelta64",
+ "uint16",
+ "uint32",
+ "uint32",
+ "uint64",
+ "uint8",
+ "unsignedinteger",
+ "void",
+ ):
with self.subTest(typ=type_):
inferred = self._inferred_numpy_attribute(type_)
for meth in generic_methods:
@@ -312,18 +517,56 @@ class NumpyBrainCoreNumericTypesTest(SubTestWrapper):
"""
Test that all generic derived types have specified attributes
"""
- generic_attr = ['base', 'data', 'dtype', 'flags', 'flat', 'imag',
- 'itemsize', 'nbytes', 'ndim', 'real', 'size',
- 'strides']
-
- for type_ in ('bool_', 'bytes_', 'character', 'complex128',
- 'complex192', 'complex64', 'complexfloating',
- 'datetime64', 'flexible', 'float16', 'float32',
- 'float64', 'float96', 'floating', 'generic', 'inexact',
- 'int16', 'int32', 'int32', 'int64', 'int8', 'integer',
- 'number', 'signedinteger', 'str_',
- 'timedelta64', 'uint16', 'uint32', 'uint32', 'uint64',
- 'uint8', 'unsignedinteger', 'void'):
+ generic_attr = [
+ "base",
+ "data",
+ "dtype",
+ "flags",
+ "flat",
+ "imag",
+ "itemsize",
+ "nbytes",
+ "ndim",
+ "real",
+ "size",
+ "strides",
+ ]
+
+ for type_ in (
+ "bool_",
+ "bytes_",
+ "character",
+ "complex128",
+ "complex192",
+ "complex64",
+ "complexfloating",
+ "datetime64",
+ "flexible",
+ "float16",
+ "float32",
+ "float64",
+ "float96",
+ "floating",
+ "generic",
+ "inexact",
+ "int16",
+ "int32",
+ "int32",
+ "int64",
+ "int8",
+ "integer",
+ "number",
+ "signedinteger",
+ "str_",
+ "timedelta64",
+ "uint16",
+ "uint32",
+ "uint32",
+ "uint64",
+ "uint8",
+ "unsignedinteger",
+ "void",
+ ):
with self.subTest(typ=type_):
inferred = self._inferred_numpy_attribute(type_)
for attr in generic_attr:
@@ -331,5 +574,5 @@ class NumpyBrainCoreNumericTypesTest(SubTestWrapper):
self.assertNotEqual(len(inferred.getattr(attr)), 0)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/tests/unittest_builder.py b/astroid/tests/unittest_builder.py
index d76a5060..d02b581f 100644
--- a/astroid/tests/unittest_builder.py
+++ b/astroid/tests/unittest_builder.py
@@ -34,9 +34,8 @@ BUILTINS = builtins.__name__
class FromToLineNoTest(unittest.TestCase):
-
def setUp(self):
- self.astroid = resources.build_file('data/format.py')
+ self.astroid = resources.build_file("data/format.py")
def test_callfunc_lineno(self):
stmts = self.astroid.body
@@ -57,10 +56,10 @@ class FromToLineNoTest(unittest.TestCase):
self.assertEqual(name.tolineno, 4)
strarg = callfunc.args[0]
self.assertIsInstance(strarg, nodes.Const)
- if hasattr(sys, 'pypy_version_info'):
+ if hasattr(sys, "pypy_version_info"):
lineno = 4
else:
- lineno = 5 # no way for this one in CPython (is 4 actually)
+ lineno = 5 # no way for this one in CPython (is 4 actually)
self.assertEqual(strarg.fromlineno, lineno)
self.assertEqual(strarg.tolineno, lineno)
namearg = callfunc.args[1]
@@ -86,8 +85,8 @@ class FromToLineNoTest(unittest.TestCase):
self.assertEqual(name.tolineno, 10)
for i, arg in enumerate(callfunc.args):
self.assertIsInstance(arg, nodes.Const)
- self.assertEqual(arg.fromlineno, 10+i)
- self.assertEqual(arg.tolineno, 10+i)
+ self.assertEqual(arg.fromlineno, 10 + i)
+ self.assertEqual(arg.tolineno, 10 + i)
def test_function_lineno(self):
stmts = self.astroid.body
@@ -107,17 +106,22 @@ class FromToLineNoTest(unittest.TestCase):
if sys.version_info < (3, 0):
self.assertEqual(function.blockstart_tolineno, 17)
else:
- self.skipTest('FIXME http://bugs.python.org/issue10445 '
- '(no line number on function args)')
+ self.skipTest(
+ "FIXME http://bugs.python.org/issue10445 "
+ "(no line number on function args)"
+ )
def test_decorated_function_lineno(self):
- astroid = builder.parse('''
+ astroid = builder.parse(
+ """
@decorator
def function(
arg):
print (arg)
- ''', __name__)
- function = astroid['function']
+ """,
+ __name__,
+ )
+ function = astroid["function"]
# XXX discussable, but that's what is expected by pylint right now
self.assertEqual(function.fromlineno, 3)
self.assertEqual(function.tolineno, 5)
@@ -126,9 +130,10 @@ class FromToLineNoTest(unittest.TestCase):
if sys.version_info < (3, 0):
self.assertEqual(function.blockstart_tolineno, 4)
else:
- self.skipTest('FIXME http://bugs.python.org/issue10445 '
- '(no line number on function args)')
-
+ self.skipTest(
+ "FIXME http://bugs.python.org/issue10445 "
+ "(no line number on function args)"
+ )
def test_class_lineno(self):
stmts = self.astroid.body
@@ -162,86 +167,98 @@ class FromToLineNoTest(unittest.TestCase):
self.assertEqual(if_.orelse[1].tolineno, 27)
def test_for_while_lineno(self):
- for code in ('''
+ for code in (
+ """
for a in range(4):
print (a)
break
else:
print ("bouh")
- ''', '''
+ """,
+ """
while a:
print (a)
break
else:
print ("bouh")
- '''):
+ """,
+ ):
astroid = builder.parse(code, __name__)
stmt = astroid.body[0]
self.assertEqual(stmt.fromlineno, 2)
self.assertEqual(stmt.tolineno, 6)
self.assertEqual(stmt.blockstart_tolineno, 2)
- self.assertEqual(stmt.orelse[0].fromlineno, 6) # XXX
+ self.assertEqual(stmt.orelse[0].fromlineno, 6) # XXX
self.assertEqual(stmt.orelse[0].tolineno, 6)
def test_try_except_lineno(self):
- astroid = builder.parse('''
+ astroid = builder.parse(
+ """
try:
print (a)
except:
pass
else:
print ("bouh")
- ''', __name__)
+ """,
+ __name__,
+ )
try_ = astroid.body[0]
self.assertEqual(try_.fromlineno, 2)
self.assertEqual(try_.tolineno, 7)
self.assertEqual(try_.blockstart_tolineno, 2)
- self.assertEqual(try_.orelse[0].fromlineno, 7) # XXX
+ self.assertEqual(try_.orelse[0].fromlineno, 7) # XXX
self.assertEqual(try_.orelse[0].tolineno, 7)
hdlr = try_.handlers[0]
self.assertEqual(hdlr.fromlineno, 4)
self.assertEqual(hdlr.tolineno, 5)
self.assertEqual(hdlr.blockstart_tolineno, 4)
-
def test_try_finally_lineno(self):
- astroid = builder.parse('''
+ astroid = builder.parse(
+ """
try:
print (a)
finally:
print ("bouh")
- ''', __name__)
+ """,
+ __name__,
+ )
try_ = astroid.body[0]
self.assertEqual(try_.fromlineno, 2)
self.assertEqual(try_.tolineno, 5)
self.assertEqual(try_.blockstart_tolineno, 2)
- self.assertEqual(try_.finalbody[0].fromlineno, 5) # XXX
+ self.assertEqual(try_.finalbody[0].fromlineno, 5) # XXX
self.assertEqual(try_.finalbody[0].tolineno, 5)
-
def test_try_finally_25_lineno(self):
- astroid = builder.parse('''
+ astroid = builder.parse(
+ """
try:
print (a)
except:
pass
finally:
print ("bouh")
- ''', __name__)
+ """,
+ __name__,
+ )
try_ = astroid.body[0]
self.assertEqual(try_.fromlineno, 2)
self.assertEqual(try_.tolineno, 7)
self.assertEqual(try_.blockstart_tolineno, 2)
- self.assertEqual(try_.finalbody[0].fromlineno, 7) # XXX
+ self.assertEqual(try_.finalbody[0].fromlineno, 7) # XXX
self.assertEqual(try_.finalbody[0].tolineno, 7)
-
def test_with_lineno(self):
- astroid = builder.parse('''
+ astroid = builder.parse(
+ """
from __future__ import with_statement
with file("/tmp/pouet") as f:
print (f)
- ''', __name__)
+ """,
+ __name__,
+ )
with_ = astroid.body[1]
self.assertEqual(with_.fromlineno, 3)
self.assertEqual(with_.tolineno, 4)
@@ -249,13 +266,12 @@ class FromToLineNoTest(unittest.TestCase):
class BuilderTest(unittest.TestCase):
-
def setUp(self):
self.builder = builder.AstroidBuilder()
def test_data_build_null_bytes(self):
with self.assertRaises(exceptions.AstroidSyntaxError):
- self.builder.string_build('\x00')
+ self.builder.string_build("\x00")
def test_data_build_invalid_x_escape(self):
with self.assertRaises(exceptions.AstroidSyntaxError):
@@ -263,38 +279,38 @@ class BuilderTest(unittest.TestCase):
def test_missing_newline(self):
"""check that a file with no trailing new line is parseable"""
- resources.build_file('data/noendingnewline.py')
+ resources.build_file("data/noendingnewline.py")
def test_missing_file(self):
with self.assertRaises(exceptions.AstroidBuildingError):
- resources.build_file('data/inexistant.py')
+ resources.build_file("data/inexistant.py")
def test_inspect_build0(self):
"""test astroid tree build from a living object"""
builtin_ast = MANAGER.ast_from_module_name(BUILTINS)
# just check type and object are there
- builtin_ast.getattr('type')
- objectastroid = builtin_ast.getattr('object')[0]
- self.assertIsInstance(objectastroid.getattr('__new__')[0], nodes.FunctionDef)
+ builtin_ast.getattr("type")
+ objectastroid = builtin_ast.getattr("object")[0]
+ self.assertIsInstance(objectastroid.getattr("__new__")[0], nodes.FunctionDef)
# check open file alias
- builtin_ast.getattr('open')
+ builtin_ast.getattr("open")
# check 'help' is there (defined dynamically by site.py)
- builtin_ast.getattr('help')
+ builtin_ast.getattr("help")
# check property has __init__
- pclass = builtin_ast['property']
- self.assertIn('__init__', pclass)
- self.assertIsInstance(builtin_ast['None'], nodes.Const)
- self.assertIsInstance(builtin_ast['True'], nodes.Const)
- self.assertIsInstance(builtin_ast['False'], nodes.Const)
- self.assertIsInstance(builtin_ast['Exception'], nodes.ClassDef)
- self.assertIsInstance(builtin_ast['NotImplementedError'], nodes.ClassDef)
+ pclass = builtin_ast["property"]
+ self.assertIn("__init__", pclass)
+ self.assertIsInstance(builtin_ast["None"], nodes.Const)
+ self.assertIsInstance(builtin_ast["True"], nodes.Const)
+ self.assertIsInstance(builtin_ast["False"], nodes.Const)
+ self.assertIsInstance(builtin_ast["Exception"], nodes.ClassDef)
+ self.assertIsInstance(builtin_ast["NotImplementedError"], nodes.ClassDef)
def test_inspect_build1(self):
- time_ast = MANAGER.ast_from_module_name('time')
+ time_ast = MANAGER.ast_from_module_name("time")
self.assertTrue(time_ast)
- self.assertEqual(time_ast['time'].args.defaults, [])
+ self.assertEqual(time_ast["time"].args.defaults, [])
- if os.name == 'java':
+ if os.name == "java":
test_inspect_build1 = unittest.expectedFailure(test_inspect_build1)
def test_inspect_build2(self):
@@ -302,68 +318,71 @@ class BuilderTest(unittest.TestCase):
try:
from mx import DateTime
except ImportError:
- self.skipTest('test skipped: mxDateTime is not available')
+ self.skipTest("test skipped: mxDateTime is not available")
else:
dt_ast = self.builder.inspect_build(DateTime)
- dt_ast.getattr('DateTime')
+ dt_ast.getattr("DateTime")
# this one is failing since DateTimeType.__module__ = 'builtins' !
- #dt_ast.getattr('DateTimeType')
+ # dt_ast.getattr('DateTimeType')
def test_inspect_build3(self):
self.builder.inspect_build(unittest)
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_inspect_build_instance(self):
"""test astroid tree build from a living object"""
import exceptions as builtin_exceptions
+
builtin_ast = self.builder.inspect_build(builtin_exceptions)
- fclass = builtin_ast['OSError']
+ fclass = builtin_ast["OSError"]
# things like OSError.strerror are now (2.5) data descriptors on the
# class instead of entries in the __dict__ of an instance
container = fclass
- self.assertIn('errno', container)
- self.assertIn('strerror', container)
- self.assertIn('filename', container)
+ self.assertIn("errno", container)
+ self.assertIn("strerror", container)
+ self.assertIn("filename", container)
def test_inspect_build_type_object(self):
builtin_ast = MANAGER.ast_from_module_name(BUILTINS)
- inferred = list(builtin_ast.igetattr('object'))
+ inferred = list(builtin_ast.igetattr("object"))
self.assertEqual(len(inferred), 1)
inferred = inferred[0]
- self.assertEqual(inferred.name, 'object')
- inferred.as_string() # no crash test
+ self.assertEqual(inferred.name, "object")
+ inferred.as_string() # no crash test
- inferred = list(builtin_ast.igetattr('type'))
+ inferred = list(builtin_ast.igetattr("type"))
self.assertEqual(len(inferred), 1)
inferred = inferred[0]
- self.assertEqual(inferred.name, 'type')
- inferred.as_string() # no crash test
+ self.assertEqual(inferred.name, "type")
+ inferred.as_string() # no crash test
def test_inspect_transform_module(self):
# ensure no cached version of the time module
- MANAGER._mod_file_cache.pop(('time', None), None)
- MANAGER.astroid_cache.pop('time', None)
+ MANAGER._mod_file_cache.pop(("time", None), None)
+ MANAGER.astroid_cache.pop("time", None)
+
def transform_time(node):
- if node.name == 'time':
+ if node.name == "time":
node.transformed = True
+
MANAGER.register_transform(nodes.Module, transform_time)
try:
- time_ast = MANAGER.ast_from_module_name('time')
- self.assertTrue(getattr(time_ast, 'transformed', False))
+ time_ast = MANAGER.ast_from_module_name("time")
+ self.assertTrue(getattr(time_ast, "transformed", False))
finally:
MANAGER.unregister_transform(nodes.Module, transform_time)
def test_package_name(self):
"""test base properties and method of an astroid module"""
- datap = resources.build_file('data/__init__.py', 'data')
- self.assertEqual(datap.name, 'data')
+ datap = resources.build_file("data/__init__.py", "data")
+ self.assertEqual(datap.name, "data")
self.assertEqual(datap.package, 1)
- datap = resources.build_file('data/__init__.py', 'data.__init__')
- self.assertEqual(datap.name, 'data')
+ datap = resources.build_file("data/__init__.py", "data.__init__")
+ self.assertEqual(datap.name, "data")
self.assertEqual(datap.package, 1)
- datap = resources.build_file('data/tmp__init__.py', 'data.tmp__init__')
- self.assertEqual(datap.name, 'data.tmp__init__')
+ datap = resources.build_file("data/tmp__init__.py", "data.tmp__init__")
+ self.assertEqual(datap.name, "data.tmp__init__")
self.assertEqual(datap.package, 0)
def test_yield_parent(self):
@@ -384,10 +403,10 @@ class BuilderTest(unittest.TestCase):
def test_object(self):
obj_ast = self.builder.inspect_build(object)
- self.assertIn('__setattr__', obj_ast)
+ self.assertIn("__setattr__", obj_ast)
def test_newstyle_detection(self):
- data = '''
+ data = """
class A:
"old style"
@@ -407,17 +426,17 @@ class BuilderTest(unittest.TestCase):
class F:
"new style"
- '''
+ """
mod_ast = builder.parse(data, __name__)
- self.assertTrue(mod_ast['A'].newstyle)
- self.assertTrue(mod_ast['B'].newstyle)
- self.assertTrue(mod_ast['E'].newstyle)
- self.assertTrue(mod_ast['C'].newstyle)
- self.assertTrue(mod_ast['D'].newstyle)
- self.assertTrue(mod_ast['F'].newstyle)
+ self.assertTrue(mod_ast["A"].newstyle)
+ self.assertTrue(mod_ast["B"].newstyle)
+ self.assertTrue(mod_ast["E"].newstyle)
+ self.assertTrue(mod_ast["C"].newstyle)
+ self.assertTrue(mod_ast["D"].newstyle)
+ self.assertTrue(mod_ast["F"].newstyle)
def test_globals(self):
- data = '''
+ data = """
CSTE = 1
def update_global():
@@ -427,39 +446,39 @@ class BuilderTest(unittest.TestCase):
def global_no_effect():
global CSTE2
print (CSTE)
- '''
+ """
astroid = builder.parse(data, __name__)
- self.assertEqual(len(astroid.getattr('CSTE')), 2)
- self.assertIsInstance(astroid.getattr('CSTE')[0], nodes.AssignName)
- self.assertEqual(astroid.getattr('CSTE')[0].fromlineno, 2)
- self.assertEqual(astroid.getattr('CSTE')[1].fromlineno, 6)
+ self.assertEqual(len(astroid.getattr("CSTE")), 2)
+ self.assertIsInstance(astroid.getattr("CSTE")[0], nodes.AssignName)
+ self.assertEqual(astroid.getattr("CSTE")[0].fromlineno, 2)
+ self.assertEqual(astroid.getattr("CSTE")[1].fromlineno, 6)
with self.assertRaises(exceptions.AttributeInferenceError):
- astroid.getattr('CSTE2')
+ astroid.getattr("CSTE2")
with self.assertRaises(exceptions.InferenceError):
- next(astroid['global_no_effect'].ilookup('CSTE2'))
+ next(astroid["global_no_effect"].ilookup("CSTE2"))
def test_socket_build(self):
import socket
+
astroid = self.builder.module_build(socket)
# XXX just check the first one. Actually 3 objects are inferred (look at
# the socket module) but the last one as those attributes dynamically
# set and astroid is missing this.
- for fclass in astroid.igetattr('socket'):
- self.assertIn('connect', fclass)
- self.assertIn('send', fclass)
- self.assertIn('close', fclass)
+ for fclass in astroid.igetattr("socket"):
+ self.assertIn("connect", fclass)
+ self.assertIn("send", fclass)
+ self.assertIn("close", fclass)
break
def test_gen_expr_var_scope(self):
- data = 'l = list(n for n in range(10))\n'
+ data = "l = list(n for n in range(10))\n"
astroid = builder.parse(data, __name__)
# n unavailable outside gen expr scope
- self.assertNotIn('n', astroid)
+ self.assertNotIn("n", astroid)
# test n is inferable anyway
- n = test_utils.get_name_node(astroid, 'n')
+ n = test_utils.get_name_node(astroid, "n")
self.assertIsNot(n.scope(), astroid)
- self.assertEqual([i.__class__ for i in n.infer()],
- [util.Uninferable.__class__])
+ self.assertEqual([i.__class__ for i in n.infer()], [util.Uninferable.__class__])
def test_no_future_imports(self):
mod = builder.parse("import sys")
@@ -467,88 +486,95 @@ class BuilderTest(unittest.TestCase):
def test_future_imports(self):
mod = builder.parse("from __future__ import print_function")
- self.assertEqual({'print_function'}, mod.future_imports)
+ self.assertEqual({"print_function"}, mod.future_imports)
def test_two_future_imports(self):
- mod = builder.parse("""
+ mod = builder.parse(
+ """
from __future__ import print_function
from __future__ import absolute_import
- """)
- self.assertEqual({'print_function', 'absolute_import'}, mod.future_imports)
+ """
+ )
+ self.assertEqual({"print_function", "absolute_import"}, mod.future_imports)
def test_inferred_build(self):
- code = '''
+ code = """
class A: pass
A.type = "class"
def A_assign_type(self):
print (self)
A.assign_type = A_assign_type
- '''
+ """
astroid = builder.parse(code)
- lclass = list(astroid.igetattr('A'))
+ lclass = list(astroid.igetattr("A"))
self.assertEqual(len(lclass), 1)
lclass = lclass[0]
- self.assertIn('assign_type', lclass.locals)
- self.assertIn('type', lclass.locals)
+ self.assertIn("assign_type", lclass.locals)
+ self.assertIn("type", lclass.locals)
def test_augassign_attr(self):
- builder.parse("""
+ builder.parse(
+ """
class Counter:
v = 0
def inc(self):
self.v += 1
- """, __name__)
+ """,
+ __name__,
+ )
# TODO: Check self.v += 1 generate AugAssign(AssAttr(...)),
# not AugAssign(GetAttr(AssName...))
def test_inferred_dont_pollute(self):
- code = '''
+ code = """
def func(a=None):
a.custom_attr = 0
def func2(a={}):
a.custom_attr = 0
- '''
+ """
builder.parse(code)
nonetype = nodes.const_factory(None)
# pylint: disable=no-member; Infers two potential values
- self.assertNotIn('custom_attr', nonetype.locals)
- self.assertNotIn('custom_attr', nonetype.instance_attrs)
+ self.assertNotIn("custom_attr", nonetype.locals)
+ self.assertNotIn("custom_attr", nonetype.instance_attrs)
nonetype = nodes.const_factory({})
- self.assertNotIn('custom_attr', nonetype.locals)
- self.assertNotIn('custom_attr', nonetype.instance_attrs)
+ self.assertNotIn("custom_attr", nonetype.locals)
+ self.assertNotIn("custom_attr", nonetype.instance_attrs)
def test_asstuple(self):
- code = 'a, b = range(2)'
+ code = "a, b = range(2)"
astroid = builder.parse(code)
- self.assertIn('b', astroid.locals)
- code = '''
+ self.assertIn("b", astroid.locals)
+ code = """
def visit_if(self, node):
node.test, body = node.tests[0]
- '''
+ """
astroid = builder.parse(code)
- self.assertIn('body', astroid['visit_if'].locals)
+ self.assertIn("body", astroid["visit_if"].locals)
def test_build_constants(self):
- '''test expected values of constants after rebuilding'''
- code = '''
+ """test expected values of constants after rebuilding"""
+ code = """
def func():
return None
return
return 'None'
- '''
+ """
astroid = builder.parse(code)
none, nothing, chain = [ret.value for ret in astroid.body[0].body]
self.assertIsInstance(none, nodes.Const)
self.assertIsNone(none.value)
self.assertIsNone(nothing)
self.assertIsInstance(chain, nodes.Const)
- self.assertEqual(chain.value, 'None')
+ self.assertEqual(chain.value, "None")
def test_not_implemented(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
NotImplemented #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, NotImplemented)
@@ -556,18 +582,18 @@ class BuilderTest(unittest.TestCase):
class FileBuildTest(unittest.TestCase):
def setUp(self):
- self.module = resources.build_file('data/module.py', 'data.module')
+ self.module = resources.build_file("data/module.py", "data.module")
def test_module_base_props(self):
"""test base properties and method of an astroid module"""
module = self.module
- self.assertEqual(module.name, 'data.module')
+ self.assertEqual(module.name, "data.module")
self.assertEqual(module.doc, "test module for astroid\n")
self.assertEqual(module.fromlineno, 0)
self.assertIsNone(module.parent)
self.assertEqual(module.frame(), module)
self.assertEqual(module.root(), module)
- self.assertEqual(module.file, os.path.abspath(resources.find('data/module.py')))
+ self.assertEqual(module.file, os.path.abspath(resources.find("data/module.py")))
self.assertEqual(module.pure_python, 1)
self.assertEqual(module.package, 0)
self.assertFalse(module.is_statement)
@@ -580,39 +606,48 @@ class FileBuildTest(unittest.TestCase):
_locals = module.locals
self.assertIs(_locals, module.globals)
keys = sorted(_locals.keys())
- should = ['MY_DICT', 'NameNode', 'YO', 'YOUPI',
- '__revision__', 'global_access', 'modutils', 'four_args',
- 'os', 'redirect']
+ should = [
+ "MY_DICT",
+ "NameNode",
+ "YO",
+ "YOUPI",
+ "__revision__",
+ "global_access",
+ "modutils",
+ "four_args",
+ "os",
+ "redirect",
+ ]
should.sort()
self.assertEqual(keys, sorted(should))
def test_function_base_props(self):
"""test base properties and method of an astroid function"""
module = self.module
- function = module['global_access']
- self.assertEqual(function.name, 'global_access')
- self.assertEqual(function.doc, 'function test')
+ function = module["global_access"]
+ self.assertEqual(function.name, "global_access")
+ self.assertEqual(function.doc, "function test")
self.assertEqual(function.fromlineno, 11)
self.assertTrue(function.parent)
self.assertEqual(function.frame(), function)
self.assertEqual(function.parent.frame(), module)
self.assertEqual(function.root(), module)
- self.assertEqual([n.name for n in function.args.args], ['key', 'val'])
- self.assertEqual(function.type, 'function')
+ self.assertEqual([n.name for n in function.args.args], ["key", "val"])
+ self.assertEqual(function.type, "function")
def test_function_locals(self):
"""test the 'locals' dictionary of an astroid function"""
- _locals = self.module['global_access'].locals
+ _locals = self.module["global_access"].locals
self.assertEqual(len(_locals), 4)
keys = sorted(_locals.keys())
- self.assertEqual(keys, ['i', 'key', 'local', 'val'])
+ self.assertEqual(keys, ["i", "key", "local", "val"])
def test_class_base_props(self):
"""test base properties and method of an astroid class"""
module = self.module
- klass = module['YO']
- self.assertEqual(klass.name, 'YO')
- self.assertEqual(klass.doc, 'hehe\n haha')
+ klass = module["YO"]
+ self.assertEqual(klass.name, "YO")
+ self.assertEqual(klass.doc, "hehe\n haha")
self.assertEqual(klass.fromlineno, 25)
self.assertTrue(klass.parent)
self.assertEqual(klass.frame(), klass)
@@ -624,76 +659,80 @@ class FileBuildTest(unittest.TestCase):
def test_class_locals(self):
"""test the 'locals' dictionary of an astroid class"""
module = self.module
- klass1 = module['YO']
+ klass1 = module["YO"]
locals1 = klass1.locals
keys = sorted(locals1.keys())
- assert_keys = ['__init__', '__module__', '__qualname__', 'a']
+ assert_keys = ["__init__", "__module__", "__qualname__", "a"]
if sys.version_info < (3, 3):
- assert_keys.pop(assert_keys.index('__qualname__'))
+ assert_keys.pop(assert_keys.index("__qualname__"))
self.assertEqual(keys, assert_keys)
- klass2 = module['YOUPI']
+ klass2 = module["YOUPI"]
locals2 = klass2.locals
keys = locals2.keys()
assert_keys = [
- '__init__', '__module__', '__qualname__', 'class_attr', 'class_method',
- 'method', 'static_method'
+ "__init__",
+ "__module__",
+ "__qualname__",
+ "class_attr",
+ "class_method",
+ "method",
+ "static_method",
]
if sys.version_info < (3, 3):
- assert_keys.pop(assert_keys.index('__qualname__'))
+ assert_keys.pop(assert_keys.index("__qualname__"))
self.assertEqual(sorted(keys), assert_keys)
def test_class_instance_attrs(self):
module = self.module
- klass1 = module['YO']
- klass2 = module['YOUPI']
- self.assertEqual(list(klass1.instance_attrs.keys()), ['yo'])
- self.assertEqual(list(klass2.instance_attrs.keys()), ['member'])
+ klass1 = module["YO"]
+ klass2 = module["YOUPI"]
+ self.assertEqual(list(klass1.instance_attrs.keys()), ["yo"])
+ self.assertEqual(list(klass2.instance_attrs.keys()), ["member"])
def test_class_basenames(self):
module = self.module
- klass1 = module['YO']
- klass2 = module['YOUPI']
+ klass1 = module["YO"]
+ klass2 = module["YOUPI"]
self.assertEqual(klass1.basenames, [])
- self.assertEqual(klass2.basenames, ['YO'])
+ self.assertEqual(klass2.basenames, ["YO"])
def test_method_base_props(self):
"""test base properties and method of an astroid method"""
- klass2 = self.module['YOUPI']
+ klass2 = self.module["YOUPI"]
# "normal" method
- method = klass2['method']
- self.assertEqual(method.name, 'method')
- self.assertEqual([n.name for n in method.args.args], ['self'])
- self.assertEqual(method.doc, 'method\n test')
+ method = klass2["method"]
+ self.assertEqual(method.name, "method")
+ self.assertEqual([n.name for n in method.args.args], ["self"])
+ self.assertEqual(method.doc, "method\n test")
self.assertEqual(method.fromlineno, 48)
- self.assertEqual(method.type, 'method')
+ self.assertEqual(method.type, "method")
# class method
- method = klass2['class_method']
- self.assertEqual([n.name for n in method.args.args], ['cls'])
- self.assertEqual(method.type, 'classmethod')
+ method = klass2["class_method"]
+ self.assertEqual([n.name for n in method.args.args], ["cls"])
+ self.assertEqual(method.type, "classmethod")
# static method
- method = klass2['static_method']
+ method = klass2["static_method"]
self.assertEqual(method.args.args, [])
- self.assertEqual(method.type, 'staticmethod')
+ self.assertEqual(method.type, "staticmethod")
def test_method_locals(self):
"""test the 'locals' dictionary of an astroid method"""
- method = self.module['YOUPI']['method']
+ method = self.module["YOUPI"]["method"]
_locals = method.locals
keys = sorted(_locals)
if sys.version_info < (3, 0):
self.assertEqual(len(_locals), 5)
- self.assertEqual(keys, ['a', 'autre', 'b', 'local', 'self'])
- else:# ListComp variables are no more accessible outside
+ self.assertEqual(keys, ["a", "autre", "b", "local", "self"])
+ else: # ListComp variables are no more accessible outside
self.assertEqual(len(_locals), 4)
- self.assertEqual(keys, ['__class__', 'autre', 'local', 'self'])
+ self.assertEqual(keys, ["__class__", "autre", "local", "self"])
def test_unknown_encoding(self):
with self.assertRaises(exceptions.AstroidSyntaxError):
- resources.build_file('data/invalid_encoding.py')
+ resources.build_file("data/invalid_encoding.py")
class ModuleBuildTest(resources.SysPathSetup, FileBuildTest):
-
def setUp(self):
super(ModuleBuildTest, self).setUp()
abuilder = builder.AstroidBuilder()
@@ -701,9 +740,9 @@ class ModuleBuildTest(resources.SysPathSetup, FileBuildTest):
import data.module
except ImportError:
# Make pylint happy.
- self.skipTest('Unable to load data.module')
+ self.skipTest("Unable to load data.module")
else:
- self.module = abuilder.module_build(data.module, 'data.module')
+ self.module = abuilder.module_build(data.module, "data.module")
def test_module_build_dunder_file():
@@ -712,5 +751,5 @@ def test_module_build_dunder_file():
assert module.path[0] == collections.__file__
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/tests/unittest_helpers.py b/astroid/tests/unittest_helpers.py
index 25f5bf8f..8ed07ede 100644
--- a/astroid/tests/unittest_helpers.py
+++ b/astroid/tests/unittest_helpers.py
@@ -18,7 +18,6 @@ from astroid import util
class TestHelpers(unittest.TestCase):
-
def setUp(self):
builtins_name = builtins.__name__
astroid_manager = manager.AstroidManager()
@@ -40,17 +39,17 @@ class TestHelpers(unittest.TestCase):
def test_object_type(self):
pairs = [
- ('1', self._extract('int')),
- ('[]', self._extract('list')),
- ('{1, 2, 3}', self._extract('set')),
- ('{1:2, 4:3}', self._extract('dict')),
- ('type', self._extract('type')),
- ('object', self._extract('type')),
- ('object()', self._extract('object')),
- ('lambda: None', self._build_custom_builtin('function')),
- ('len', self._build_custom_builtin('builtin_function_or_method')),
- ('None', self._build_custom_builtin('NoneType')),
- ('import sys\nsys#@', self._build_custom_builtin('module')),
+ ("1", self._extract("int")),
+ ("[]", self._extract("list")),
+ ("{1, 2, 3}", self._extract("set")),
+ ("{1:2, 4:3}", self._extract("dict")),
+ ("type", self._extract("type")),
+ ("object", self._extract("type")),
+ ("object()", self._extract("object")),
+ ("lambda: None", self._build_custom_builtin("function")),
+ ("len", self._build_custom_builtin("builtin_function_or_method")),
+ ("None", self._build_custom_builtin("NoneType")),
+ ("import sys\nsys#@", self._build_custom_builtin("module")),
]
for code, expected in pairs:
node = builder.extract_node(code)
@@ -58,7 +57,8 @@ class TestHelpers(unittest.TestCase):
self.assert_classes_equal(objtype, expected)
def test_object_type_classes_and_functions(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
def generator():
yield
@@ -78,50 +78,54 @@ class TestHelpers(unittest.TestCase):
A.static_method #@
A().static_method #@
generator() #@
- ''')
+ """
+ )
from_self = helpers.object_type(ast_nodes[0])
cls = next(ast_nodes[1].infer())
self.assert_classes_equal(from_self, cls)
cls_type = helpers.object_type(ast_nodes[1])
- self.assert_classes_equal(cls_type, self._extract('type'))
+ self.assert_classes_equal(cls_type, self._extract("type"))
instance_type = helpers.object_type(ast_nodes[2])
cls = next(ast_nodes[2].infer())._proxied
self.assert_classes_equal(instance_type, cls)
expected_method_types = [
- (ast_nodes[3], 'function'),
- (ast_nodes[4], 'method'),
- (ast_nodes[5], 'method'),
- (ast_nodes[6], 'method'),
- (ast_nodes[7], 'function'),
- (ast_nodes[8], 'function'),
- (ast_nodes[9], 'generator'),
+ (ast_nodes[3], "function"),
+ (ast_nodes[4], "method"),
+ (ast_nodes[5], "method"),
+ (ast_nodes[6], "method"),
+ (ast_nodes[7], "function"),
+ (ast_nodes[8], "function"),
+ (ast_nodes[9], "generator"),
]
for node, expected in expected_method_types:
node_type = helpers.object_type(node)
expected_type = self._build_custom_builtin(expected)
self.assert_classes_equal(node_type, expected_type)
- @test_utils.require_version(minver='3.0')
+ @test_utils.require_version(minver="3.0")
def test_object_type_metaclasses(self):
- module = builder.parse('''
+ module = builder.parse(
+ """
import abc
class Meta(metaclass=abc.ABCMeta):
pass
meta_instance = Meta()
- ''')
- meta_type = helpers.object_type(module['Meta'])
- self.assert_classes_equal(meta_type, module['Meta'].metaclass())
+ """
+ )
+ meta_type = helpers.object_type(module["Meta"])
+ self.assert_classes_equal(meta_type, module["Meta"].metaclass())
- meta_instance = next(module['meta_instance'].infer())
+ meta_instance = next(module["meta_instance"].infer())
instance_type = helpers.object_type(meta_instance)
- self.assert_classes_equal(instance_type, module['Meta'])
+ self.assert_classes_equal(instance_type, module["Meta"])
- @test_utils.require_version(minver='3.0')
+ @test_utils.require_version(minver="3.0")
def test_object_type_most_derived(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
class A(type):
def __new__(*args, **kwargs):
return type.__new__(*args, **kwargs)
@@ -131,21 +135,25 @@ class TestHelpers(unittest.TestCase):
# The most derived metaclass of D is A rather than type.
class D(B , C): #@
pass
- ''')
+ """
+ )
metaclass = node.metaclass()
- self.assertEqual(metaclass.name, 'A')
+ self.assertEqual(metaclass.name, "A")
obj_type = helpers.object_type(node)
self.assertEqual(metaclass, obj_type)
def test_inference_errors(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
from unknown import Unknown
u = Unknown #@
- ''')
+ """
+ )
self.assertEqual(helpers.object_type(node), util.Uninferable)
def test_object_type_too_many_types(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
from unknown import Unknown
def test(x):
if x:
@@ -153,24 +161,27 @@ class TestHelpers(unittest.TestCase):
else:
return 1
test(Unknown) #@
- ''')
+ """
+ )
self.assertEqual(helpers.object_type(node), util.Uninferable)
def test_is_subtype(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class int_subclass(int):
pass
class A(object): pass #@
class B(A): pass #@
class C(A): pass #@
int_subclass() #@
- ''')
+ """
+ )
cls_a = ast_nodes[0]
cls_b = ast_nodes[1]
cls_c = ast_nodes[2]
int_subclass = ast_nodes[3]
int_subclass = helpers.object_type(next(int_subclass.infer()))
- base_int = self._extract('int')
+ base_int = self._extract("int")
self.assertTrue(helpers.is_subtype(int_subclass, base_int))
self.assertTrue(helpers.is_supertype(base_int, int_subclass))
@@ -181,28 +192,32 @@ class TestHelpers(unittest.TestCase):
self.assertFalse(helpers.is_subtype(cls_a, cls_b))
self.assertFalse(helpers.is_subtype(cls_a, cls_b))
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_is_subtype_supertype_old_style_classes(self):
- cls_a, cls_b = builder.extract_node('''
+ cls_a, cls_b = builder.extract_node(
+ """
class A: #@
pass
class B(A): #@
pass
- ''')
+ """
+ )
self.assertFalse(helpers.is_subtype(cls_a, cls_b))
self.assertFalse(helpers.is_subtype(cls_b, cls_a))
self.assertFalse(helpers.is_supertype(cls_a, cls_b))
self.assertFalse(helpers.is_supertype(cls_b, cls_a))
def test_is_subtype_supertype_mro_error(self):
- cls_e, cls_f = builder.extract_node('''
+ cls_e, cls_f = builder.extract_node(
+ """
class A(object): pass
class B(A): pass
class C(A): pass
class D(B, C): pass
class E(C, B): pass #@
class F(D, E): pass #@
- ''')
+ """
+ )
self.assertFalse(helpers.is_subtype(cls_e, cls_f))
self.assertFalse(helpers.is_subtype(cls_e, cls_f))
@@ -211,44 +226,52 @@ class TestHelpers(unittest.TestCase):
self.assertFalse(helpers.is_supertype(cls_f, cls_e))
def test_is_subtype_supertype_unknown_bases(self):
- cls_a, cls_b = builder.extract_node('''
+ cls_a, cls_b = builder.extract_node(
+ """
from unknown import Unknown
class A(Unknown): pass #@
class B(A): pass #@
- ''')
+ """
+ )
with self.assertRaises(exceptions._NonDeducibleTypeHierarchy):
helpers.is_subtype(cls_a, cls_b)
with self.assertRaises(exceptions._NonDeducibleTypeHierarchy):
helpers.is_supertype(cls_a, cls_b)
def test_is_subtype_supertype_unrelated_classes(self):
- cls_a, cls_b = builder.extract_node('''
+ cls_a, cls_b = builder.extract_node(
+ """
class A(object): pass #@
class B(object): pass #@
- ''')
+ """
+ )
self.assertFalse(helpers.is_subtype(cls_a, cls_b))
self.assertFalse(helpers.is_subtype(cls_b, cls_a))
self.assertFalse(helpers.is_supertype(cls_a, cls_b))
self.assertFalse(helpers.is_supertype(cls_b, cls_a))
def test_is_subtype_supertype_classes_no_type_ancestor(self):
- cls_a = builder.extract_node('''
+ cls_a = builder.extract_node(
+ """
class A(object): #@
pass
- ''')
- builtin_type = self._extract('type')
+ """
+ )
+ builtin_type = self._extract("type")
self.assertFalse(helpers.is_supertype(builtin_type, cls_a))
self.assertFalse(helpers.is_subtype(cls_a, builtin_type))
def test_is_subtype_supertype_classes_metaclasses(self):
- cls_a = builder.extract_node('''
+ cls_a = builder.extract_node(
+ """
class A(type): #@
pass
- ''')
- builtin_type = self._extract('type')
+ """
+ )
+ builtin_type = self._extract("type")
self.assertTrue(helpers.is_supertype(builtin_type, cls_a))
self.assertTrue(helpers.is_subtype(cls_a, builtin_type))
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/tests/unittest_inference.py b/astroid/tests/unittest_inference.py
index 7ecd197d..758fcd76 100644
--- a/astroid/tests/unittest_inference.py
+++ b/astroid/tests/unittest_inference.py
@@ -34,8 +34,7 @@ import pytest
from astroid import InferenceError, builder, nodes
from astroid.builder import parse, extract_node
from astroid.inference import infer_end as inference_infer_end
-from astroid.bases import Instance, BoundMethod, UnboundMethod,\
- BUILTINS
+from astroid.bases import Instance, BoundMethod, UnboundMethod, BUILTINS
from astroid import arguments
from astroid import decorators as decoratorsmod
from astroid import exceptions
@@ -49,21 +48,22 @@ from astroid.tests import resources
def get_node_of_class(start_from, klass):
return next(start_from.nodes_of_class(klass))
+
builder = builder.AstroidBuilder()
if sys.version_info < (3, 0):
- EXC_MODULE = 'exceptions'
- BOOL_SPECIAL_METHOD = '__nonzero__'
+ EXC_MODULE = "exceptions"
+ BOOL_SPECIAL_METHOD = "__nonzero__"
else:
EXC_MODULE = BUILTINS
- BOOL_SPECIAL_METHOD = '__bool__'
+ BOOL_SPECIAL_METHOD = "__bool__"
class InferenceUtilsTest(unittest.TestCase):
-
def test_path_wrapper(self):
def infer_default(self, *args):
raise InferenceError
+
infer_default = decoratorsmod.path_wrapper(infer_default)
infer_end = decoratorsmod.path_wrapper(inference_infer_end)
with self.assertRaises(InferenceError):
@@ -74,8 +74,8 @@ class InferenceUtilsTest(unittest.TestCase):
def _assertInferElts(node_type, self, node, elts):
inferred = next(node.infer())
self.assertIsInstance(inferred, node_type)
- self.assertEqual(sorted(elt.value for elt in inferred.elts),
- elts)
+ self.assertEqual(sorted(elt.value for elt in inferred.elts), elts)
+
def partialmethod(func, arg):
"""similar to functools.partial but return a lambda instead of a class so returned value may be
@@ -83,6 +83,7 @@ def partialmethod(func, arg):
"""
return lambda *args, **kwargs: func(arg, *args, **kwargs)
+
class InferenceTest(resources.SysPathSetup, unittest.TestCase):
# additional assertInfer* method for builtin types
@@ -96,8 +97,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Dict)
- elts = {(key.value, value.value)
- for (key, value) in inferred.items}
+ elts = {(key.value, value.value) for (key, value) in inferred.items}
self.assertEqual(sorted(elts), sorted(expected.items()))
assertInferTuple = partialmethod(_assertInferElts, nodes.Tuple)
@@ -105,7 +105,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
assertInferSet = partialmethod(_assertInferElts, nodes.Set)
assertInferFrozenSet = partialmethod(_assertInferElts, objects.FrozenSet)
- CODE = '''
+ CODE = """
class C(object):
"new style"
attr = 4
@@ -134,12 +134,13 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
i, (j, k) = "glup", f
a, b= b, a # Gasp !
- '''
+ """
ast = parse(CODE, __name__)
def test_infer_abstract_property_return_values(self):
- module = parse('''
+ module = parse(
+ """
import abc
class A(object):
@@ -149,8 +150,9 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
a = A()
x = a.test
- ''')
- inferred = next(module['x'].infer())
+ """
+ )
+ inferred = next(module["x"].infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 42)
@@ -162,158 +164,158 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertRaises(StopIteration, partial(next, inferred))
def test_class_inference(self):
- inferred = self.ast['C'].infer()
+ inferred = self.ast["C"].infer()
obj = next(inferred)
- self.assertEqual(obj.name, 'C')
+ self.assertEqual(obj.name, "C")
self.assertEqual(obj.root().name, __name__)
self.assertRaises(StopIteration, partial(next, inferred))
def test_function_inference(self):
- inferred = self.ast['C']['meth1'].infer()
+ inferred = self.ast["C"]["meth1"].infer()
obj = next(inferred)
- self.assertEqual(obj.name, 'meth1')
+ self.assertEqual(obj.name, "meth1")
self.assertEqual(obj.root().name, __name__)
self.assertRaises(StopIteration, partial(next, inferred))
def test_builtin_name_inference(self):
- inferred = self.ast['C']['meth1']['var'].infer()
+ inferred = self.ast["C"]["meth1"]["var"].infer()
var = next(inferred)
- self.assertEqual(var.name, 'object')
+ self.assertEqual(var.name, "object")
self.assertEqual(var.root().name, BUILTINS)
self.assertRaises(StopIteration, partial(next, inferred))
def test_tupleassign_name_inference(self):
- inferred = self.ast['a'].infer()
+ inferred = self.ast["a"].infer()
exc = next(inferred)
self.assertIsInstance(exc, Instance)
- self.assertEqual(exc.name, 'Exception')
+ self.assertEqual(exc.name, "Exception")
self.assertEqual(exc.root().name, EXC_MODULE)
self.assertRaises(StopIteration, partial(next, inferred))
- inferred = self.ast['b'].infer()
+ inferred = self.ast["b"].infer()
const = next(inferred)
self.assertIsInstance(const, nodes.Const)
self.assertEqual(const.value, 1)
self.assertRaises(StopIteration, partial(next, inferred))
- inferred = self.ast['c'].infer()
+ inferred = self.ast["c"].infer()
const = next(inferred)
self.assertIsInstance(const, nodes.Const)
self.assertEqual(const.value, "bonjour")
self.assertRaises(StopIteration, partial(next, inferred))
def test_listassign_name_inference(self):
- inferred = self.ast['d'].infer()
+ inferred = self.ast["d"].infer()
exc = next(inferred)
self.assertIsInstance(exc, Instance)
- self.assertEqual(exc.name, 'Exception')
+ self.assertEqual(exc.name, "Exception")
self.assertEqual(exc.root().name, EXC_MODULE)
self.assertRaises(StopIteration, partial(next, inferred))
- inferred = self.ast['e'].infer()
+ inferred = self.ast["e"].infer()
const = next(inferred)
self.assertIsInstance(const, nodes.Const)
self.assertEqual(const.value, 1.0)
self.assertRaises(StopIteration, partial(next, inferred))
- inferred = self.ast['f'].infer()
+ inferred = self.ast["f"].infer()
const = next(inferred)
self.assertIsInstance(const, nodes.Tuple)
self.assertRaises(StopIteration, partial(next, inferred))
def test_advanced_tupleassign_name_inference1(self):
- inferred = self.ast['g'].infer()
+ inferred = self.ast["g"].infer()
const = next(inferred)
self.assertIsInstance(const, nodes.Const)
self.assertEqual(const.value, "bonjour")
self.assertRaises(StopIteration, partial(next, inferred))
- inferred = self.ast['h'].infer()
+ inferred = self.ast["h"].infer()
var = next(inferred)
- self.assertEqual(var.name, 'object')
+ self.assertEqual(var.name, "object")
self.assertEqual(var.root().name, BUILTINS)
self.assertRaises(StopIteration, partial(next, inferred))
def test_advanced_tupleassign_name_inference2(self):
- inferred = self.ast['i'].infer()
+ inferred = self.ast["i"].infer()
const = next(inferred)
self.assertIsInstance(const, nodes.Const)
self.assertEqual(const.value, "glup")
self.assertRaises(StopIteration, partial(next, inferred))
- inferred = self.ast['j'].infer()
+ inferred = self.ast["j"].infer()
const = next(inferred)
self.assertIsInstance(const, nodes.Const)
self.assertEqual(const.value, "bonjour")
self.assertRaises(StopIteration, partial(next, inferred))
- inferred = self.ast['k'].infer()
+ inferred = self.ast["k"].infer()
var = next(inferred)
- self.assertEqual(var.name, 'object')
+ self.assertEqual(var.name, "object")
self.assertEqual(var.root().name, BUILTINS)
self.assertRaises(StopIteration, partial(next, inferred))
def test_swap_assign_inference(self):
- inferred = self.ast.locals['a'][1].infer()
+ inferred = self.ast.locals["a"][1].infer()
const = next(inferred)
self.assertIsInstance(const, nodes.Const)
self.assertEqual(const.value, 1)
self.assertRaises(StopIteration, partial(next, inferred))
- inferred = self.ast.locals['b'][1].infer()
+ inferred = self.ast.locals["b"][1].infer()
exc = next(inferred)
self.assertIsInstance(exc, Instance)
- self.assertEqual(exc.name, 'Exception')
+ self.assertEqual(exc.name, "Exception")
self.assertEqual(exc.root().name, EXC_MODULE)
self.assertRaises(StopIteration, partial(next, inferred))
def test_getattr_inference1(self):
- inferred = self.ast['ex'].infer()
+ inferred = self.ast["ex"].infer()
exc = next(inferred)
self.assertIsInstance(exc, Instance)
- self.assertEqual(exc.name, 'Exception')
+ self.assertEqual(exc.name, "Exception")
self.assertEqual(exc.root().name, EXC_MODULE)
self.assertRaises(StopIteration, partial(next, inferred))
def test_getattr_inference2(self):
- inferred = get_node_of_class(self.ast['C']['meth2'], nodes.Attribute).infer()
+ inferred = get_node_of_class(self.ast["C"]["meth2"], nodes.Attribute).infer()
meth1 = next(inferred)
- self.assertEqual(meth1.name, 'meth1')
+ self.assertEqual(meth1.name, "meth1")
self.assertEqual(meth1.root().name, __name__)
self.assertRaises(StopIteration, partial(next, inferred))
def test_getattr_inference3(self):
- inferred = self.ast['C']['meth3']['b'].infer()
+ inferred = self.ast["C"]["meth3"]["b"].infer()
const = next(inferred)
self.assertIsInstance(const, nodes.Const)
self.assertEqual(const.value, 4)
self.assertRaises(StopIteration, partial(next, inferred))
def test_getattr_inference4(self):
- inferred = self.ast['C']['meth3']['c'].infer()
+ inferred = self.ast["C"]["meth3"]["c"].infer()
const = next(inferred)
self.assertIsInstance(const, nodes.Const)
self.assertEqual(const.value, "hop")
self.assertRaises(StopIteration, partial(next, inferred))
def test_callfunc_inference(self):
- inferred = self.ast['v'].infer()
+ inferred = self.ast["v"].infer()
meth1 = next(inferred)
self.assertIsInstance(meth1, Instance)
- self.assertEqual(meth1.name, 'object')
+ self.assertEqual(meth1.name, "object")
self.assertEqual(meth1.root().name, BUILTINS)
self.assertRaises(StopIteration, partial(next, inferred))
def test_unbound_method_inference(self):
- inferred = self.ast['m_unbound'].infer()
+ inferred = self.ast["m_unbound"].infer()
meth1 = next(inferred)
self.assertIsInstance(meth1, UnboundMethod)
- self.assertEqual(meth1.name, 'meth1')
- self.assertEqual(meth1.parent.frame().name, 'C')
+ self.assertEqual(meth1.name, "meth1")
+ self.assertEqual(meth1.parent.frame().name, "C")
self.assertRaises(StopIteration, partial(next, inferred))
def test_bound_method_inference(self):
- inferred = self.ast['m_bound'].infer()
+ inferred = self.ast["m_bound"].infer()
meth1 = next(inferred)
self.assertIsInstance(meth1, BoundMethod)
- self.assertEqual(meth1.name, 'meth1')
- self.assertEqual(meth1.parent.frame().name, 'C')
+ self.assertEqual(meth1.name, "meth1")
+ self.assertEqual(meth1.parent.frame().name, "C")
self.assertRaises(StopIteration, partial(next, inferred))
def test_args_default_inference1(self):
- optarg = test_utils.get_name_node(self.ast['C']['meth1'], 'optarg')
+ optarg = test_utils.get_name_node(self.ast["C"]["meth1"], "optarg")
inferred = optarg.infer()
obj1 = next(inferred)
self.assertIsInstance(obj1, nodes.Const)
@@ -323,7 +325,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertRaises(StopIteration, partial(next, inferred))
def test_args_default_inference2(self):
- inferred = self.ast['C']['meth3'].ilookup('d')
+ inferred = self.ast["C"]["meth3"].ilookup("d")
obj1 = next(inferred)
self.assertIsInstance(obj1, nodes.Const)
self.assertEqual(obj1.value, 4)
@@ -332,26 +334,26 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertRaises(StopIteration, partial(next, inferred))
def test_inference_restrictions(self):
- inferred = test_utils.get_name_node(self.ast['C']['meth1'], 'arg1').infer()
+ inferred = test_utils.get_name_node(self.ast["C"]["meth1"], "arg1").infer()
obj1 = next(inferred)
self.assertIs(obj1, util.Uninferable, obj1)
self.assertRaises(StopIteration, partial(next, inferred))
def test_ancestors_inference(self):
- code = '''
+ code = """
class A(object): #@
pass
class A(A): #@
pass
- '''
+ """
a1, a2 = extract_node(code, __name__)
a2_ancestors = list(a2.ancestors())
self.assertEqual(len(a2_ancestors), 2)
self.assertIs(a2_ancestors[0], a1)
def test_ancestors_inference2(self):
- code = '''
+ code = """
class A(object): #@
pass
@@ -360,7 +362,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
class A(B): #@
pass
- '''
+ """
a1, b, a2 = extract_node(code, __name__)
a2_ancestors = list(a2.ancestors())
self.assertEqual(len(a2_ancestors), 3)
@@ -368,37 +370,42 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertIs(a2_ancestors[1], a1)
def test_f_arg_f(self):
- code = '''
+ code = """
def f(f=1):
return f
a = f()
- '''
+ """
ast = parse(code, __name__)
- a = ast['a']
+ a = ast["a"]
a_inferred = a.inferred()
self.assertEqual(a_inferred[0].value, 1)
self.assertEqual(len(a_inferred), 1)
def test_exc_ancestors(self):
- code = '''
+ code = """
def f():
raise __(NotImplementedError)
- '''
+ """
error = extract_node(code, __name__)
nie = error.inferred()[0]
self.assertIsInstance(nie, nodes.ClassDef)
nie_ancestors = [c.name for c in nie.ancestors()]
if sys.version_info < (3, 0):
- expected = ['RuntimeError', 'StandardError',
- 'Exception', 'BaseException', 'object']
+ expected = [
+ "RuntimeError",
+ "StandardError",
+ "Exception",
+ "BaseException",
+ "object",
+ ]
self.assertEqual(nie_ancestors, expected)
else:
- expected = ['RuntimeError', 'Exception', 'BaseException', 'object']
+ expected = ["RuntimeError", "Exception", "BaseException", "object"]
self.assertEqual(nie_ancestors, expected)
def test_except_inference(self):
- code = '''
+ code = """
try:
print (hop)
except NameError as ex:
@@ -406,48 +413,48 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
except Exception as ex:
ex2 = ex
raise
- '''
+ """
ast = parse(code, __name__)
- ex1 = ast['ex1']
+ ex1 = ast["ex1"]
ex1_infer = ex1.infer()
ex1 = next(ex1_infer)
self.assertIsInstance(ex1, Instance)
- self.assertEqual(ex1.name, 'NameError')
+ self.assertEqual(ex1.name, "NameError")
self.assertRaises(StopIteration, partial(next, ex1_infer))
- ex2 = ast['ex2']
+ ex2 = ast["ex2"]
ex2_infer = ex2.infer()
ex2 = next(ex2_infer)
self.assertIsInstance(ex2, Instance)
- self.assertEqual(ex2.name, 'Exception')
+ self.assertEqual(ex2.name, "Exception")
self.assertRaises(StopIteration, partial(next, ex2_infer))
def test_del1(self):
- code = '''
+ code = """
del undefined_attr
- '''
+ """
delete = extract_node(code, __name__)
self.assertRaises(InferenceError, delete.infer)
def test_del2(self):
- code = '''
+ code = """
a = 1
b = a
del a
c = a
a = 2
d = a
- '''
+ """
ast = parse(code, __name__)
- n = ast['b']
+ n = ast["b"]
n_infer = n.infer()
inferred = next(n_infer)
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 1)
self.assertRaises(StopIteration, partial(next, n_infer))
- n = ast['c']
+ n = ast["c"]
n_infer = n.infer()
self.assertRaises(InferenceError, partial(next, n_infer))
- n = ast['d']
+ n = ast["d"]
n_infer = n.infer()
inferred = next(n_infer)
self.assertIsInstance(inferred, nodes.Const)
@@ -455,110 +462,112 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertRaises(StopIteration, partial(next, n_infer))
def test_builtin_types(self):
- code = '''
+ code = """
l = [1]
t = (2,)
d = {}
s = ''
s2 = '_'
- '''
+ """
ast = parse(code, __name__)
- n = ast['l']
+ n = ast["l"]
inferred = next(n.infer())
self.assertIsInstance(inferred, nodes.List)
self.assertIsInstance(inferred, Instance)
self.assertEqual(inferred.getitem(nodes.Const(0)).value, 1)
self.assertIsInstance(inferred._proxied, nodes.ClassDef)
- self.assertEqual(inferred._proxied.name, 'list')
- self.assertIn('append', inferred._proxied.locals)
- n = ast['t']
+ self.assertEqual(inferred._proxied.name, "list")
+ self.assertIn("append", inferred._proxied.locals)
+ n = ast["t"]
inferred = next(n.infer())
self.assertIsInstance(inferred, nodes.Tuple)
self.assertIsInstance(inferred, Instance)
self.assertEqual(inferred.getitem(nodes.Const(0)).value, 2)
self.assertIsInstance(inferred._proxied, nodes.ClassDef)
- self.assertEqual(inferred._proxied.name, 'tuple')
- n = ast['d']
+ self.assertEqual(inferred._proxied.name, "tuple")
+ n = ast["d"]
inferred = next(n.infer())
self.assertIsInstance(inferred, nodes.Dict)
self.assertIsInstance(inferred, Instance)
self.assertIsInstance(inferred._proxied, nodes.ClassDef)
- self.assertEqual(inferred._proxied.name, 'dict')
- self.assertIn('get', inferred._proxied.locals)
- n = ast['s']
+ self.assertEqual(inferred._proxied.name, "dict")
+ self.assertIn("get", inferred._proxied.locals)
+ n = ast["s"]
inferred = next(n.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'str')
- self.assertIn('lower', inferred._proxied.locals)
- n = ast['s2']
+ self.assertEqual(inferred.name, "str")
+ self.assertIn("lower", inferred._proxied.locals)
+ n = ast["s2"]
inferred = next(n.infer())
- self.assertEqual(inferred.getitem(nodes.Const(0)).value, '_')
+ self.assertEqual(inferred.getitem(nodes.Const(0)).value, "_")
- code = 's = {1}'
+ code = "s = {1}"
ast = parse(code, __name__)
- n = ast['s']
+ n = ast["s"]
inferred = next(n.infer())
self.assertIsInstance(inferred, nodes.Set)
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'set')
- self.assertIn('remove', inferred._proxied.locals)
+ self.assertEqual(inferred.name, "set")
+ self.assertIn("remove", inferred._proxied.locals)
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_unicode_type(self):
code = '''u = u""'''
ast = parse(code, __name__)
- n = ast['u']
+ n = ast["u"]
inferred = next(n.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'unicode')
- self.assertIn('lower', inferred._proxied.locals)
+ self.assertEqual(inferred.name, "unicode")
+ self.assertIn("lower", inferred._proxied.locals)
@unittest.expectedFailure
def test_descriptor_are_callable(self):
- code = '''
+ code = """
class A:
statm = staticmethod(open)
clsm = classmethod('whatever')
- '''
+ """
ast = parse(code, __name__)
- statm = next(ast['A'].igetattr('statm'))
+ statm = next(ast["A"].igetattr("statm"))
self.assertTrue(statm.callable())
- clsm = next(ast['A'].igetattr('clsm'))
+ clsm = next(ast["A"].igetattr("clsm"))
self.assertFalse(clsm.callable())
def test_bt_ancestor_crash(self):
- code = '''
+ code = """
class Warning(Warning):
pass
- '''
+ """
ast = parse(code, __name__)
- w = ast['Warning']
+ w = ast["Warning"]
ancestors = w.ancestors()
ancestor = next(ancestors)
- self.assertEqual(ancestor.name, 'Warning')
+ self.assertEqual(ancestor.name, "Warning")
self.assertEqual(ancestor.root().name, EXC_MODULE)
ancestor = next(ancestors)
- self.assertEqual(ancestor.name, 'Exception')
+ self.assertEqual(ancestor.name, "Exception")
self.assertEqual(ancestor.root().name, EXC_MODULE)
ancestor = next(ancestors)
- self.assertEqual(ancestor.name, 'BaseException')
+ self.assertEqual(ancestor.name, "BaseException")
self.assertEqual(ancestor.root().name, EXC_MODULE)
ancestor = next(ancestors)
- self.assertEqual(ancestor.name, 'object')
+ self.assertEqual(ancestor.name, "object")
self.assertEqual(ancestor.root().name, BUILTINS)
self.assertRaises(StopIteration, partial(next, ancestors))
def test_qqch(self):
- code = '''
+ code = """
from astroid.modutils import load_module_from_name
xxx = load_module_from_name('__pkginfo__')
- '''
+ """
ast = parse(code, __name__)
- xxx = ast['xxx']
- self.assertSetEqual({n.__class__ for n in xxx.inferred()},
- {nodes.Const, util.Uninferable.__class__})
+ xxx = ast["xxx"]
+ self.assertSetEqual(
+ {n.__class__ for n in xxx.inferred()},
+ {nodes.Const, util.Uninferable.__class__},
+ )
def test_method_argument(self):
code = '''
@@ -572,28 +581,27 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
print(args)
'''
ast = parse(code, __name__)
- arg = test_utils.get_name_node(ast['ErudiEntitySchema']['__init__'], 'e_type')
- self.assertEqual([n.__class__ for n in arg.infer()],
- [util.Uninferable.__class__])
- arg = test_utils.get_name_node(ast['ErudiEntitySchema']['__init__'], 'kwargs')
- self.assertEqual([n.__class__ for n in arg.infer()],
- [nodes.Dict])
- arg = test_utils.get_name_node(ast['ErudiEntitySchema']['meth'], 'e_type')
- self.assertEqual([n.__class__ for n in arg.infer()],
- [util.Uninferable.__class__])
- arg = test_utils.get_name_node(ast['ErudiEntitySchema']['meth'], 'args')
- self.assertEqual([n.__class__ for n in arg.infer()],
- [nodes.Tuple])
- arg = test_utils.get_name_node(ast['ErudiEntitySchema']['meth'], 'kwargs')
- self.assertEqual([n.__class__ for n in arg.infer()],
- [nodes.Dict])
+ arg = test_utils.get_name_node(ast["ErudiEntitySchema"]["__init__"], "e_type")
+ self.assertEqual(
+ [n.__class__ for n in arg.infer()], [util.Uninferable.__class__]
+ )
+ arg = test_utils.get_name_node(ast["ErudiEntitySchema"]["__init__"], "kwargs")
+ self.assertEqual([n.__class__ for n in arg.infer()], [nodes.Dict])
+ arg = test_utils.get_name_node(ast["ErudiEntitySchema"]["meth"], "e_type")
+ self.assertEqual(
+ [n.__class__ for n in arg.infer()], [util.Uninferable.__class__]
+ )
+ arg = test_utils.get_name_node(ast["ErudiEntitySchema"]["meth"], "args")
+ self.assertEqual([n.__class__ for n in arg.infer()], [nodes.Tuple])
+ arg = test_utils.get_name_node(ast["ErudiEntitySchema"]["meth"], "kwargs")
+ self.assertEqual([n.__class__ for n in arg.infer()], [nodes.Dict])
def test_tuple_then_list(self):
- code = '''
+ code = """
def test_view(rql, vid, tags=()):
tags = list(tags)
__(tags).append(vid)
- '''
+ """
name = extract_node(code, __name__)
it = name.infer()
tags = next(it)
@@ -637,12 +645,19 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
fct(a_line)
'''
ast = parse(code, __name__)
- self.assertEqual(len(list(ast['process_line'].infer_call_result(None))), 3)
- self.assertEqual(len(list(ast['tupletest'].infer())), 3)
- values = ['<FunctionDef.first_word', '<FunctionDef.last_word',
- '<Const.NoneType']
- self.assertTrue(all(repr(inferred).startswith(value) for inferred, value
- in zip(ast['fct'].infer(), values)))
+ self.assertEqual(len(list(ast["process_line"].infer_call_result(None))), 3)
+ self.assertEqual(len(list(ast["tupletest"].infer())), 3)
+ values = [
+ "<FunctionDef.first_word",
+ "<FunctionDef.last_word",
+ "<Const.NoneType",
+ ]
+ self.assertTrue(
+ all(
+ repr(inferred).startswith(value)
+ for inferred, value in zip(ast["fct"].infer(), values)
+ )
+ )
def test_float_complex_ambiguity(self):
code = '''
@@ -657,12 +672,8 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
return __(something).conjugate()
'''
func, retval = extract_node(code, __name__)
- self.assertEqual(
- [i.value for i in func.ilookup('something')],
- [1.0, 1.0j])
- self.assertEqual(
- [i.value for i in retval.infer()],
- [1.0, 1.0j])
+ self.assertEqual([i.value for i in func.ilookup("something")], [1.0, 1.0j])
+ self.assertEqual([i.value for i in retval.infer()], [1.0, 1.0j])
def test_lookup_cond_branches(self):
code = '''
@@ -674,12 +685,13 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
return something.conjugate()
'''
ast = parse(code, __name__)
- values = [i.value for i in test_utils.get_name_node(ast, 'something', -1).infer()]
+ values = [
+ i.value for i in test_utils.get_name_node(ast, "something", -1).infer()
+ ]
self.assertEqual(values, [1.0, 1.0j])
-
def test_simple_subscript(self):
- code = '''
+ code = """
class A(object):
def __getitem__(self, index):
return index + 42
@@ -694,16 +706,17 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
tuple((4, 5, 6))[2] #@
A()[0] #@
A()[-1] #@
- '''
+ """
ast_nodes = extract_node(code, __name__)
- expected = [1, 2, 3, 6, 'value', 'f', 3, 6, 42, 41]
+ expected = [1, 2, 3, 6, "value", "f", 3, 6, 42, 41]
for node, expected_value in zip(ast_nodes, expected):
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, expected_value)
def test_invalid_subscripts(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class NoGetitem(object):
pass
class InvalidGetitem(object):
@@ -713,38 +726,43 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
NoGetitem()[4] #@
InvalidGetitem()[5] #@
InvalidGetitem2()[10] #@
- ''')
+ """
+ )
for node in ast_nodes[:3]:
self.assertRaises(InferenceError, next, node.infer())
for node in ast_nodes[3:]:
self.assertEqual(next(node.infer()), util.Uninferable)
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
[1, 2, 3][None] #@
'lala'['bala'] #@
- ''')
+ """
+ )
for node in ast_nodes:
self.assertRaises(InferenceError, next, node.infer())
def test_bytes_subscript(self):
- node = extract_node('''b'a'[0]''')
+ node = extract_node("""b'a'[0]""")
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 97)
def test_simple_tuple(self):
- module = parse("""
+ module = parse(
+ """
a = (1,)
b = (22,)
some = a + b #@
- """)
- ast = next(module['some'].infer())
+ """
+ )
+ ast = next(module["some"].infer())
self.assertIsInstance(ast, nodes.Tuple)
self.assertEqual(len(ast.elts), 2)
self.assertEqual(ast.elts[0].value, 1)
self.assertEqual(ast.elts[1].value, 22)
def test_simple_for(self):
- code = '''
+ code = """
for a in [1, 2, 3]:
print (a)
for b,c in [(1,2), (3,4)]:
@@ -752,34 +770,40 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
print (c)
print ([(d,e) for e,d in ([1,2], [3,4])])
- '''
+ """
ast = parse(code, __name__)
- self.assertEqual([i.value for i in
- test_utils.get_name_node(ast, 'a', -1).infer()], [1, 2, 3])
- self.assertEqual([i.value for i in
- test_utils.get_name_node(ast, 'b', -1).infer()], [1, 3])
- self.assertEqual([i.value for i in
- test_utils.get_name_node(ast, 'c', -1).infer()], [2, 4])
- self.assertEqual([i.value for i in
- test_utils.get_name_node(ast, 'd', -1).infer()], [2, 4])
- self.assertEqual([i.value for i in
- test_utils.get_name_node(ast, 'e', -1).infer()], [1, 3])
+ self.assertEqual(
+ [i.value for i in test_utils.get_name_node(ast, "a", -1).infer()], [1, 2, 3]
+ )
+ self.assertEqual(
+ [i.value for i in test_utils.get_name_node(ast, "b", -1).infer()], [1, 3]
+ )
+ self.assertEqual(
+ [i.value for i in test_utils.get_name_node(ast, "c", -1).infer()], [2, 4]
+ )
+ self.assertEqual(
+ [i.value for i in test_utils.get_name_node(ast, "d", -1).infer()], [2, 4]
+ )
+ self.assertEqual(
+ [i.value for i in test_utils.get_name_node(ast, "e", -1).infer()], [1, 3]
+ )
def test_simple_for_genexpr(self):
- code = '''
+ code = """
print ((d,e) for e,d in ([1,2], [3,4]))
- '''
+ """
ast = parse(code, __name__)
- self.assertEqual([i.value for i in
- test_utils.get_name_node(ast, 'd', -1).infer()], [2, 4])
- self.assertEqual([i.value for i in
- test_utils.get_name_node(ast, 'e', -1).infer()], [1, 3])
-
+ self.assertEqual(
+ [i.value for i in test_utils.get_name_node(ast, "d", -1).infer()], [2, 4]
+ )
+ self.assertEqual(
+ [i.value for i in test_utils.get_name_node(ast, "e", -1).infer()], [1, 3]
+ )
def test_builtin_help(self):
- code = '''
+ code = """
help()
- '''
+ """
# XXX failing since __builtin__.help assignment has
# been moved into a function...
node = extract_node(code, __name__)
@@ -789,47 +813,48 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertEqual(inferred[0].name, "_Helper")
def test_builtin_open(self):
- code = '''
+ code = """
open("toto.txt")
- '''
+ """
node = extract_node(code, __name__).func
inferred = list(node.infer())
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], nodes.FunctionDef)
- self.assertEqual(inferred[0].name, 'open')
- if platform.python_implementation() == 'PyPy':
+ self.assertEqual(inferred[0].name, "open")
+
+ if platform.python_implementation() == "PyPy":
test_builtin_open = unittest.expectedFailure(test_builtin_open)
def test_callfunc_context_func(self):
- code = '''
+ code = """
def mirror(arg=None):
return arg
un = mirror(1)
- '''
+ """
ast = parse(code, __name__)
- inferred = list(ast.igetattr('un'))
+ inferred = list(ast.igetattr("un"))
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], nodes.Const)
self.assertEqual(inferred[0].value, 1)
def test_callfunc_context_lambda(self):
- code = '''
+ code = """
mirror = lambda x=None: x
un = mirror(1)
- '''
+ """
ast = parse(code, __name__)
- inferred = list(ast.igetattr('mirror'))
+ inferred = list(ast.igetattr("mirror"))
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], nodes.Lambda)
- inferred = list(ast.igetattr('un'))
+ inferred = list(ast.igetattr("un"))
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], nodes.Const)
self.assertEqual(inferred[0].value, 1)
def test_factory_method(self):
- code = '''
+ code = """
class Super(object):
@classmethod
def instance(cls):
@@ -840,16 +865,16 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
print ('method called')
sub = Sub.instance()
- '''
+ """
ast = parse(code, __name__)
- inferred = list(ast.igetattr('sub'))
+ inferred = list(ast.igetattr("sub"))
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], Instance)
- self.assertEqual(inferred[0]._proxied.name, 'Sub')
-
+ self.assertEqual(inferred[0]._proxied.name, "Sub")
def test_factory_methods_cls_call(self):
- ast = extract_node("""
+ ast = extract_node(
+ """
class C:
@classmethod
def factory(cls):
@@ -860,17 +885,19 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
C.factory() #@
D.factory() #@
- """, 'module')
+ """,
+ "module",
+ )
should_be_C = list(ast[0].infer())
should_be_D = list(ast[1].infer())
self.assertEqual(1, len(should_be_C))
self.assertEqual(1, len(should_be_D))
- self.assertEqual('module.C', should_be_C[0].qname())
- self.assertEqual('module.D', should_be_D[0].qname())
-
+ self.assertEqual("module.C", should_be_C[0].qname())
+ self.assertEqual("module.D", should_be_D[0].qname())
def test_factory_methods_object_new_call(self):
- ast = extract_node("""
+ ast = extract_node(
+ """
class C:
@classmethod
def factory(cls):
@@ -881,40 +908,44 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
C.factory() #@
D.factory() #@
- """, 'module')
+ """,
+ "module",
+ )
should_be_C = list(ast[0].infer())
should_be_D = list(ast[1].infer())
self.assertEqual(1, len(should_be_C))
self.assertEqual(1, len(should_be_D))
- self.assertEqual('module.C', should_be_C[0].qname())
- self.assertEqual('module.D', should_be_D[0].qname())
+ self.assertEqual("module.C", should_be_C[0].qname())
+ self.assertEqual("module.D", should_be_D[0].qname())
def test_factory_methods_inside_binary_operation(self):
- node = extract_node("""
+ node = extract_node(
+ """
from pathlib import Path
h = Path("/home")
u = h / "user"
u #@
- """)
- assert next(node.infer()).qname() == 'pathlib.Path'
+ """
+ )
+ assert next(node.infer()).qname() == "pathlib.Path"
def test_import_as(self):
- code = '''
+ code = """
import os.path as osp
print (osp.dirname(__file__))
from os.path import exists as e
assert e(__file__)
- '''
+ """
ast = parse(code, __name__)
- inferred = list(ast.igetattr('osp'))
+ inferred = list(ast.igetattr("osp"))
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], nodes.Module)
- self.assertEqual(inferred[0].name, 'os.path')
- inferred = list(ast.igetattr('e'))
+ self.assertEqual(inferred[0].name, "os.path")
+ inferred = list(ast.igetattr("e"))
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], nodes.FunctionDef)
- self.assertEqual(inferred[0].name, 'exists')
+ self.assertEqual(inferred[0].name, "exists")
def _test_const_inferred(self, node, value):
inferred = list(node.infer())
@@ -923,86 +954,94 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertEqual(inferred[0].value, value)
def test_unary_not(self):
- for code in ('a = not (1,); b = not ()',
- 'a = not {1:2}; b = not {}',
- 'a = not [1, 2]; b = not []',
- 'a = not {1, 2}; b = not set()',
- 'a = not 1; b = not 0',
- 'a = not "a"; b = not ""',
- 'a = not b"a"; b = not b""'):
+ for code in (
+ "a = not (1,); b = not ()",
+ "a = not {1:2}; b = not {}",
+ "a = not [1, 2]; b = not []",
+ "a = not {1, 2}; b = not set()",
+ "a = not 1; b = not 0",
+ 'a = not "a"; b = not ""',
+ 'a = not b"a"; b = not b""',
+ ):
ast = builder.string_build(code, __name__, __file__)
- self._test_const_inferred(ast['a'], False)
- self._test_const_inferred(ast['b'], True)
+ self._test_const_inferred(ast["a"], False)
+ self._test_const_inferred(ast["b"], True)
def test_unary_op_numbers(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
+1 #@
-1 #@
~1 #@
+2.0 #@
-2.0 #@
- ''')
+ """
+ )
expected = [1, -1, -2, 2.0, -2.0]
for node, expected_value in zip(ast_nodes, expected):
inferred = next(node.infer())
self.assertEqual(inferred.value, expected_value)
- @test_utils.require_version(minver='3.5')
+ @test_utils.require_version(minver="3.5")
def test_matmul(self):
- node = extract_node('''
+ node = extract_node(
+ """
class Array:
def __matmul__(self, other):
return 42
Array() @ Array() #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 42)
def test_binary_op_int_add(self):
- ast = builder.string_build('a = 1 + 2', __name__, __file__)
- self._test_const_inferred(ast['a'], 3)
+ ast = builder.string_build("a = 1 + 2", __name__, __file__)
+ self._test_const_inferred(ast["a"], 3)
def test_binary_op_int_sub(self):
- ast = builder.string_build('a = 1 - 2', __name__, __file__)
- self._test_const_inferred(ast['a'], -1)
+ ast = builder.string_build("a = 1 - 2", __name__, __file__)
+ self._test_const_inferred(ast["a"], -1)
def test_binary_op_float_div(self):
- ast = builder.string_build('a = 1 / 2.', __name__, __file__)
- self._test_const_inferred(ast['a'], 1 / 2.)
+ ast = builder.string_build("a = 1 / 2.", __name__, __file__)
+ self._test_const_inferred(ast["a"], 1 / 2.)
def test_binary_op_str_mul(self):
ast = builder.string_build('a = "*" * 40', __name__, __file__)
- self._test_const_inferred(ast['a'], "*" * 40)
+ self._test_const_inferred(ast["a"], "*" * 40)
def test_binary_op_int_bitand(self):
- ast = builder.string_build('a = 23&20', __name__, __file__)
- self._test_const_inferred(ast['a'], 23&20)
+ ast = builder.string_build("a = 23&20", __name__, __file__)
+ self._test_const_inferred(ast["a"], 23 & 20)
def test_binary_op_int_bitor(self):
- ast = builder.string_build('a = 23|8', __name__, __file__)
- self._test_const_inferred(ast['a'], 23|8)
+ ast = builder.string_build("a = 23|8", __name__, __file__)
+ self._test_const_inferred(ast["a"], 23 | 8)
def test_binary_op_int_bitxor(self):
- ast = builder.string_build('a = 23^9', __name__, __file__)
- self._test_const_inferred(ast['a'], 23^9)
+ ast = builder.string_build("a = 23^9", __name__, __file__)
+ self._test_const_inferred(ast["a"], 23 ^ 9)
def test_binary_op_int_shiftright(self):
- ast = builder.string_build('a = 23 >>1', __name__, __file__)
- self._test_const_inferred(ast['a'], 23>>1)
+ ast = builder.string_build("a = 23 >>1", __name__, __file__)
+ self._test_const_inferred(ast["a"], 23 >> 1)
def test_binary_op_int_shiftleft(self):
- ast = builder.string_build('a = 23 <<1', __name__, __file__)
- self._test_const_inferred(ast['a'], 23<<1)
+ ast = builder.string_build("a = 23 <<1", __name__, __file__)
+ self._test_const_inferred(ast["a"], 23 << 1)
def test_binary_op_other_type(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class A:
def __add__(self, other):
return other + 42
A() + 1 #@
1 + A() #@
- ''')
+ """
+ )
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, nodes.Const)
self.assertEqual(first.value, 43)
@@ -1011,13 +1050,15 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertEqual(second, util.Uninferable)
def test_binary_op_other_type_using_reflected_operands(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class A(object):
def __radd__(self, other):
return other + 42
A() + 1 #@
1 + A() #@
- ''')
+ """
+ )
first = next(ast_nodes[0].infer())
self.assertEqual(first, util.Uninferable)
@@ -1026,19 +1067,21 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertEqual(second.value, 43)
def test_binary_op_reflected_and_not_implemented_is_type_error(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object):
def __radd__(self, other): return NotImplemented
1 + A() #@
- ''')
+ """
+ )
first = next(ast_node.infer())
self.assertEqual(first, util.Uninferable)
def test_binary_op_list_mul(self):
- for code in ('a = [[]] * 2', 'a = 2 * [[]]'):
+ for code in ("a = [[]] * 2", "a = 2 * [[]]"):
ast = builder.string_build(code, __name__, __file__)
- inferred = list(ast['a'].infer())
+ inferred = list(ast["a"].infer())
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], nodes.List)
self.assertEqual(len(inferred[0].elts), 2)
@@ -1046,43 +1089,43 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertIsInstance(inferred[0].elts[1], nodes.List)
def test_binary_op_list_mul_none(self):
- 'test correct handling on list multiplied by None'
+ "test correct handling on list multiplied by None"
ast = builder.string_build('a = [1] * None\nb = [1] * "r"')
- inferred = ast['a'].inferred()
+ inferred = ast["a"].inferred()
self.assertEqual(len(inferred), 1)
self.assertEqual(inferred[0], util.Uninferable)
- inferred = ast['b'].inferred()
+ inferred = ast["b"].inferred()
self.assertEqual(len(inferred), 1)
self.assertEqual(inferred[0], util.Uninferable)
def test_binary_op_list_mul_int(self):
- 'test correct handling on list multiplied by int when there are more than one'
- code = '''
+ "test correct handling on list multiplied by int when there are more than one"
+ code = """
from ctypes import c_int
seq = [c_int()] * 4
- '''
+ """
ast = parse(code, __name__)
- inferred = ast['seq'].inferred()
+ inferred = ast["seq"].inferred()
self.assertEqual(len(inferred), 1)
listval = inferred[0]
self.assertIsInstance(listval, nodes.List)
self.assertEqual(len(listval.itered()), 4)
def test_binary_op_on_self(self):
- 'test correct handling of applying binary operator to self'
- code = '''
+ "test correct handling of applying binary operator to self"
+ code = """
import sys
sys.path = ['foo'] + sys.path
sys.path.insert(0, 'bar')
path = sys.path
- '''
+ """
ast = parse(code, __name__)
- inferred = ast['path'].inferred()
+ inferred = ast["path"].inferred()
self.assertIsInstance(inferred[0], nodes.List)
def test_binary_op_tuple_add(self):
- ast = builder.string_build('a = (1,) + (2,)', __name__, __file__)
- inferred = list(ast['a'].infer())
+ ast = builder.string_build("a = (1,) + (2,)", __name__, __file__)
+ inferred = list(ast["a"].infer())
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], nodes.Tuple)
self.assertEqual(len(inferred[0].elts), 2)
@@ -1090,7 +1133,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertEqual(inferred[0].elts[1].value, 2)
def test_binary_op_custom_class(self):
- code = '''
+ code = """
class myarray:
def __init__(self, array):
self.array = array
@@ -1106,22 +1149,23 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
return int(5)
x = randint(1)
- '''
+ """
ast = parse(code, __name__)
- inferred = list(ast.igetattr('x'))
+ inferred = list(ast.igetattr("x"))
self.assertEqual(len(inferred), 2)
value = [str(v) for v in inferred]
# The __name__ trick here makes it work when invoked directly
# (__name__ == '__main__') and through pytest (__name__ ==
# 'unittest_inference')
- self.assertEqual(value, ['Instance of %s.myarray' % __name__,
- 'Const.int(value=5)'])
+ self.assertEqual(
+ value, ["Instance of %s.myarray" % __name__, "Const.int(value=5)"]
+ )
def test_nonregr_lambda_arg(self):
- code = '''
+ code = """
def f(g = lambda: None):
__(g()).x
-'''
+"""
callfuncnode = extract_node(code)
inferred = list(callfuncnode.infer())
self.assertEqual(len(inferred), 2, inferred)
@@ -1130,12 +1174,12 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertIsNone(inferred[0].value)
def test_nonregr_getitem_empty_tuple(self):
- code = '''
+ code = """
def f(x):
a = ()[x]
- '''
+ """
ast = parse(code, __name__)
- inferred = list(ast['f'].ilookup('a'))
+ inferred = list(ast["f"].ilookup("a"))
self.assertEqual(len(inferred), 1)
self.assertEqual(inferred[0], util.Uninferable)
@@ -1154,19 +1198,19 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.attr = 41
"""
ast = parse(code, __name__)
- foo_class = ast['Foo']
- bar_class = ast['Bar']
- bar_self = ast['Bar']['__init__']['self']
- assattr = bar_class.instance_attrs['attr'][0]
- self.assertEqual(len(foo_class.instance_attrs['attr']), 1)
- self.assertEqual(len(bar_class.instance_attrs['attr']), 1)
- self.assertEqual(bar_class.instance_attrs, {'attr': [assattr]})
+ foo_class = ast["Foo"]
+ bar_class = ast["Bar"]
+ bar_self = ast["Bar"]["__init__"]["self"]
+ assattr = bar_class.instance_attrs["attr"][0]
+ self.assertEqual(len(foo_class.instance_attrs["attr"]), 1)
+ self.assertEqual(len(bar_class.instance_attrs["attr"]), 1)
+ self.assertEqual(bar_class.instance_attrs, {"attr": [assattr]})
# call 'instance_attr' via 'Instance.getattr' to trigger the bug:
instance = bar_self.inferred()[0]
- instance.getattr('attr')
- self.assertEqual(len(bar_class.instance_attrs['attr']), 1)
- self.assertEqual(len(foo_class.instance_attrs['attr']), 1)
- self.assertEqual(bar_class.instance_attrs, {'attr': [assattr]})
+ instance.getattr("attr")
+ self.assertEqual(len(bar_class.instance_attrs["attr"]), 1)
+ self.assertEqual(len(foo_class.instance_attrs["attr"]), 1)
+ self.assertEqual(bar_class.instance_attrs, {"attr": [assattr]})
def test_nonregr_multi_referential_addition(self):
"""Regression test for https://github.com/PyCQA/astroid/issues/483
@@ -1181,7 +1225,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
variable_a = extract_node(code)
self.assertEqual(variable_a.inferred()[0].value, 2)
- @test_utils.require_version(minver='3.5')
+ @test_utils.require_version(minver="3.5")
def test_nonregr_layed_dictunpack(self):
"""Regression test for https://github.com/PyCQA/astroid/issues/483
Make sure multiple dictunpack references are inferable
@@ -1243,24 +1287,25 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
assert isinstance(result[0], nodes.Dict)
assert result[1] is util.Uninferable
-
def test_python25_no_relative_import(self):
- ast = resources.build_file('data/package/absimport.py')
+ ast = resources.build_file("data/package/absimport.py")
self.assertTrue(ast.absolute_import_activated(), True)
- inferred = next(test_utils.get_name_node(ast, 'import_package_subpackage_module').infer())
+ inferred = next(
+ test_utils.get_name_node(ast, "import_package_subpackage_module").infer()
+ )
# failed to import since absolute_import is activated
self.assertIs(inferred, util.Uninferable)
def test_nonregr_absolute_import(self):
- ast = resources.build_file('data/absimp/string.py', 'data.absimp.string')
+ ast = resources.build_file("data/absimp/string.py", "data.absimp.string")
self.assertTrue(ast.absolute_import_activated(), True)
- inferred = next(test_utils.get_name_node(ast, 'string').infer())
+ inferred = next(test_utils.get_name_node(ast, "string").infer())
self.assertIsInstance(inferred, nodes.Module)
- self.assertEqual(inferred.name, 'string')
- self.assertIn('ascii_letters', inferred.locals)
+ self.assertEqual(inferred.name, "string")
+ self.assertIn("ascii_letters", inferred.locals)
def test_property(self):
- code = '''
+ code = """
from smtplib import SMTP
class SendMailController(object):
@@ -1274,28 +1319,26 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
my_smtp = SendMailController().smtp
my_me = SendMailController().me
- '''
- decorators = {'%s.property' % BUILTINS}
+ """
+ decorators = {"%s.property" % BUILTINS}
ast = parse(code, __name__)
- self.assertEqual(ast['SendMailController']['smtp'].decoratornames(),
- decorators)
+ self.assertEqual(ast["SendMailController"]["smtp"].decoratornames(), decorators)
propinferred = list(ast.body[2].value.infer())
self.assertEqual(len(propinferred), 1)
propinferred = propinferred[0]
self.assertIsInstance(propinferred, Instance)
- self.assertEqual(propinferred.name, 'SMTP')
- self.assertEqual(propinferred.root().name, 'smtplib')
- self.assertEqual(ast['SendMailController']['me'].decoratornames(),
- decorators)
+ self.assertEqual(propinferred.name, "SMTP")
+ self.assertEqual(propinferred.root().name, "smtplib")
+ self.assertEqual(ast["SendMailController"]["me"].decoratornames(), decorators)
propinferred = list(ast.body[3].value.infer())
self.assertEqual(len(propinferred), 1)
propinferred = propinferred[0]
self.assertIsInstance(propinferred, Instance)
- self.assertEqual(propinferred.name, 'SendMailController')
+ self.assertEqual(propinferred.name, "SendMailController")
self.assertEqual(propinferred.root().name, __name__)
def test_im_func_unwrap(self):
- code = '''
+ code = """
class EnvBasedTC:
def pactions(self):
pass
@@ -1305,32 +1348,32 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
class EnvBasedTC2:
pactions = EnvBasedTC.pactions.im_func
print (pactions)
- '''
+ """
ast = parse(code, __name__)
- pactions = test_utils.get_name_node(ast, 'pactions')
+ pactions = test_utils.get_name_node(ast, "pactions")
inferred = list(pactions.infer())
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], nodes.FunctionDef)
- pactions = test_utils.get_name_node(ast['EnvBasedTC2'], 'pactions')
+ pactions = test_utils.get_name_node(ast["EnvBasedTC2"], "pactions")
inferred = list(pactions.infer())
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], nodes.FunctionDef)
def test_augassign(self):
- code = '''
+ code = """
a = 1
a += 2
print (a)
- '''
+ """
ast = parse(code, __name__)
- inferred = list(test_utils.get_name_node(ast, 'a').infer())
+ inferred = list(test_utils.get_name_node(ast, "a").infer())
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], nodes.Const)
self.assertEqual(inferred[0].value, 3)
def test_nonregr_func_arg(self):
- code = '''
+ code = """
def foo(self, bar):
def baz():
pass
@@ -1338,14 +1381,14 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
return baz
spam = bar(None, qux)
print (spam)
- '''
+ """
ast = parse(code, __name__)
- inferred = list(test_utils.get_name_node(ast['foo'], 'spam').infer())
+ inferred = list(test_utils.get_name_node(ast["foo"], "spam").infer())
self.assertEqual(len(inferred), 1)
self.assertIs(inferred[0], util.Uninferable)
def test_nonregr_func_global(self):
- code = '''
+ code = """
active_application = None
def get_active_application():
@@ -1363,21 +1406,23 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
def test(self):
p = self.app
print (p)
- '''
+ """
ast = parse(code, __name__)
- inferred = list(Instance(ast['DataManager']).igetattr('app'))
- self.assertEqual(len(inferred), 2, inferred) # None / Instance(Application)
- inferred = list(test_utils.get_name_node(ast['DataManager']['test'], 'p').infer())
+ inferred = list(Instance(ast["DataManager"]).igetattr("app"))
+ self.assertEqual(len(inferred), 2, inferred) # None / Instance(Application)
+ inferred = list(
+ test_utils.get_name_node(ast["DataManager"]["test"], "p").infer()
+ )
self.assertEqual(len(inferred), 2, inferred)
for node in inferred:
- if isinstance(node, Instance) and node.name == 'Application':
+ if isinstance(node, Instance) and node.name == "Application":
break
else:
- self.fail('expected to find an instance of Application in %s' % inferred)
+ self.fail("expected to find an instance of Application in %s" % inferred)
def test_list_inference(self):
"""#20464"""
- code = '''
+ code = """
from unknown import Unknown
A = []
B = []
@@ -1389,15 +1434,15 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
return xyz
Z = test()
- '''
+ """
ast = parse(code, __name__)
- inferred = next(ast['Z'].infer())
+ inferred = next(ast["Z"].infer())
self.assertIsInstance(inferred, nodes.List)
self.assertEqual(len(inferred.elts), 1)
self.assertIsInstance(inferred.elts[0], nodes.Unknown)
def test__new__(self):
- code = '''
+ code = """
class NewTest(object):
"doc"
def __new__(cls, arg):
@@ -1406,50 +1451,52 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
return self
n = NewTest()
- '''
+ """
ast = parse(code, __name__)
- self.assertRaises(InferenceError, list, ast['NewTest'].igetattr('arg'))
- n = next(ast['n'].infer())
- inferred = list(n.igetattr('arg'))
+ self.assertRaises(InferenceError, list, ast["NewTest"].igetattr("arg"))
+ n = next(ast["n"].infer())
+ inferred = list(n.igetattr("arg"))
self.assertEqual(len(inferred), 1, inferred)
def test__new__bound_methods(self):
- node = extract_node('''
+ node = extract_node(
+ """
class cls(object): pass
cls().__new__(cls) #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred._proxied, node.root()['cls'])
+ self.assertEqual(inferred._proxied, node.root()["cls"])
def test_two_parents_from_same_module(self):
- code = '''
+ code = """
from data import nonregr
class Xxx(nonregr.Aaa, nonregr.Ccc):
"doc"
- '''
+ """
ast = parse(code, __name__)
- parents = list(ast['Xxx'].ancestors())
- self.assertEqual(len(parents), 3, parents) # Aaa, Ccc, object
+ parents = list(ast["Xxx"].ancestors())
+ self.assertEqual(len(parents), 3, parents) # Aaa, Ccc, object
def test_pluggable_inference(self):
- code = '''
+ code = """
from collections import namedtuple
A = namedtuple('A', ['a', 'b'])
B = namedtuple('B', 'a b')
- '''
+ """
ast = parse(code, __name__)
- aclass = ast['A'].inferred()[0]
+ aclass = ast["A"].inferred()[0]
self.assertIsInstance(aclass, nodes.ClassDef)
- self.assertIn('a', aclass.instance_attrs)
- self.assertIn('b', aclass.instance_attrs)
- bclass = ast['B'].inferred()[0]
+ self.assertIn("a", aclass.instance_attrs)
+ self.assertIn("b", aclass.instance_attrs)
+ bclass = ast["B"].inferred()[0]
self.assertIsInstance(bclass, nodes.ClassDef)
- self.assertIn('a', bclass.instance_attrs)
- self.assertIn('b', bclass.instance_attrs)
+ self.assertIn("a", bclass.instance_attrs)
+ self.assertIn("b", bclass.instance_attrs)
def test_infer_arguments(self):
- code = '''
+ code = """
class A(object):
def first(self, arg1, arg2):
return arg1
@@ -1469,30 +1516,30 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
z = A.static(1, [])
empty = A.empty()
empty_list = A().empty_method()
- '''
+ """
ast = parse(code, __name__)
- int_node = ast['x'].inferred()[0]
+ int_node = ast["x"].inferred()[0]
self.assertIsInstance(int_node, nodes.Const)
self.assertEqual(int_node.value, 1)
- list_node = ast['y'].inferred()[0]
+ list_node = ast["y"].inferred()[0]
self.assertIsInstance(list_node, nodes.List)
- int_node = ast['z'].inferred()[0]
+ int_node = ast["z"].inferred()[0]
self.assertIsInstance(int_node, nodes.Const)
self.assertEqual(int_node.value, 1)
- empty = ast['empty'].inferred()[0]
+ empty = ast["empty"].inferred()[0]
self.assertIsInstance(empty, nodes.Const)
self.assertEqual(empty.value, 2)
- empty_list = ast['empty_list'].inferred()[0]
+ empty_list = ast["empty_list"].inferred()[0]
self.assertIsInstance(empty_list, nodes.List)
def test_infer_variable_arguments(self):
- code = '''
+ code = """
def test(*args, **kwargs):
vararg = args
kwarg = kwargs
- '''
+ """
ast = parse(code, __name__)
- func = ast['test']
+ func = ast["test"]
vararg = func.body[0].value
kwarg = func.body[1].value
@@ -1532,8 +1579,8 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
mul = a * b
"""
ast = parse(code, __name__)
- sub = ast['sub'].inferred()[0]
- mul = ast['mul'].inferred()[0]
+ sub = ast["sub"].inferred()[0]
+ mul = ast["mul"].inferred()[0]
self.assertIs(sub, util.Uninferable)
self.assertIsInstance(mul, nodes.Const)
self.assertEqual(mul.value, 42)
@@ -1551,9 +1598,9 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
mul = a * b
"""
ast = parse(code, __name__)
- sub = ast['sub'].inferred()[0]
- mul = ast['mul'].inferred()[0]
- self.assertIs(sub, util. Uninferable)
+ sub = ast["sub"].inferred()[0]
+ mul = ast["mul"].inferred()[0]
+ self.assertIs(sub, util.Uninferable)
self.assertIsInstance(mul, nodes.Const)
self.assertEqual(mul.value, 42)
@@ -1571,8 +1618,8 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
mul = a * b
"""
ast = parse(code, __name__)
- sub = ast['sub'].inferred()[0]
- mul = ast['mul'].inferred()[0]
+ sub = ast["sub"].inferred()[0]
+ mul = ast["mul"].inferred()[0]
self.assertIs(sub, util.Uninferable)
self.assertIsInstance(mul, nodes.List)
self.assertIsInstance(mul.elts[0], nodes.Const)
@@ -1589,7 +1636,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
c = a * b
"""
ast = parse(code, __name__)
- node = ast['c']
+ node = ast["c"]
self.assertEqual(node.inferred(), [util.Uninferable])
def test_infer_empty_nodes(self):
@@ -1611,11 +1658,12 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
pass
"""
ast = parse(code, __name__)
- node = ast['do_a_thing']
- self.assertEqual(node.type, 'function')
+ node = ast["do_a_thing"]
+ self.assertEqual(node.type, "function")
def test_no_infinite_ancestor_loop(self):
- klass = extract_node("""
+ klass = extract_node(
+ """
import datetime
def method(self):
@@ -1623,10 +1671,9 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
class something(datetime.datetime): #@
pass
- """)
- self.assertIn(
- 'object',
- [base.name for base in klass.ancestors()])
+ """
+ )
+ self.assertIn("object", [base.name for base in klass.ancestors()])
def test_stop_iteration_leak(self):
code = """
@@ -1671,7 +1718,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertIsInstance(inferred, Instance)
self.assertEqual(inferred.qname(), "{}.tuple".format(BUILTINS))
- @test_utils.require_version('3.5')
+ @test_utils.require_version("3.5")
def test_starred_in_tuple_literal(self):
code = """
var = (1, 2, 3)
@@ -1690,7 +1737,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertInferTuple(ast[3], [0, 1, 2, 3, 4, 5, 6, 7, 8])
self.assertInferTuple(ast[4], [0, 1, 2, 3, 4, 5, 6, 7, 999, 1000, 1001])
- @test_utils.require_version('3.5')
+ @test_utils.require_version("3.5")
def test_starred_in_list_literal(self):
code = """
var = (1, 2, 3)
@@ -1709,7 +1756,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertInferList(ast[3], [0, 1, 2, 3, 4, 5, 6, 7, 8])
self.assertInferList(ast[4], [0, 1, 2, 3, 4, 5, 6, 7, 999, 1000, 1001])
- @test_utils.require_version('3.5')
+ @test_utils.require_version("3.5")
def test_starred_in_set_literal(self):
code = """
var = (1, 2, 3)
@@ -1728,7 +1775,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertInferSet(ast[3], [0, 1, 2, 3, 4, 5, 6, 7, 8])
self.assertInferSet(ast[4], [0, 1, 2, 3, 4, 5, 6, 7, 999, 1000, 1001])
- @test_utils.require_version('3.5')
+ @test_utils.require_version("3.5")
def test_starred_in_literals_inference_issues(self):
code = """
{0, *var} #@
@@ -1742,7 +1789,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
with self.assertRaises(InferenceError):
next(node.infer())
- @test_utils.require_version('3.5')
+ @test_utils.require_version("3.5")
def test_starred_in_mapping_literal(self):
code = """
var = {1: 'b', 2: 'c'}
@@ -1752,14 +1799,16 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
{0: 'a', **var, 3: 'd', **{**bar, 6: 'g'}} #@
"""
ast = extract_node(code, __name__)
- self.assertInferDict(ast[0], {0: 'a', 1: 'b', 2: 'c'})
- self.assertInferDict(ast[1], {0: 'a', 1: 'b', 2: 'c', 3: 'd'})
- self.assertInferDict(ast[2], {0: 'a', 1: 'b', 2: 'c', 3: 'd',
- 4: 'e', 5: 'f', 6: 'g'})
+ self.assertInferDict(ast[0], {0: "a", 1: "b", 2: "c"})
+ self.assertInferDict(ast[1], {0: "a", 1: "b", 2: "c", 3: "d"})
+ self.assertInferDict(
+ ast[2], {0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f", 6: "g"}
+ )
- @test_utils.require_version('3.5')
+ @test_utils.require_version("3.5")
def test_starred_in_mapping_literal_no_inference_possible(self):
- node = extract_node('''
+ node = extract_node(
+ """
from unknown import unknown
def test(a):
@@ -1770,10 +1819,11 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
return {0: 1, **a}
test(**func())
- ''')
+ """
+ )
self.assertEqual(next(node.infer()), util.Uninferable)
- @test_utils.require_version('3.5')
+ @test_utils.require_version("3.5")
def test_starred_in_mapping_inference_issues(self):
code = """
{0: 'a', **var} #@
@@ -1785,7 +1835,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
with self.assertRaises(InferenceError):
next(node.infer())
- @test_utils.require_version('3.5')
+ @test_utils.require_version("3.5")
def test_starred_in_mapping_literal_non_const_keys_values(self):
code = """
a, b, c, d, e, f, g, h, i, j = "ABCDEFGHIJ"
@@ -1891,20 +1941,22 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertEqual(inferred.qname(), "{}.list".format(BUILTINS))
def test_conversion_of_dict_methods(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
list({1:2, 2:3}.values()) #@
list({1:2, 2:3}.keys()) #@
tuple({1:2, 2:3}.values()) #@
tuple({1:2, 3:4}.keys()) #@
set({1:2, 2:4}.keys()) #@
- ''')
+ """
+ )
self.assertInferList(ast_nodes[0], [2, 3])
self.assertInferList(ast_nodes[1], [1, 2])
self.assertInferTuple(ast_nodes[2], [2, 3])
self.assertInferTuple(ast_nodes[3], [1, 3])
self.assertInferSet(ast_nodes[4], [1, 2])
- @test_utils.require_version('3.0')
+ @test_utils.require_version("3.0")
def test_builtin_inference_py3k(self):
code = """
list(b"abc") #@
@@ -1946,14 +1998,14 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
"""
ast = extract_node(code, __name__)
self.assertInferDict(ast[0], {})
- self.assertInferDict(ast[1], {'a': 1, 'b': 2, 'c': 3})
+ self.assertInferDict(ast[1], {"a": 1, "b": 2, "c": 3})
for i in range(2, 5):
self.assertInferDict(ast[i], {1: 2, 2: 3})
- self.assertInferDict(ast[5], {'a': 2, 'b': 2, 'c': 3})
+ self.assertInferDict(ast[5], {"a": 2, "b": 2, "c": 3})
self.assertInferDict(ast[6], {1: 2})
- self.assertInferDict(ast[7], {'c': 2, 'a': 4, 'b': 5})
- self.assertInferDict(ast[8], {'a': 1, 'b': 2})
- self.assertInferDict(ast[9], {'x': 2, 'y': 3, 'a': 1, 'b': 2})
+ self.assertInferDict(ast[7], {"c": 2, "a": 4, "b": 5})
+ self.assertInferDict(ast[8], {"a": 1, "b": 2})
+ self.assertInferDict(ast[9], {"x": 2, "y": 3, "a": 1, "b": 2})
for node in ast[10:]:
inferred = next(node.infer())
@@ -1961,21 +2013,21 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertEqual(inferred.qname(), "{}.dict".format(BUILTINS))
def test_dict_inference_kwargs(self):
- ast_node = extract_node('''dict(a=1, b=2, **{'c': 3})''')
- self.assertInferDict(ast_node, {'a': 1, 'b': 2, 'c': 3})
+ ast_node = extract_node("""dict(a=1, b=2, **{'c': 3})""")
+ self.assertInferDict(ast_node, {"a": 1, "b": 2, "c": 3})
- @test_utils.require_version('3.5')
+ @test_utils.require_version("3.5")
def test_dict_inference_for_multiple_starred(self):
pairs = [
- ('dict(a=1, **{"b": 2}, **{"c":3})', {'a':1, 'b':2, 'c':3}),
- ('dict(a=1, **{"b": 2}, d=4, **{"c":3})', {'a':1, 'b':2, 'c':3, 'd':4}),
- ('dict({"a":1}, b=2, **{"c":3})', {'a':1, 'b':2, 'c':3}),
+ ('dict(a=1, **{"b": 2}, **{"c":3})', {"a": 1, "b": 2, "c": 3}),
+ ('dict(a=1, **{"b": 2}, d=4, **{"c":3})', {"a": 1, "b": 2, "c": 3, "d": 4}),
+ ('dict({"a":1}, b=2, **{"c":3})', {"a": 1, "b": 2, "c": 3}),
]
for code, expected_value in pairs:
node = extract_node(code)
self.assertInferDict(node, expected_value)
- @test_utils.require_version('3.5')
+ @test_utils.require_version("3.5")
def test_dict_inference_unpack_repeated_key(self):
"""Make sure astroid does not infer repeated keys in a dictionary
@@ -1990,21 +2042,12 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
b4 = {a: 3, **base} #@
"""
ast = extract_node(code)
- final_values = (
- "{'data': 1}",
- "{'data': 0}",
- "{'data': 3}",
- "{'data': 0}",
- )
+ final_values = ("{'data': 1}", "{'data': 0}", "{'data': 3}", "{'data': 0}")
for node, final_value in zip(ast, final_values):
assert node.targets[0].inferred()[0].as_string() == final_value
def test_dict_invalid_args(self):
- invalid_values = [
- 'dict(*1)',
- 'dict(**lala)',
- 'dict(**[])',
- ]
+ invalid_values = ["dict(*1)", "dict(**lala)", "dict(**[])"]
for invalid in invalid_values:
ast_node = extract_node(invalid)
inferred = next(ast_node.infer())
@@ -2036,9 +2079,9 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
' '.count() #@
"""
ast = extract_node(code, __name__)
- self.assertInferConst(ast[0], '')
+ self.assertInferConst(ast[0], "")
for i in range(1, 16):
- self.assertInferConst(ast[i], '')
+ self.assertInferConst(ast[i], "")
for i in range(16, 19):
self.assertInferConst(ast[i], 0)
@@ -2067,29 +2110,30 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
u' '.count() #@
"""
ast = extract_node(code, __name__)
- self.assertInferConst(ast[0], '')
+ self.assertInferConst(ast[0], "")
for i in range(1, 16):
- self.assertInferConst(ast[i], '')
+ self.assertInferConst(ast[i], "")
for i in range(16, 19):
self.assertInferConst(ast[i], 0)
def test_scope_lookup_same_attributes(self):
- code = '''
+ code = """
import collections
class Second(collections.Counter):
def collections(self):
return "second"
- '''
+ """
ast = parse(code, __name__)
- bases = ast['Second'].bases[0]
+ bases = ast["Second"].bases[0]
inferred = next(bases.infer())
self.assertTrue(inferred)
self.assertIsInstance(inferred, nodes.ClassDef)
- self.assertEqual(inferred.qname(), 'collections.Counter')
+ self.assertEqual(inferred.qname(), "collections.Counter")
def test_inferring_with_statement_failures(self):
- module = parse('''
+ module = parse(
+ """
class NoEnter(object):
pass
class NoMethod(object):
@@ -2104,13 +2148,15 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
pass
with NoElts() as (no_elts, no_elts1):
pass
- ''')
- self.assertRaises(InferenceError, next, module['no_enter'].infer())
- self.assertRaises(InferenceError, next, module['no_method'].infer())
- self.assertRaises(InferenceError, next, module['no_elts'].infer())
+ """
+ )
+ self.assertRaises(InferenceError, next, module["no_enter"].infer())
+ self.assertRaises(InferenceError, next, module["no_method"].infer())
+ self.assertRaises(InferenceError, next, module["no_elts"].infer())
def test_inferring_with_statement(self):
- module = parse('''
+ module = parse(
+ """
class SelfContext(object):
def __enter__(self):
return self
@@ -2135,33 +2181,35 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
pass
with MultipleReturns2() as (stdout, (stderr, stdin)):
pass
- ''')
- self_context = module['self_context']
+ """
+ )
+ self_context = module["self_context"]
inferred = next(self_context.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'SelfContext')
+ self.assertEqual(inferred.name, "SelfContext")
- other_context = module['other_context']
+ other_context = module["other_context"]
inferred = next(other_context.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'SelfContext')
+ self.assertEqual(inferred.name, "SelfContext")
- multiple_with = module['multiple_with']
+ multiple_with = module["multiple_with"]
inferred = next(multiple_with.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'SelfContext')
+ self.assertEqual(inferred.name, "SelfContext")
- stdout = module['stdout']
+ stdout = module["stdout"]
inferred = next(stdout.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 1)
- stderr = module['stderr']
+ stderr = module["stderr"]
inferred = next(stderr.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 2)
def test_inferring_with_contextlib_contextmanager(self):
- module = parse('''
+ module = parse(
+ """
import contextlib
from contextlib import contextmanager
@@ -2192,20 +2240,21 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
pass
with manager_multiple() as (first, second):
pass
- ''')
- none = module['none']
+ """
+ )
+ none = module["none"]
inferred = next(none.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertIsNone(inferred.value)
- something = module['something']
+ something = module["something"]
inferred = something.inferred()
self.assertEqual(len(inferred), 1)
inferred = inferred[0]
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 42)
- first, second = module['first'], module['second']
+ first, second = module["first"], module["second"]
first = next(first.infer())
second = next(second.infer())
self.assertIsInstance(first, nodes.Const)
@@ -2219,18 +2268,21 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
# indices. This is the case of contextlib.nested, where the
# result is a list, which is mutated later on, so it's
# undetected by astroid.
- module = parse('''
+ module = parse(
+ """
class Manager(object):
def __enter__(self):
return []
with Manager() as (a, b, c):
pass
- ''')
- self.assertRaises(InferenceError, next, module['a'].infer())
+ """
+ )
+ self.assertRaises(InferenceError, next, module["a"].infer())
def test_inferring_context_manager_unpacking_inference_error(self):
# https://github.com/PyCQA/pylint/issues/1463
- module = parse('''
+ module = parse(
+ """
import contextlib
@contextlib.contextmanager
@@ -2241,11 +2293,13 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
result = _select_source()
with result as (a, b, c):
pass
- ''')
- self.assertRaises(InferenceError, next, module['a'].infer())
+ """
+ )
+ self.assertRaises(InferenceError, next, module["a"].infer())
def test_inferring_with_contextlib_contextmanager_failures(self):
- module = parse('''
+ module = parse(
+ """
from contextlib import contextmanager
def no_decorators_mgr():
@@ -2263,10 +2317,11 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
pass
with no_yield_mgr() as no_yield:
pass
- ''')
- self.assertRaises(InferenceError, next, module['no_decorators'].infer())
- self.assertRaises(InferenceError, next, module['other_decorators'].infer())
- self.assertRaises(InferenceError, next, module['no_yield'].infer())
+ """
+ )
+ self.assertRaises(InferenceError, next, module["no_decorators"].infer())
+ self.assertRaises(InferenceError, next, module["other_decorators"].infer())
+ self.assertRaises(InferenceError, next, module["no_yield"].infer())
def test_nested_contextmanager(self):
"""Make sure contextmanager works with nested functions
@@ -2299,11 +2354,12 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
assert isinstance(value, nodes.Const)
def test_unary_op_leaks_stop_iteration(self):
- node = extract_node('+[] #@')
+ node = extract_node("+[] #@")
self.assertEqual(util.Uninferable, next(node.infer()))
def test_unary_operands(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
import os
def func(): pass
from missing import missing
@@ -2343,7 +2399,8 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
~os #@
-func #@
+BadInstance #@
- ''')
+ """
+ )
expected = [42, 1, 42, -1, 24, 25]
for node, value in zip(ast_nodes[:6], expected):
inferred = next(node.infer())
@@ -2355,15 +2412,18 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertEqual(inferred, util.Uninferable)
def test_unary_op_instance_method_not_callable(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A:
__pos__ = (i for i in range(10))
+A() #@
- ''')
+ """
+ )
self.assertRaises(InferenceError, next, ast_node.infer())
def test_binary_op_type_errors(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
import collections
1 + "a" #@
1 - [] #@
@@ -2406,7 +2466,8 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
f+=A() #@
x = 1
x+=[] #@
- ''')
+ """
+ )
msg = "unsupported operand type(s) for {op}: {lhs!r} and {rhs!r}"
expected = [
msg.format(op="+", lhs="int", rhs="str"),
@@ -2438,7 +2499,8 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertEqual(str(error), expected_value)
def test_unary_type_errors(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
import collections
~[] #@
~() #@
@@ -2455,23 +2517,24 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
~A() #@
~collections #@
~2.0 #@
- ''')
+ """
+ )
msg = "bad operand type for unary {op}: {type}"
expected = [
- msg.format(op="~", type='list'),
- msg.format(op="~", type='tuple'),
- msg.format(op="~", type='dict'),
- msg.format(op="~", type='dict'),
- msg.format(op="~", type='set'),
- msg.format(op="-", type='set'),
- msg.format(op="-", type='str'),
- msg.format(op="~", type='str'),
- msg.format(op="+", type='str'),
- msg.format(op="~", type='<lambda>'),
- msg.format(op="~", type='A'),
- msg.format(op="~", type='A'),
- msg.format(op="~", type='collections'),
- msg.format(op="~", type='float'),
+ msg.format(op="~", type="list"),
+ msg.format(op="~", type="tuple"),
+ msg.format(op="~", type="dict"),
+ msg.format(op="~", type="dict"),
+ msg.format(op="~", type="set"),
+ msg.format(op="-", type="set"),
+ msg.format(op="-", type="str"),
+ msg.format(op="~", type="str"),
+ msg.format(op="+", type="str"),
+ msg.format(op="~", type="<lambda>"),
+ msg.format(op="~", type="A"),
+ msg.format(op="~", type="A"),
+ msg.format(op="~", type="collections"),
+ msg.format(op="~", type="float"),
]
for node, expected_value in zip(ast_nodes, expected):
errors = node.type_errors()
@@ -2481,10 +2544,12 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
def test_unary_empty_type_errors(self):
# These aren't supported right now
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
~(2 and []) #@
-(0 or {}) #@
- ''')
+ """
+ )
expected = [
"bad operand type for unary ~: list",
"bad operand type for unary -: dict",
@@ -2495,24 +2560,21 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertEqual(str(errors[0]), expected_value)
def test_unary_type_errors_for_non_instance_objects(self):
- node = extract_node('~slice(1, 2, 3)')
+ node = extract_node("~slice(1, 2, 3)")
errors = node.type_errors()
self.assertEqual(len(errors), 1)
- self.assertEqual(
- str(errors[0]),
- 'bad operand type for unary ~: slice'
- )
+ self.assertEqual(str(errors[0]), "bad operand type for unary ~: slice")
def test_bool_value_recursive(self):
pairs = [
- ('{}', False),
- ('{1:2}', True),
- ('()', False),
- ('(1, 2)', True),
- ('[]', False),
- ('[1,2]', True),
- ('frozenset()', False),
- ('frozenset((1, 2))', True),
+ ("{}", False),
+ ("{1:2}", True),
+ ("()", False),
+ ("(1, 2)", True),
+ ("[]", False),
+ ("[1,2]", True),
+ ("frozenset()", False),
+ ("frozenset((1, 2))", True),
]
for code, expected in pairs:
node = extract_node(code)
@@ -2520,20 +2582,23 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertEqual(inferred.bool_value(), expected)
def test_genexpr_bool_value(self):
- node = extract_node('''(x for x in range(10))''')
+ node = extract_node("""(x for x in range(10))""")
self.assertTrue(node.bool_value())
def test_name_bool_value(self):
- node = extract_node('''
+ node = extract_node(
+ """
x = 42
y = x
y
- ''')
+ """
+ )
self.assertIs(node.bool_value(), util.Uninferable)
def test_bool_value(self):
# Verify the truth value of nodes.
- module = parse('''
+ module = parse(
+ """
import collections
collections_module = collections
def function(): pass
@@ -2558,40 +2623,42 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
compare = 2 < 3
const_str_true = 'testconst'
const_str_false = ''
- ''')
- collections_module = next(module['collections_module'].infer())
+ """
+ )
+ collections_module = next(module["collections_module"].infer())
self.assertTrue(collections_module.bool_value())
- function = module['function']
+ function = module["function"]
self.assertTrue(function.bool_value())
- klass = module['Class']
+ klass = module["Class"]
self.assertTrue(klass.bool_value())
- dict_comp = next(module['dict_comp'].infer())
+ dict_comp = next(module["dict_comp"].infer())
self.assertEqual(dict_comp, util.Uninferable)
- set_comp = next(module['set_comp'].infer())
+ set_comp = next(module["set_comp"].infer())
self.assertEqual(set_comp, util.Uninferable)
- list_comp = next(module['list_comp'].infer())
+ list_comp = next(module["list_comp"].infer())
self.assertEqual(list_comp, util.Uninferable)
- lambda_func = next(module['lambda_func'].infer())
+ lambda_func = next(module["lambda_func"].infer())
self.assertTrue(lambda_func)
- unbound_method = next(module['unbound_method'].infer())
+ unbound_method = next(module["unbound_method"].infer())
self.assertTrue(unbound_method)
- bound_method = next(module['bound_method'].infer())
+ bound_method = next(module["bound_method"].infer())
self.assertTrue(bound_method)
- generator = next(module['generator'].infer())
+ generator = next(module["generator"].infer())
self.assertTrue(generator)
- bin_op = module['bin_op'].parent.value
+ bin_op = module["bin_op"].parent.value
self.assertIs(bin_op.bool_value(), util.Uninferable)
- bool_op = module['bool_op'].parent.value
+ bool_op = module["bool_op"].parent.value
self.assertEqual(bool_op.bool_value(), util.Uninferable)
- callfunc = module['callfunc'].parent.value
+ callfunc = module["callfunc"].parent.value
self.assertEqual(callfunc.bool_value(), util.Uninferable)
- good_callfunc = next(module['good_callfunc'].infer())
+ good_callfunc = next(module["good_callfunc"].infer())
self.assertTrue(good_callfunc.bool_value())
- compare = module['compare'].parent.value
+ compare = module["compare"].parent.value
self.assertEqual(compare.bool_value(), util.Uninferable)
def test_bool_value_instances(self):
- instances = extract_node('''
+ instances = extract_node(
+ """
class FalseBoolInstance(object):
def {bool}(self):
return False
@@ -2620,14 +2687,18 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
TrueLenInstance() #@
AlwaysTrueInstance() #@
ErrorInstance() #@
- '''.format(bool=BOOL_SPECIAL_METHOD))
+ """.format(
+ bool=BOOL_SPECIAL_METHOD
+ )
+ )
expected = (False, True, False, True, True, util.Uninferable, util.Uninferable)
for node, expected_value in zip(instances, expected):
inferred = next(node.infer())
self.assertEqual(inferred.bool_value(), expected_value)
def test_bool_value_variable(self):
- instance = extract_node('''
+ instance = extract_node(
+ """
class VariableBoolInstance(object):
def __init__(self, value):
self.value = value
@@ -2635,12 +2706,16 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
return self.value
not VariableBoolInstance(True)
- '''.format(bool=BOOL_SPECIAL_METHOD))
+ """.format(
+ bool=BOOL_SPECIAL_METHOD
+ )
+ )
inferred = next(instance.infer())
self.assertIs(inferred.bool_value(), util.Uninferable)
def test_infer_coercion_rules_for_floats_complex(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
1 + 1.0 #@
1 * 1.0 #@
2 - 1.0 #@
@@ -2649,17 +2724,20 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
2 * 1j #@
2 - 1j #@
3 / 1j #@
- ''')
+ """
+ )
expected_values = [2.0, 1.0, 1.0, 1.0, 1 + 1j, 2j, 2 - 1j, -3j]
for node, expected in zip(ast_nodes, expected_values):
inferred = next(node.infer())
self.assertEqual(inferred.value, expected)
def test_binop_list_with_elts(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
x = [A] * 1
[1] + x
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.List)
self.assertEqual(len(inferred.elts), 2)
@@ -2667,7 +2745,8 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertIsInstance(inferred.elts[1], nodes.Unknown)
def test_binop_same_types(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class A(object):
def __add__(self, other):
return 42
@@ -2675,7 +2754,8 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
1 - 1 #@
"a" + "b" #@
A() + A() #@
- ''')
+ """
+ )
expected_values = [2, 0, "ab", 42]
for node, expected in zip(ast_nodes, expected_values):
inferred = next(node.infer())
@@ -2683,20 +2763,23 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertEqual(inferred.value, expected)
def test_binop_different_types_reflected_only(self):
- node = extract_node('''
+ node = extract_node(
+ """
class A(object):
pass
class B(object):
def __radd__(self, other):
return other
A() + B() #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'A')
+ self.assertEqual(inferred.name, "A")
def test_binop_different_types_unknown_bases(self):
- node = extract_node('''
+ node = extract_node(
+ """
from foo import bar
class A(bar):
@@ -2705,12 +2788,14 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
def __radd__(self, other):
return other
A() + B() #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIs(inferred, util.Uninferable)
def test_binop_different_types_normal_not_implemented_and_reflected(self):
- node = extract_node('''
+ node = extract_node(
+ """
class A(object):
def __add__(self, other):
return NotImplemented
@@ -2718,80 +2803,94 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
def __radd__(self, other):
return other
A() + B() #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'A')
+ self.assertEqual(inferred.name, "A")
def test_binop_different_types_no_method_implemented(self):
- node = extract_node('''
+ node = extract_node(
+ """
class A(object):
pass
class B(object): pass
A() + B() #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertEqual(inferred, util.Uninferable)
def test_binop_different_types_reflected_and_normal_not_implemented(self):
- node = extract_node('''
+ node = extract_node(
+ """
class A(object):
def __add__(self, other): return NotImplemented
class B(object):
def __radd__(self, other): return NotImplemented
A() + B() #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertEqual(inferred, util.Uninferable)
def test_binop_subtype(self):
- node = extract_node('''
+ node = extract_node(
+ """
class A(object): pass
class B(A):
def __add__(self, other): return other
B() + A() #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'A')
+ self.assertEqual(inferred.name, "A")
def test_binop_subtype_implemented_in_parent(self):
- node = extract_node('''
+ node = extract_node(
+ """
class A(object):
def __add__(self, other): return other
class B(A): pass
B() + A() #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'A')
+ self.assertEqual(inferred.name, "A")
def test_binop_subtype_not_implemented(self):
- node = extract_node('''
+ node = extract_node(
+ """
class A(object):
pass
class B(A):
def __add__(self, other): return NotImplemented
B() + A() #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertEqual(inferred, util.Uninferable)
def test_binop_supertype(self):
- node = extract_node('''
+ node = extract_node(
+ """
class A(object):
pass
class B(A):
def __radd__(self, other):
return other
A() + B() #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'A')
+ self.assertEqual(inferred.name, "A")
def test_binop_supertype_rop_not_implemented(self):
- node = extract_node('''
+ node = extract_node(
+ """
class A(object):
def __add__(self, other):
return other
@@ -2799,25 +2898,29 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
def __radd__(self, other):
return NotImplemented
A() + B() #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'B')
+ self.assertEqual(inferred.name, "B")
def test_binop_supertype_both_not_implemented(self):
- node = extract_node('''
+ node = extract_node(
+ """
class A(object):
def __add__(self): return NotImplemented
class B(A):
def __radd__(self, other):
return NotImplemented
A() + B() #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertEqual(inferred, util.Uninferable)
def test_binop_inference_errors(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
from unknown import Unknown
class A(object):
def __add__(self, other): return NotImplemented
@@ -2827,12 +2930,14 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
Unknown + A() #@
B() + A() #@
A() + B() #@
- ''')
+ """
+ )
for node in ast_nodes:
self.assertEqual(next(node.infer()), util.Uninferable)
def test_binop_ambiguity(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class A(object):
def __add__(self, other):
if isinstance(other, B):
@@ -2850,12 +2955,14 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
B() + A() #@
A() + C() #@
C() + A() #@
- ''')
+ """
+ )
for node in ast_nodes:
self.assertEqual(next(node.infer()), util.Uninferable)
def test_metaclass__getitem__(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class Meta(type):
def __getitem__(cls, arg):
return 24
@@ -2865,13 +2972,15 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
pass
A['Awesome'] #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 24)
def test_bin_op_classes(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class Meta(type):
def __or__(self, other):
return 24
@@ -2881,13 +2990,15 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
pass
A | A
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 24)
def test_bin_op_supertype_more_complicated_example(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object):
def __init__(self):
self.foo = 42
@@ -2901,45 +3012,53 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
return NotImplemented
A() + B() #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(int(inferred.value), 45)
def test_aug_op_same_type_not_implemented(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object):
def __iadd__(self, other): return NotImplemented
def __add__(self, other): return NotImplemented
A() + A() #@
- ''')
+ """
+ )
self.assertEqual(next(ast_node.infer()), util.Uninferable)
def test_aug_op_same_type_aug_implemented(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object):
def __iadd__(self, other): return other
f = A()
f += A() #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'A')
+ self.assertEqual(inferred.name, "A")
def test_aug_op_same_type_aug_not_implemented_normal_implemented(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object):
def __iadd__(self, other): return NotImplemented
def __add__(self, other): return 42
f = A()
f += A() #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 42)
def test_aug_op_subtype_both_not_implemented(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object):
def __iadd__(self, other): return NotImplemented
def __add__(self, other): return NotImplemented
@@ -2947,71 +3066,83 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
pass
b = B()
b+=A() #@
- ''')
+ """
+ )
self.assertEqual(next(ast_node.infer()), util.Uninferable)
def test_aug_op_subtype_aug_op_is_implemented(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object):
def __iadd__(self, other): return 42
class B(A):
pass
b = B()
b+=A() #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 42)
def test_aug_op_subtype_normal_op_is_implemented(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object):
def __add__(self, other): return 42
class B(A):
pass
b = B()
b+=A() #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 42)
def test_aug_different_types_no_method_implemented(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object): pass
class B(object): pass
f = A()
f += B() #@
- ''')
+ """
+ )
self.assertEqual(next(ast_node.infer()), util.Uninferable)
def test_aug_different_types_augop_implemented(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object):
def __iadd__(self, other): return other
class B(object): pass
f = A()
f += B() #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'B')
+ self.assertEqual(inferred.name, "B")
def test_aug_different_types_aug_not_implemented(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object):
def __iadd__(self, other): return NotImplemented
def __add__(self, other): return other
class B(object): pass
f = A()
f += B() #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'B')
+ self.assertEqual(inferred.name, "B")
def test_aug_different_types_aug_not_implemented_rop_fallback(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object):
def __iadd__(self, other): return NotImplemented
def __add__(self, other): return NotImplemented
@@ -3019,22 +3150,26 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
def __radd__(self, other): return other
f = A()
f += B() #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'A')
+ self.assertEqual(inferred.name, "A")
def test_augop_supertypes_none_implemented(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object): pass
class B(object): pass
a = A()
a += B() #@
- ''')
+ """
+ )
self.assertEqual(next(ast_node.infer()), util.Uninferable)
def test_augop_supertypes_not_implemented_returned_for_all(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object):
def __iadd__(self, other): return NotImplemented
def __add__(self, other): return NotImplemented
@@ -3042,36 +3177,42 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
def __add__(self, other): return NotImplemented
a = A()
a += B() #@
- ''')
+ """
+ )
self.assertEqual(next(ast_node.infer()), util.Uninferable)
def test_augop_supertypes_augop_implemented(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object):
def __iadd__(self, other): return other
class B(A): pass
a = A()
a += B() #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'B')
+ self.assertEqual(inferred.name, "B")
def test_augop_supertypes_reflected_binop_implemented(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object):
def __iadd__(self, other): return NotImplemented
class B(A):
def __radd__(self, other): return other
a = A()
a += B() #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'A')
+ self.assertEqual(inferred.name, "A")
def test_augop_supertypes_normal_binop_implemented(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object):
def __iadd__(self, other): return NotImplemented
def __add__(self, other): return other
@@ -3080,17 +3221,20 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
a = A()
a += B() #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'B')
+ self.assertEqual(inferred.name, "B")
@unittest.expectedFailure
def test_string_interpolation(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
"a%d%d" % (1, 2) #@
"a%(x)s" % {"x": 42} #@
- ''')
+ """
+ )
expected = ["a12", "a42"]
for node, expected_value in zip(ast_nodes, expected):
inferred = next(node.infer())
@@ -3098,7 +3242,8 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertEqual(inferred.value, expected_value)
def test_mul_list_supports__index__(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class Index(object):
def __index__(self): return 2
class NotIndex(object): pass
@@ -3108,17 +3253,18 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
a * Index() #@
a * NotIndex() #@
a * NotIndex2() #@
- ''')
+ """
+ )
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, nodes.List)
- self.assertEqual([node.value for node in first.itered()],
- [1, 2, 1, 2])
+ self.assertEqual([node.value for node in first.itered()], [1, 2, 1, 2])
for rest in ast_nodes[1:]:
inferred = next(rest.infer())
self.assertEqual(inferred, util.Uninferable)
def test_subscript_supports__index__(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class Index(object):
def __index__(self): return 2
class LambdaIndex(object):
@@ -3131,7 +3277,8 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
a[Index()] #@
a[LambdaIndex()] #@
a[NonIndex()] #@
- ''')
+ """
+ )
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, nodes.Const)
self.assertEqual(first.value, 3)
@@ -3141,7 +3288,8 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
self.assertRaises(InferenceError, next, ast_nodes[2].infer())
def test_special_method_masquerading_as_another(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class Info(object):
def __add__(self, other):
return "lala"
@@ -3149,26 +3297,30 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
f = Info()
f | Info() #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, "lala")
def test_unary_op_assignment(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object): pass
def pos(self):
return 42
A.__pos__ = pos
f = A()
+f #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 42)
def test_unary_op_classes(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
import six
class Meta(type):
def __invert__(self):
@@ -3177,7 +3329,8 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
class A(object):
pass
~A
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 42)
@@ -3187,8 +3340,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
ast_node = extract_node(code)
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, cls)
- self.assertEqual(get_elts(inferred), expected,
- ast_node.as_string())
+ self.assertEqual(get_elts(inferred), expected, ast_node.as_string())
def test_slicing_list(self):
pairs = (
@@ -3206,8 +3358,8 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
("[1, 2, 3, 4, 5, 6][0:4-1:2+0] #@", [1, 3]),
)
self._slicing_test_helper(
- pairs, nodes.List,
- lambda inferred: [elt.value for elt in inferred.elts])
+ pairs, nodes.List, lambda inferred: [elt.value for elt in inferred.elts]
+ )
def test_slicing_tuple(self):
pairs = (
@@ -3225,8 +3377,8 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
("(1, 2, 3, 4, 5, 6)[0:4-1:2+0] #@", [1, 3]),
)
self._slicing_test_helper(
- pairs, nodes.Tuple,
- lambda inferred: [elt.value for elt in inferred.elts])
+ pairs, nodes.Tuple, lambda inferred: [elt.value for elt in inferred.elts]
+ )
def test_slicing_str(self):
pairs = (
@@ -3243,8 +3395,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
("'123'[0:2:2] #@", "1"),
("'123456'[0:4-1:2+0] #@", "13"),
)
- self._slicing_test_helper(
- pairs, nodes.Const, lambda inferred: inferred.value)
+ self._slicing_test_helper(pairs, nodes.Const, lambda inferred: inferred.value)
def test_invalid_slicing_primaries(self):
examples = [
@@ -3253,184 +3404,207 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
"(1, 2, 3)[a:]",
"(1, 2, 3)[object:object]",
"(1, 2, 3)[1:object]",
- 'enumerate[2]'
+ "enumerate[2]",
]
for code in examples:
node = extract_node(code)
self.assertRaises(InferenceError, next, node.infer())
def test_instance_slicing(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class A(object):
def __getitem__(self, index):
return [1, 2, 3, 4, 5][index]
A()[1:] #@
A()[:2] #@
A()[1:4] #@
- ''')
- expected_values = [
- [2, 3, 4, 5],
- [1, 2],
- [2, 3, 4],
- ]
+ """
+ )
+ expected_values = [[2, 3, 4, 5], [1, 2], [2, 3, 4]]
for expected, node in zip(expected_values, ast_nodes):
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.List)
self.assertEqual([elt.value for elt in inferred.elts], expected)
def test_instance_slicing_slices(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object):
def __getitem__(self, index):
return index
A()[1:] #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.Slice)
self.assertEqual(inferred.lower.value, 1)
self.assertIsNone(inferred.upper)
def test_instance_slicing_fails(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class A(object):
def __getitem__(self, index):
return 1[index]
A()[4:5] #@
A()[2:] #@
- ''')
+ """
+ )
for node in ast_nodes:
self.assertEqual(next(node.infer()), util.Uninferable)
def test_type__new__with_metaclass(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class Metaclass(type):
pass
class Entity(object):
pass
type.__new__(Metaclass, 'NewClass', (Entity,), {'a': 1}) #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.ClassDef)
- self.assertEqual(inferred.name, 'NewClass')
+ self.assertEqual(inferred.name, "NewClass")
metaclass = inferred.metaclass()
- self.assertEqual(metaclass, inferred.root()['Metaclass'])
+ self.assertEqual(metaclass, inferred.root()["Metaclass"])
ancestors = list(inferred.ancestors())
self.assertEqual(len(ancestors), 2)
- self.assertEqual(ancestors[0], inferred.root()['Entity'])
- attributes = inferred.getattr('a')
+ self.assertEqual(ancestors[0], inferred.root()["Entity"])
+ attributes = inferred.getattr("a")
self.assertEqual(len(attributes), 1)
self.assertIsInstance(attributes[0], nodes.Const)
self.assertEqual(attributes[0].value, 1)
-
def test_type__new__not_enough_arguments(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
type.__new__(type, 'foo') #@
type.__new__(type, 'foo', ()) #@
type.__new__(type, 'foo', (), {}, ()) #@
- ''')
+ """
+ )
for node in ast_nodes:
with pytest.raises(InferenceError):
next(node.infer())
def test_type__new__invalid_mcs_argument(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class Class(object): pass
type.__new__(1, 2, 3, 4) #@
type.__new__(Class, 2, 3, 4) #@
- ''')
+ """
+ )
for node in ast_nodes:
with pytest.raises(InferenceError):
next(node.infer())
def test_type__new__invalid_name(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class Class(type): pass
type.__new__(Class, object, 1, 2) #@
type.__new__(Class, 1, 1, 2) #@
type.__new__(Class, [], 1, 2) #@
- ''')
+ """
+ )
for node in ast_nodes:
with pytest.raises(InferenceError):
next(node.infer())
def test_type__new__invalid_bases(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
type.__new__(type, 'a', 1, 2) #@
type.__new__(type, 'a', [], 2) #@
type.__new__(type, 'a', {}, 2) #@
type.__new__(type, 'a', (1, ), 2) #@
type.__new__(type, 'a', (object, 1), 2) #@
- ''')
+ """
+ )
for node in ast_nodes:
with pytest.raises(InferenceError):
next(node.infer())
def test_type__new__invalid_attrs(self):
- type_error_nodes = extract_node('''
+ type_error_nodes = extract_node(
+ """
type.__new__(type, 'a', (), ()) #@
type.__new__(type, 'a', (), object) #@
type.__new__(type, 'a', (), 1) #@
- ''')
+ """
+ )
for node in type_error_nodes:
with pytest.raises(InferenceError):
next(node.infer())
# Ignore invalid keys
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
type.__new__(type, 'a', (), {object: 1}) #@
type.__new__(type, 'a', (), {1:2, "a":5}) #@
- ''')
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.ClassDef)
def test_type__new__metaclass_lookup(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class Metaclass(type):
def test(cls): pass
@classmethod
def test1(cls): pass
attr = 42
type.__new__(Metaclass, 'A', (), {}) #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.ClassDef)
- test = inferred.getattr('test')
+ test = inferred.getattr("test")
self.assertEqual(len(test), 1)
self.assertIsInstance(test[0], BoundMethod)
self.assertIsInstance(test[0].bound, nodes.ClassDef)
self.assertEqual(test[0].bound, inferred)
- test1 = inferred.getattr('test1')
+ test1 = inferred.getattr("test1")
self.assertEqual(len(test1), 1)
self.assertIsInstance(test1[0], BoundMethod)
self.assertIsInstance(test1[0].bound, nodes.ClassDef)
self.assertEqual(test1[0].bound, inferred.metaclass())
- attr = inferred.getattr('attr')
+ attr = inferred.getattr("attr")
self.assertEqual(len(attr), 1)
self.assertIsInstance(attr[0], nodes.Const)
self.assertEqual(attr[0].value, 42)
def test_type__new__metaclass_and_ancestors_lookup(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class Book(object):
title = 'Ubik'
class MetaBook(type):
title = 'Grimus'
type.__new__(MetaBook, 'book', (Book, ), {'title':'Catch 22'}) #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.ClassDef)
- titles = [title.value for attr in inferred.getattr('title')
- for title in attr.inferred()]
- self.assertEqual(titles, ['Catch 22', 'Ubik', 'Grimus'])
+ titles = [
+ title.value
+ for attr in inferred.getattr("title")
+ for title in attr.inferred()
+ ]
+ self.assertEqual(titles, ["Catch 22", "Ubik", "Grimus"])
@unittest.expectedFailure
def test_function_metaclasses(self):
# These are not supported right now, although
# they will be in the future.
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
import six
class BookMeta(type):
@@ -3443,18 +3617,20 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
class Book(object):
pass
Book #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
metaclass = inferred.metaclass()
self.assertIsInstance(metaclass, nodes.ClassDef)
- self.assertEqual(metaclass.name, 'BookMeta')
- author = next(inferred.igetattr('author'))
+ self.assertEqual(metaclass.name, "BookMeta")
+ author = next(inferred.igetattr("author"))
self.assertIsInstance(author, nodes.Const)
- self.assertEqual(author.value, 'Rushdie')
+ self.assertEqual(author.value, "Rushdie")
def test_subscript_inference_error(self):
# Used to raise StopIteration
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class AttributeDict(dict):
def __getitem__(self, name):
return self
@@ -3462,11 +3638,13 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
flow['app'] = AttributeDict()
flow['app']['config'] = AttributeDict()
flow['app']['config']['doffing'] = AttributeDict() #@
- ''')
+ """
+ )
self.assertIsNone(helpers.safe_infer(ast_node.targets[0]))
def test_classmethod_inferred_by_context(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class Super(object):
def instance(cls):
return cls()
@@ -3479,13 +3657,15 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
# should see the Sub.instance() is returning a Sub
# instance, not a Super instance
Sub.instance().method() #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, Instance)
- self.assertEqual(inferred.name, 'Sub')
+ self.assertEqual(inferred.name, "Sub")
def test_infer_call_result_invalid_dunder_call_on_instance(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class A:
__call__ = 42
class B:
@@ -3495,13 +3675,15 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
A() #@
B() #@
C() #@
- ''')
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
self.assertRaises(InferenceError, next, inferred.infer_call_result(node))
def test_context_call_for_context_managers(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class A:
def __enter__(self):
return self
@@ -3518,19 +3700,21 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
b #@
with C() as c:
c #@
- ''')
+ """
+ )
first_a = next(ast_nodes[0].infer())
self.assertIsInstance(first_a, Instance)
- self.assertEqual(first_a.name, 'A')
+ self.assertEqual(first_a.name, "A")
second_b = next(ast_nodes[1].infer())
self.assertIsInstance(second_b, Instance)
- self.assertEqual(second_b.name, 'B')
+ self.assertEqual(second_b.name, "B")
third_c = next(ast_nodes[2].infer())
self.assertIsInstance(third_c, Instance)
- self.assertEqual(third_c.name, 'A')
+ self.assertEqual(third_c.name, "A")
def test_metaclass_subclasses_arguments_are_classes_not_instances(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(type):
def test(cls):
return cls
@@ -3540,20 +3724,23 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
pass
B.test() #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.ClassDef)
- self.assertEqual(inferred.name, 'B')
+ self.assertEqual(inferred.name, "B")
def test_infer_cls_in_class_methods(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class A(type):
def __call__(cls):
cls #@
class B(object):
def __call__(cls):
cls #@
- ''')
+ """
+ )
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, nodes.ClassDef)
second = next(ast_nodes[1].infer())
@@ -3561,26 +3748,30 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
@unittest.expectedFailure
def test_metaclass_arguments_are_classes_not_instances(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(type):
def test(cls): return cls
A.test() #@
- ''')
+ """
+ )
# This is not supported yet
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.ClassDef)
- self.assertEqual(inferred.name, 'A')
+ self.assertEqual(inferred.name, "A")
- @test_utils.require_version(minver='3.0')
+ @test_utils.require_version(minver="3.0")
def test_metaclass_with_keyword_args(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class TestMetaKlass(type):
def __new__(mcs, name, bases, ns, kwo_arg):
return super().__new__(mcs, name, bases, ns)
class TestKlass(metaclass=TestMetaKlass, kwo_arg=42): #@
pass
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.ClassDef)
@@ -3590,7 +3781,9 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
See https://github.com/PyCQA/pylint/issues/2159
"""
- val = extract_node("""
+ val = (
+ extract_node(
+ """
class _Meta(type):
def __call__(cls):
return 1
@@ -3599,60 +3792,73 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
return 5.5
Clazz() #@
- """).inferred()[0].value
+ """
+ )
+ .inferred()[0]
+ .value
+ )
assert val == 1
def test_metaclass_custom_dunder_call_boundnode(self):
"""The boundnode should be the calling class"""
- cls = extract_node("""
+ cls = extract_node(
+ """
class _Meta(type):
def __call__(cls):
return cls
class Clazz(metaclass=_Meta):
pass
Clazz() #@
- """).inferred()[0]
+ """
+ ).inferred()[0]
assert isinstance(cls, nodes.ClassDef) and cls.name == "Clazz"
def test_delayed_attributes_without_slots(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A(object):
__slots__ = ('a', )
a = A()
a.teta = 24
a.a = 24
a #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
with self.assertRaises(exceptions.NotFoundError):
- inferred.getattr('teta')
- inferred.getattr('a')
+ inferred.getattr("teta")
+ inferred.getattr("a")
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_delayed_attributes_with_old_style_classes(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class A:
__slots__ = ('a', )
a = A()
a.teta = 42
a #@
- ''')
- next(ast_node.infer()).getattr('teta')
+ """
+ )
+ next(ast_node.infer()).getattr("teta")
def test_lambda_as_methods(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class X:
m = lambda self, arg: self.z + arg
z = 24
X().m(4) #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 28)
def test_inner_value_redefined_by_subclass(self):
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class X(object):
M = lambda self, arg: "a"
x = 24
@@ -3664,7 +3870,8 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
M = lambda self, arg: arg + 1
def blurb(self):
self.m #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 25)
@@ -3673,7 +3880,8 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
def test_inner_value_redefined_by_subclass_with_mro(self):
# This might work, but it currently doesn't due to not being able
# to reuse inference contexts.
- ast_node = extract_node('''
+ ast_node = extract_node(
+ """
class X(object):
M = lambda self, arg: arg + 1
x = 24
@@ -3688,7 +3896,8 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
M = lambda self, arg: arg + 1
def blurb(self):
self.m #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 25)
@@ -3696,20 +3905,22 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
def test_getitem_of_class_raised_type_error(self):
# Test that we wrap an AttributeInferenceError
# and reraise it as a TypeError in Class.getitem
- node = extract_node('''
+ node = extract_node(
+ """
def test():
yield
test()
- ''')
+ """
+ )
inferred = next(node.infer())
with self.assertRaises(exceptions.AstroidTypeError):
- inferred.getitem(nodes.Const('4'))
+ inferred.getitem(nodes.Const("4"))
class GetattrTest(unittest.TestCase):
-
def test_yes_when_unknown(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
from missing import Missing
getattr(1, Unknown) #@
getattr(Unknown, 'a') #@
@@ -3720,7 +3931,8 @@ class GetattrTest(unittest.TestCase):
getattr(Missing, Missing) #@
getattr('a', Missing) #@
getattr('a', Missing, Missing) #@
- ''')
+ """
+ )
for node in ast_nodes[:4]:
self.assertRaises(InferenceError, next, node.infer())
@@ -3729,30 +3941,36 @@ class GetattrTest(unittest.TestCase):
self.assertEqual(inferred, util.Uninferable, node)
def test_attrname_not_string(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
getattr(1, 1) #@
c = int
getattr(1, c) #@
- ''')
+ """
+ )
for node in ast_nodes:
self.assertRaises(InferenceError, next, node.infer())
def test_attribute_missing(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
getattr(1, 'ala') #@
getattr(int, 'ala') #@
getattr(float, 'bala') #@
getattr({}, 'portocala') #@
- ''')
+ """
+ )
for node in ast_nodes:
self.assertRaises(InferenceError, next, node.infer())
def test_default(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
getattr(1, 'ala', None) #@
getattr(int, 'bala', int) #@
getattr(int, 'bala', getattr(int, 'portocala', None)) #@
- ''')
+ """
+ )
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, nodes.Const)
self.assertIsNone(first.value)
@@ -3766,7 +3984,8 @@ class GetattrTest(unittest.TestCase):
self.assertIsNone(third.value)
def test_lookup(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class A(object):
def test(self): pass
class B(A):
@@ -3783,69 +4002,76 @@ class GetattrTest(unittest.TestCase):
class X(object):
def test(self):
getattr(self, 'test') #@
- ''')
+ """
+ )
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, BoundMethod)
- self.assertEqual(first.bound.name, 'A')
+ self.assertEqual(first.bound.name, "A")
second = next(ast_nodes[1].infer())
self.assertIsInstance(second, UnboundMethod)
self.assertIsInstance(second.parent, nodes.ClassDef)
- self.assertEqual(second.parent.name, 'A')
+ self.assertEqual(second.parent.name, "A")
third = next(ast_nodes[2].infer())
self.assertIsInstance(third, BoundMethod)
# Bound to E, but the provider is B.
- self.assertEqual(third.bound.name, 'E')
- self.assertEqual(third._proxied._proxied.parent.name, 'B')
+ self.assertEqual(third.bound.name, "E")
+ self.assertEqual(third._proxied._proxied.parent.name, "B")
fourth = next(ast_nodes[3].infer())
self.assertIsInstance(fourth, BoundMethod)
- self.assertEqual(fourth.bound.name, 'E')
- self.assertEqual(third._proxied._proxied.parent.name, 'B')
+ self.assertEqual(fourth.bound.name, "E")
+ self.assertEqual(third._proxied._proxied.parent.name, "B")
fifth = next(ast_nodes[4].infer())
self.assertIsInstance(fifth, BoundMethod)
- self.assertEqual(fifth.bound.name, 'X')
+ self.assertEqual(fifth.bound.name, "X")
def test_lambda(self):
- node = extract_node('''
+ node = extract_node(
+ """
getattr(lambda x: x, 'f') #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertEqual(inferred, util.Uninferable)
class HasattrTest(unittest.TestCase):
-
def test_inference_errors(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
from missing import Missing
hasattr(Unknown, 'ala') #@
hasattr(Missing, 'bala') #@
hasattr('portocala', Missing) #@
- ''')
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
self.assertEqual(inferred, util.Uninferable)
def test_attribute_is_missing(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class A: pass
hasattr(int, 'ala') #@
hasattr({}, 'bala') #@
hasattr(A(), 'portocala') #@
- ''')
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertFalse(inferred.value)
def test_attribute_is_not_missing(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class A(object):
def test(self): pass
class B(A):
@@ -3862,39 +4088,41 @@ class HasattrTest(unittest.TestCase):
class X(object):
def test(self):
hasattr(self, 'test') #@
- ''')
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertTrue(inferred.value)
def test_lambda(self):
- node = extract_node('''
+ node = extract_node(
+ """
hasattr(lambda x: x, 'f') #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertEqual(inferred, util.Uninferable)
class BoolOpTest(unittest.TestCase):
-
def test_bool_ops(self):
expected = [
- ('1 and 2', 2),
- ('0 and 2', 0),
- ('1 or 2', 1),
- ('0 or 2', 2),
- ('0 or 0 or 1', 1),
- ('1 and 2 and 3', 3),
- ('1 and 2 or 3', 2),
- ('1 and 0 or 3', 3),
- ('1 or 0 and 2', 1),
- ('(1 and 2) and (2 and 3)', 3),
- ('not 2 and 3', False),
- ('2 and not 3', False),
- ('not 0 and 3', 3),
- ('True and False', False),
- ('not (True or False) and True', False),
+ ("1 and 2", 2),
+ ("0 and 2", 0),
+ ("1 or 2", 1),
+ ("0 or 2", 2),
+ ("0 or 0 or 1", 1),
+ ("1 and 2 and 3", 3),
+ ("1 and 2 or 3", 2),
+ ("1 and 0 or 3", 3),
+ ("1 or 0 and 2", 1),
+ ("(1 and 2) and (2 and 3)", 3),
+ ("not 2 and 3", False),
+ ("2 and not 3", False),
+ ("not 0 and 3", 3),
+ ("True and False", False),
+ ("not (True or False) and True", False),
]
for code, expected_value in expected:
node = extract_node(code)
@@ -3902,46 +4130,55 @@ class BoolOpTest(unittest.TestCase):
self.assertEqual(inferred.value, expected_value)
def test_yes_when_unknown(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
from unknown import unknown, any, not_any
0 and unknown #@
unknown or 0 #@
any or not_any and unknown #@
- ''')
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
self.assertEqual(inferred, util.Uninferable)
def test_other_nodes(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
def test(): pass
test and 0 #@
1 and test #@
- ''')
+ """
+ )
first = next(ast_nodes[0].infer())
self.assertEqual(first.value, 0)
second = next(ast_nodes[1].infer())
self.assertIsInstance(second, nodes.FunctionDef)
- self.assertEqual(second.name, 'test')
+ self.assertEqual(second.name, "test")
class TestCallable(unittest.TestCase):
-
def test_callable(self):
expected = [
- ('callable(len)', True),
+ ("callable(len)", True),
('callable("a")', False),
- ('callable(callable)', True),
- ('callable(lambda x, y: x+y)', True),
- ('import os; __(callable(os))', False),
- ('callable(int)', True),
- ('''
+ ("callable(callable)", True),
+ ("callable(lambda x, y: x+y)", True),
+ ("import os; __(callable(os))", False),
+ ("callable(int)", True),
+ (
+ """
def test(): pass
- callable(test) #@''', True),
- ('''
+ callable(test) #@""",
+ True,
+ ),
+ (
+ """
class C1:
def meth(self): pass
- callable(C1) #@''', True),
+ callable(C1) #@""",
+ True,
+ ),
]
for code, expected_value in expected:
node = extract_node(code)
@@ -3949,7 +4186,8 @@ class TestCallable(unittest.TestCase):
self.assertEqual(inferred.value, expected_value)
def test_callable_methods(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class C:
def test(self): pass
@staticmethod
@@ -3975,48 +4213,52 @@ class TestCallable(unittest.TestCase):
property #@
D #@
D() #@
- ''')
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
self.assertTrue(inferred)
def test_inference_errors(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
from unknown import unknown
callable(unknown) #@
def test():
return unknown
callable(test()) #@
- ''')
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
self.assertEqual(inferred, util.Uninferable)
def test_not_callable(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
callable("") #@
callable(1) #@
callable(True) #@
- ''')
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
self.assertFalse(inferred.value)
class TestBool(unittest.TestCase):
-
def test_bool(self):
pairs = [
- ('bool()', False),
- ('bool(1)', True),
- ('bool(0)', False),
- ('bool([])', False),
- ('bool([1])', True),
- ('bool({})', False),
- ('bool(True)', True),
- ('bool(False)', False),
- ('bool(None)', False),
- ('from unknown import Unknown; __(bool(Unknown))', util.Uninferable),
+ ("bool()", False),
+ ("bool(1)", True),
+ ("bool(0)", False),
+ ("bool([])", False),
+ ("bool([1])", True),
+ ("bool({})", False),
+ ("bool(True)", True),
+ ("bool(False)", False),
+ ("bool(None)", False),
+ ("from unknown import Unknown; __(bool(Unknown))", util.Uninferable),
]
for code, expected in pairs:
node = extract_node(code)
@@ -4027,7 +4269,8 @@ class TestBool(unittest.TestCase):
self.assertEqual(inferred.value, expected)
def test_bool_bool_special_method(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class FalseClass:
def {method}(self):
return False
@@ -4054,37 +4297,43 @@ class TestBool(unittest.TestCase):
bool(B()) #@
bool(LambdaBoolFalse()) #@
bool(FalseBoolLen()) #@
- '''.format(method=BOOL_SPECIAL_METHOD))
+ """.format(
+ method=BOOL_SPECIAL_METHOD
+ )
+ )
expected = [True, True, False, True, False, False, False]
for node, expected_value in zip(ast_nodes, expected):
inferred = next(node.infer())
self.assertEqual(inferred.value, expected_value)
def test_bool_instance_not_callable(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
class BoolInvalid(object):
{method} = 42
class LenInvalid(object):
__len__ = "a"
bool(BoolInvalid()) #@
bool(LenInvalid()) #@
- '''.format(method=BOOL_SPECIAL_METHOD))
+ """.format(
+ method=BOOL_SPECIAL_METHOD
+ )
+ )
for node in ast_nodes:
inferred = next(node.infer())
self.assertEqual(inferred, util.Uninferable)
class TestType(unittest.TestCase):
-
def test_type(self):
pairs = [
- ('type(1)', 'int'),
- ('type(type)', 'type'),
- ('type(None)', 'NoneType'),
- ('type(object)', 'type'),
- ('type(dict())', 'dict'),
- ('type({})', 'dict'),
- ('type(frozenset())', 'frozenset'),
+ ("type(1)", "int"),
+ ("type(type)", "type"),
+ ("type(None)", "NoneType"),
+ ("type(object)", "type"),
+ ("type(dict())", "dict"),
+ ("type({})", "dict"),
+ ("type(frozenset())", "frozenset"),
]
for code, expected in pairs:
node = extract_node(code)
@@ -4094,7 +4343,6 @@ class TestType(unittest.TestCase):
class ArgumentsTest(unittest.TestCase):
-
@staticmethod
def _get_dict_value(inferred):
items = inferred.items
@@ -4106,11 +4354,27 @@ class ArgumentsTest(unittest.TestCase):
return tuple(elt.value for elt in elts)
def test_args(self):
- expected_values = [(), (1, ), (2, 3), (4, 5),
- (3, ), (), (3, 4, 5),
- (), (), (4, ), (4, 5),
- (), (3, ), (), (), (3, ), (42, )]
- ast_nodes = extract_node('''
+ expected_values = [
+ (),
+ (1,),
+ (2, 3),
+ (4, 5),
+ (3,),
+ (),
+ (3, 4, 5),
+ (),
+ (),
+ (4,),
+ (4, 5),
+ (),
+ (3,),
+ (),
+ (),
+ (3,),
+ (42,),
+ ]
+ ast_nodes = extract_node(
+ """
def func(*args):
return args
func() #@
@@ -4136,24 +4400,24 @@ class ArgumentsTest(unittest.TestCase):
func(1, 2) #@
func(1, 2, 3) #@
func(1, 2, *(42, )) #@
- ''')
+ """
+ )
for node, expected_value in zip(ast_nodes, expected_values):
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Tuple)
self.assertEqual(self._get_tuple_value(inferred), expected_value)
- @test_utils.require_version('3.5')
+ @test_utils.require_version("3.5")
def test_multiple_starred_args(self):
- expected_values = [
- (1, 2, 3),
- (1, 4, 2, 3, 5, 6, 7),
- ]
- ast_nodes = extract_node('''
+ expected_values = [(1, 2, 3), (1, 4, 2, 3, 5, 6, 7)]
+ ast_nodes = extract_node(
+ """
def func(a, b, *args):
return args
func(1, 2, *(1, ), *(2, 3)) #@
func(1, 2, *(1, ), 4, *(2, 3), 5, *(6, 7)) #@
- ''')
+ """
+ )
for node, expected_value in zip(ast_nodes, expected_values):
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Tuple)
@@ -4161,23 +4425,26 @@ class ArgumentsTest(unittest.TestCase):
def test_defaults(self):
expected_values = [42, 3, 41, 42]
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
def func(a, b, c=42, *args):
return c
func(1, 2) #@
func(1, 2, 3) #@
func(1, 2, c=41) #@
func(1, 2, 42, 41) #@
- ''')
+ """
+ )
for node, expected_value in zip(ast_nodes, expected_values):
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, expected_value)
- @test_utils.require_version('3.0')
+ @test_utils.require_version("3.0")
def test_kwonly_args(self):
expected_values = [24, 24, 42, 23, 24, 24, 54]
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
def test(*, f, b): return f
test(f=24, b=33) #@
def test(a, *, f): return f
@@ -4190,25 +4457,24 @@ class ArgumentsTest(unittest.TestCase):
test(1, 2, 3) #@
test(1, 2, 3, 4) #@
test(1, 2, 3, 4, 5, f=54) #@
- ''')
+ """
+ )
for node, expected_value in zip(ast_nodes, expected_values):
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, expected_value)
def test_kwargs(self):
- expected = [
- [('a', 1), ('b', 2), ('c', 3)],
- [('a', 1)],
- [('a', 'b')],
- ]
- ast_nodes = extract_node('''
+ expected = [[("a", 1), ("b", 2), ("c", 3)], [("a", 1)], [("a", "b")]]
+ ast_nodes = extract_node(
+ """
def test(**kwargs):
return kwargs
test(a=1, b=2, c=3) #@
test(a=1) #@
test(**{'a': 'b'}) #@
- ''')
+ """
+ )
for node, expected_value in zip(ast_nodes, expected):
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Dict)
@@ -4216,19 +4482,21 @@ class ArgumentsTest(unittest.TestCase):
self.assertEqual(value, expected_value)
def test_kwargs_and_other_named_parameters(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
def test(a=42, b=24, **kwargs):
return kwargs
test(42, 24, c=3, d=4) #@
test(49, b=24, d=4) #@
test(a=42, b=33, c=3, d=42) #@
test(a=42, **{'c':42}) #@
- ''')
+ """
+ )
expected_values = [
- [('c', 3), ('d', 4)],
- [('d', 4)],
- [('c', 3), ('d', 42)],
- [('c', 42)],
+ [("c", 3), ("d", 4)],
+ [("d", 4)],
+ [("c", 3), ("d", 42)],
+ [("c", 42)],
]
for node, expected_value in zip(ast_nodes, expected_values):
inferred = next(node.infer())
@@ -4238,7 +4506,8 @@ class ArgumentsTest(unittest.TestCase):
def test_kwargs_access_by_name(self):
expected_values = [42, 42, 42, 24]
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
def test(**kwargs):
return kwargs['f']
test(f=42) #@
@@ -4247,46 +4516,46 @@ class ArgumentsTest(unittest.TestCase):
def test(f=42, **kwargs):
return kwargs['l']
test(l=24) #@
- ''')
+ """
+ )
for ast_node, value in zip(ast_nodes, expected_values):
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.Const, inferred)
self.assertEqual(inferred.value, value)
- @test_utils.require_version('3.5')
+ @test_utils.require_version("3.5")
def test_multiple_kwargs(self):
- expected_value = [
- ('a', 1),
- ('b', 2),
- ('c', 3),
- ('d', 4),
- ('f', 42),
- ]
- ast_node = extract_node('''
+ expected_value = [("a", 1), ("b", 2), ("c", 3), ("d", 4), ("f", 42)]
+ ast_node = extract_node(
+ """
def test(**kwargs):
return kwargs
test(a=1, b=2, **{'c': 3}, **{'d': 4}, f=42) #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.Dict)
value = self._get_dict_value(inferred)
self.assertEqual(value, expected_value)
def test_kwargs_are_overridden(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
def test(f):
return f
test(f=23, **{'f': 34}) #@
def test(f=None):
return f
test(f=23, **{'f':23}) #@
- ''')
+ """
+ )
for ast_node in ast_nodes:
inferred = next(ast_node.infer())
self.assertEqual(inferred, util.Uninferable)
def test_fail_to_infer_args(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
def test(a, **kwargs): return a
test(*missing) #@
test(*object) #@
@@ -4310,23 +4579,23 @@ class ArgumentsTest(unittest.TestCase):
test(*unknown) #@
def test(*args): return args
test(*unknown) #@
- ''')
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
self.assertEqual(inferred, util.Uninferable)
class SliceTest(unittest.TestCase):
-
def test_slice(self):
ast_nodes = [
- ('[1, 2, 3][slice(None)]', [1, 2, 3]),
- ('[1, 2, 3][slice(None, None)]', [1, 2, 3]),
- ('[1, 2, 3][slice(None, None, None)]', [1, 2, 3]),
- ('[1, 2, 3][slice(1, None)]', [2, 3]),
- ('[1, 2, 3][slice(None, 1, None)]', [1]),
- ('[1, 2, 3][slice(0, 1)]', [1]),
- ('[1, 2, 3][slice(0, 3, 2)]', [1, 3]),
+ ("[1, 2, 3][slice(None)]", [1, 2, 3]),
+ ("[1, 2, 3][slice(None, None)]", [1, 2, 3]),
+ ("[1, 2, 3][slice(None, None, None)]", [1, 2, 3]),
+ ("[1, 2, 3][slice(1, None)]", [2, 3]),
+ ("[1, 2, 3][slice(None, 1, None)]", [1]),
+ ("[1, 2, 3][slice(0, 1)]", [1]),
+ ("[1, 2, 3][slice(0, 3, 2)]", [1, 3]),
]
for node, expected_value in ast_nodes:
ast_node = extract_node("__({})".format(node))
@@ -4335,7 +4604,8 @@ class SliceTest(unittest.TestCase):
self.assertEqual([elt.value for elt in inferred.elts], expected_value)
def test_slice_inference_error(self):
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
from unknown import unknown
[1, 2, 3][slice(None, unknown, unknown)] #@
[1, 2, 3][slice(None, missing, missing)] #@
@@ -4345,41 +4615,41 @@ class SliceTest(unittest.TestCase):
[1, 2, 3][slice(1, 2.0, 3.0)] #@
[1, 2, 3][slice()] #@
[1, 2, 3][slice(1, 2, 3, 4)] #@
- ''')
+ """
+ )
for node in ast_nodes:
self.assertRaises(InferenceError, next, node.infer())
def test_slice_attributes(self):
ast_nodes = [
- ('slice(2, 3, 4)', (2, 3, 4)),
- ('slice(None, None, 4)', (None, None, 4)),
- ('slice(None, 1, None)', (None, 1, None)),
+ ("slice(2, 3, 4)", (2, 3, 4)),
+ ("slice(None, None, 4)", (None, None, 4)),
+ ("slice(None, 1, None)", (None, 1, None)),
]
for code, values in ast_nodes:
lower, upper, step = values
node = extract_node(code)
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Slice)
- lower_value = next(inferred.igetattr('start'))
+ lower_value = next(inferred.igetattr("start"))
self.assertIsInstance(lower_value, nodes.Const)
self.assertEqual(lower_value.value, lower)
- higher_value = next(inferred.igetattr('stop'))
+ higher_value = next(inferred.igetattr("stop"))
self.assertIsInstance(higher_value, nodes.Const)
self.assertEqual(higher_value.value, upper)
- step_value = next(inferred.igetattr('step'))
+ step_value = next(inferred.igetattr("step"))
self.assertIsInstance(step_value, nodes.Const)
self.assertEqual(step_value.value, step)
- self.assertEqual(inferred.pytype(), '%s.slice' % BUILTINS)
+ self.assertEqual(inferred.pytype(), "%s.slice" % BUILTINS)
def test_slice_type(self):
- ast_node = extract_node('type(slice(None, None, None))')
+ ast_node = extract_node("type(slice(None, None, None))")
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.ClassDef)
- self.assertEqual(inferred.name, 'slice')
+ self.assertEqual(inferred.name, "slice")
class CallSiteTest(unittest.TestCase):
-
@staticmethod
def _call_site_from_call(call):
return arguments.CallSite.from_call(call)
@@ -4388,8 +4658,9 @@ class CallSiteTest(unittest.TestCase):
ast_node = extract_node(code)
call_site = self._call_site_from_call(ast_node)
self.assertEqual(len(call_site.positional_arguments), len(expected_args))
- self.assertEqual([arg.value for arg in call_site.positional_arguments],
- expected_args)
+ self.assertEqual(
+ [arg.value for arg in call_site.positional_arguments], expected_args
+ )
self.assertEqual(len(call_site.keyword_arguments), len(expected_keywords))
for keyword, value in expected_keywords.items():
self.assertIn(keyword, call_site.keyword_arguments)
@@ -4399,37 +4670,29 @@ class CallSiteTest(unittest.TestCase):
for pair in pairs:
self._test_call_site_pair(*pair)
- @test_utils.require_version('3.5')
+ @test_utils.require_version("3.5")
def test_call_site_starred_args(self):
pairs = [
(
"f(*(1, 2), *(2, 3), *(3, 4), **{'a':1}, **{'b': 2})",
[1, 2, 2, 3, 3, 4],
- {'a': 1, 'b': 2}
+ {"a": 1, "b": 2},
),
(
"f(1, 2, *(3, 4), 5, *(6, 7), f=24, **{'c':3})",
[1, 2, 3, 4, 5, 6, 7],
- {'f':24, 'c': 3},
+ {"f": 24, "c": 3},
),
# Too many fs passed into.
- (
- "f(f=24, **{'f':24})", [], {},
- ),
+ ("f(f=24, **{'f':24})", [], {}),
]
self._test_call_site(pairs)
def test_call_site(self):
pairs = [
- (
- "f(1, 2)", [1, 2], {}
- ),
- (
- "f(1, 2, *(1, 2))", [1, 2, 1, 2], {}
- ),
- (
- "f(a=1, b=2, c=3)", [], {'a':1, 'b':2, 'c':3}
- )
+ ("f(1, 2)", [1, 2], {}),
+ ("f(1, 2, *(1, 2))", [1, 2, 1, 2], {}),
+ ("f(a=1, b=2, c=3)", [], {"a": 1, "b": 2, "c": 3}),
]
self._test_call_site(pairs)
@@ -4440,28 +4703,26 @@ class CallSiteTest(unittest.TestCase):
self.assertEqual(call_site.has_invalid_arguments(), invalid)
def test_call_site_valid_arguments(self):
- values = [
- "f(*lala)", "f(*1)", "f(*object)",
- ]
+ values = ["f(*lala)", "f(*1)", "f(*object)"]
self._test_call_site_valid_arguments(values, invalid=True)
- values = [
- "f()", "f(*(1, ))", "f(1, 2, *(2, 3))",
- ]
+ values = ["f()", "f(*(1, ))", "f(1, 2, *(2, 3))"]
self._test_call_site_valid_arguments(values, invalid=False)
def test_duplicated_keyword_arguments(self):
ast_node = extract_node('f(f=24, **{"f": 25})')
site = self._call_site_from_call(ast_node)
- self.assertIn('f', site.duplicated_keywords)
+ self.assertIn("f", site.duplicated_keywords)
class ObjectDunderNewTest(unittest.TestCase):
def test_object_dunder_new_is_inferred_if_decorator(self):
- node = extract_node('''
+ node = extract_node(
+ """
@object.__new__
class instance(object):
pass
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, Instance)
@@ -4486,7 +4747,8 @@ def test_augassign_recursion():
def test_infer_custom_inherit_from_property():
- node = extract_node('''
+ node = extract_node(
+ """
class custom_property(property):
pass
@@ -4496,17 +4758,20 @@ def test_infer_custom_inherit_from_property():
return 1
MyClass().my_prop
- ''')
+ """
+ )
inferred = next(node.infer())
assert isinstance(inferred, nodes.Const)
assert inferred.value == 1
def test_cannot_infer_call_result_for_builtin_methods():
- node = extract_node("""
+ node = extract_node(
+ """
a = "fast"
a
- """)
+ """
+ )
inferred = next(node.infer())
lenmeth = next(inferred.igetattr("__len__"))
with pytest.raises(InferenceError):
@@ -4514,11 +4779,13 @@ def test_cannot_infer_call_result_for_builtin_methods():
def test_unpack_dicts_in_assignment():
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
a, b = {1:2, 2:3}
a #@
b #@
- ''')
+ """
+ )
first_inferred = next(ast_nodes[0].infer())
second_inferred = next(ast_nodes[1].infer())
assert isinstance(first_inferred, nodes.Const)
@@ -4528,33 +4795,40 @@ def test_unpack_dicts_in_assignment():
def test_slice_inference_in_for_loops():
- node = extract_node('''
+ node = extract_node(
+ """
for a, (c, *b) in [(1, (2, 3, 4)), (4, (5, 6))]:
b #@
- ''')
+ """
+ )
inferred = next(node.infer())
assert isinstance(inferred, nodes.List)
- assert inferred.as_string() == '[3, 4]'
+ assert inferred.as_string() == "[3, 4]"
- node = extract_node('''
+ node = extract_node(
+ """
for a, *b in [(1, 2, 3, 4)]:
b #@
- ''')
+ """
+ )
inferred = next(node.infer())
assert isinstance(inferred, nodes.List)
- assert inferred.as_string() == '[2, 3, 4]'
+ assert inferred.as_string() == "[2, 3, 4]"
- node = extract_node('''
+ node = extract_node(
+ """
for a, *b in [(1,)]:
b #@
- ''')
+ """
+ )
inferred = next(node.infer())
assert isinstance(inferred, nodes.List)
- assert inferred.as_string() == '[]'
+ assert inferred.as_string() == "[]"
def test_slice_inference_in_for_loops_not_working():
- ast_nodes = extract_node('''
+ ast_nodes = extract_node(
+ """
from unknown import Unknown
for a, *b in something:
b #@
@@ -4562,38 +4836,45 @@ def test_slice_inference_in_for_loops_not_working():
b #@
for a, *b in (1):
b #@
- ''')
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
assert inferred == util.Uninferable
def test_unpacking_starred_and_dicts_in_assignment():
- node = extract_node('''
+ node = extract_node(
+ """
a, *b = {1:2, 2:3, 3:4}
b
- ''')
+ """
+ )
inferred = next(node.infer())
assert isinstance(inferred, nodes.List)
- assert inferred.as_string() == '[2, 3]'
+ assert inferred.as_string() == "[2, 3]"
- node = extract_node('''
+ node = extract_node(
+ """
a, *b = {1:2}
b
- ''')
+ """
+ )
inferred = next(node.infer())
assert isinstance(inferred, nodes.List)
- assert inferred.as_string() == '[]'
+ assert inferred.as_string() == "[]"
def test_unpacking_starred_empty_list_in_assignment():
- node = extract_node('''
+ node = extract_node(
+ """
a, *b, c = [1, 2]
b #@
- ''')
+ """
+ )
inferred = next(node.infer())
assert isinstance(inferred, nodes.List)
- assert inferred.as_string() == '[]'
+ assert inferred.as_string() == "[]"
def test_regression_infinite_loop_decorator():
@@ -4622,7 +4903,8 @@ def test_call_on_instance_with_inherited_dunder_call_method():
See https://github.com/PyCQA/pylint/issues/2199
"""
- node = extract_node("""
+ node = extract_node(
+ """
class Base:
def __call__(self):
return self
@@ -4632,7 +4914,8 @@ def test_call_on_instance_with_inherited_dunder_call_method():
obj = Sub()
val = obj()
val #@
- """)
+ """
+ )
[val] = node.inferred()
assert isinstance(val, Instance)
assert val.name == "Sub"
@@ -4641,8 +4924,10 @@ def test_call_on_instance_with_inherited_dunder_call_method():
class TestInferencePropagation:
"""Make sure function argument values are properly
propagated to sub functions"""
+
def test_call_context_propagation(self):
- n = extract_node("""
+ n = extract_node(
+ """
def chest(a):
return a * a
def best(a, b):
@@ -4650,7 +4935,8 @@ class TestInferencePropagation:
def test(a, b, c):
return best(a, b)
test(4, 5, 6) #@
- """)
+ """
+ )
assert next(n.infer()).as_string() == "16"
def test_call_starargs_propagation(self):
@@ -4695,7 +4981,7 @@ def test_limit_inference_result_amount():
"""
result = extract_node(code).inferred()
assert len(result) == 16
- with patch('astroid.node_classes.MANAGER.max_inferable_values', 4):
+ with patch("astroid.node_classes.MANAGER.max_inferable_values", 4):
result_limited = extract_node(code).inferred()
# Can't guarantee exact size
assert len(result_limited) < 16
@@ -4717,7 +5003,8 @@ def test_attribute_mro_object_inference():
"""
Inference should only infer results from the first available method
"""
- inferred = extract_node("""
+ inferred = extract_node(
+ """
class A:
def foo(self):
return 1
@@ -4725,21 +5012,26 @@ def test_attribute_mro_object_inference():
def foo(self):
return 2
B().foo() #@
- """).inferred()
+ """
+ ).inferred()
assert len(inferred) == 1
assert inferred[0].value == 2
def test_inferred_sequence_unpacking_works():
- inferred = next(extract_node("""
+ inferred = next(
+ extract_node(
+ """
def test(*args):
return (1, *args)
test(2) #@
- """).infer())
+ """
+ ).infer()
+ )
assert isinstance(inferred, nodes.Tuple)
assert len(inferred.elts) == 2
assert [value.value for value in inferred.elts] == [1, 2]
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/tests/unittest_lookup.py b/astroid/tests/unittest_lookup.py
index ac2b3254..15b5e3bc 100644
--- a/astroid/tests/unittest_lookup.py
+++ b/astroid/tests/unittest_lookup.py
@@ -22,15 +22,14 @@ from astroid.tests import resources
class LookupTest(resources.SysPathSetup, unittest.TestCase):
-
def setUp(self):
super(LookupTest, self).setUp()
- self.module = resources.build_file('data/module.py', 'data.module')
- self.module2 = resources.build_file('data/module2.py', 'data.module2')
- self.nonregr = resources.build_file('data/nonregr.py', 'data.nonregr')
+ self.module = resources.build_file("data/module.py", "data.module")
+ self.module2 = resources.build_file("data/module2.py", "data.module2")
+ self.nonregr = resources.build_file("data/nonregr.py", "data.nonregr")
def test_limit(self):
- code = '''
+ code = """
l = [a
for a,b in list]
@@ -40,20 +39,20 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
def func():
c = 1
- '''
+ """
astroid = builder.parse(code, __name__)
# a & b
a = next(astroid.nodes_of_class(nodes.Name))
self.assertEqual(a.lineno, 2)
if sys.version_info < (3, 0):
- self.assertEqual(len(astroid.lookup('b')[1]), 1)
- self.assertEqual(len(astroid.lookup('a')[1]), 1)
- b = astroid.locals['b'][1]
+ self.assertEqual(len(astroid.lookup("b")[1]), 1)
+ self.assertEqual(len(astroid.lookup("a")[1]), 1)
+ b = astroid.locals["b"][1]
else:
- self.assertEqual(len(astroid.lookup('b')[1]), 1)
- self.assertEqual(len(astroid.lookup('a')[1]), 1)
- b = astroid.locals['b'][0]
- stmts = a.lookup('a')[1]
+ self.assertEqual(len(astroid.lookup("b")[1]), 1)
+ self.assertEqual(len(astroid.lookup("a")[1]), 1)
+ b = astroid.locals["b"][0]
+ stmts = a.lookup("a")[1]
self.assertEqual(len(stmts), 1)
self.assertEqual(b.lineno, 6)
b_infer = b.infer()
@@ -61,106 +60,117 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
self.assertEqual(b_value.value, 1)
# c
self.assertRaises(StopIteration, functools.partial(next, b_infer))
- func = astroid.locals['func'][0]
- self.assertEqual(len(func.lookup('c')[1]), 1)
+ func = astroid.locals["func"][0]
+ self.assertEqual(len(func.lookup("c")[1]), 1)
def test_module(self):
- astroid = builder.parse('pass', __name__)
+ astroid = builder.parse("pass", __name__)
# built-in objects
- none = next(astroid.ilookup('None'))
+ none = next(astroid.ilookup("None"))
self.assertIsNone(none.value)
- obj = next(astroid.ilookup('object'))
+ obj = next(astroid.ilookup("object"))
self.assertIsInstance(obj, nodes.ClassDef)
- self.assertEqual(obj.name, 'object')
- self.assertRaises(exceptions.InferenceError,
- functools.partial(next, astroid.ilookup('YOAA')))
+ self.assertEqual(obj.name, "object")
+ self.assertRaises(
+ exceptions.InferenceError, functools.partial(next, astroid.ilookup("YOAA"))
+ )
# XXX
- self.assertEqual(len(list(self.nonregr.ilookup('enumerate'))), 2)
+ self.assertEqual(len(list(self.nonregr.ilookup("enumerate"))), 2)
def test_class_ancestor_name(self):
- code = '''
+ code = """
class A:
pass
class A(A):
pass
- '''
+ """
astroid = builder.parse(code, __name__)
- cls1 = astroid.locals['A'][0]
- cls2 = astroid.locals['A'][1]
+ cls1 = astroid.locals["A"][0]
+ cls2 = astroid.locals["A"][1]
name = next(cls2.nodes_of_class(nodes.Name))
self.assertEqual(next(name.infer()), cls1)
### backport those test to inline code
def test_method(self):
- method = self.module['YOUPI']['method']
- my_dict = next(method.ilookup('MY_DICT'))
+ method = self.module["YOUPI"]["method"]
+ my_dict = next(method.ilookup("MY_DICT"))
self.assertTrue(isinstance(my_dict, nodes.Dict), my_dict)
- none = next(method.ilookup('None'))
+ none = next(method.ilookup("None"))
self.assertIsNone(none.value)
- self.assertRaises(exceptions.InferenceError,
- functools.partial(next, method.ilookup('YOAA')))
+ self.assertRaises(
+ exceptions.InferenceError, functools.partial(next, method.ilookup("YOAA"))
+ )
def test_function_argument_with_default(self):
- make_class = self.module2['make_class']
- base = next(make_class.ilookup('base'))
+ make_class = self.module2["make_class"]
+ base = next(make_class.ilookup("base"))
self.assertTrue(isinstance(base, nodes.ClassDef), base.__class__)
- self.assertEqual(base.name, 'YO')
- self.assertEqual(base.root().name, 'data.module')
+ self.assertEqual(base.name, "YO")
+ self.assertEqual(base.root().name, "data.module")
def test_class(self):
- klass = self.module['YOUPI']
- my_dict = next(klass.ilookup('MY_DICT'))
+ klass = self.module["YOUPI"]
+ my_dict = next(klass.ilookup("MY_DICT"))
self.assertIsInstance(my_dict, nodes.Dict)
- none = next(klass.ilookup('None'))
+ none = next(klass.ilookup("None"))
self.assertIsNone(none.value)
- obj = next(klass.ilookup('object'))
+ obj = next(klass.ilookup("object"))
self.assertIsInstance(obj, nodes.ClassDef)
- self.assertEqual(obj.name, 'object')
- self.assertRaises(exceptions.InferenceError,
- functools.partial(next, klass.ilookup('YOAA')))
+ self.assertEqual(obj.name, "object")
+ self.assertRaises(
+ exceptions.InferenceError, functools.partial(next, klass.ilookup("YOAA"))
+ )
def test_inner_classes(self):
- ddd = list(self.nonregr['Ccc'].ilookup('Ddd'))
- self.assertEqual(ddd[0].name, 'Ddd')
+ ddd = list(self.nonregr["Ccc"].ilookup("Ddd"))
+ self.assertEqual(ddd[0].name, "Ddd")
def test_loopvar_hiding(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
x = 10
for x in range(5):
print (x)
if x > 0:
print ('#' * x)
- """, __name__)
- xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == 'x']
+ """,
+ __name__,
+ )
+ xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"]
# inside the loop, only one possible assignment
- self.assertEqual(len(xnames[0].lookup('x')[1]), 1)
+ self.assertEqual(len(xnames[0].lookup("x")[1]), 1)
# outside the loop, two possible assignments
- self.assertEqual(len(xnames[1].lookup('x')[1]), 2)
- self.assertEqual(len(xnames[2].lookup('x')[1]), 2)
+ self.assertEqual(len(xnames[1].lookup("x")[1]), 2)
+ self.assertEqual(len(xnames[2].lookup("x")[1]), 2)
def test_list_comps(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
print ([ i for i in range(10) ])
print ([ i for i in range(10) ])
print ( list( i for i in range(10) ) )
- """, __name__)
- xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == 'i']
- self.assertEqual(len(xnames[0].lookup('i')[1]), 1)
- self.assertEqual(xnames[0].lookup('i')[1][0].lineno, 2)
- self.assertEqual(len(xnames[1].lookup('i')[1]), 1)
- self.assertEqual(xnames[1].lookup('i')[1][0].lineno, 3)
- self.assertEqual(len(xnames[2].lookup('i')[1]), 1)
- self.assertEqual(xnames[2].lookup('i')[1][0].lineno, 4)
+ """,
+ __name__,
+ )
+ xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "i"]
+ self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
+ self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 2)
+ self.assertEqual(len(xnames[1].lookup("i")[1]), 1)
+ self.assertEqual(xnames[1].lookup("i")[1][0].lineno, 3)
+ self.assertEqual(len(xnames[2].lookup("i")[1]), 1)
+ self.assertEqual(xnames[2].lookup("i")[1][0].lineno, 4)
def test_list_comp_target(self):
"""test the list comprehension target"""
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
ten = [ var for var in range(10) ]
var
- """)
+ """
+ )
var = astroid.body[1].value
if sys.version_info < (3, 0):
self.assertEqual(var.inferred(), [util.Uninferable])
@@ -168,62 +178,72 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
self.assertRaises(exceptions.NameInferenceError, var.inferred)
def test_dict_comps(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
print ({ i: j for i in range(10) for j in range(10) })
print ({ i: j for i in range(10) for j in range(10) })
- """, __name__)
- xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == 'i']
- self.assertEqual(len(xnames[0].lookup('i')[1]), 1)
- self.assertEqual(xnames[0].lookup('i')[1][0].lineno, 2)
- self.assertEqual(len(xnames[1].lookup('i')[1]), 1)
- self.assertEqual(xnames[1].lookup('i')[1][0].lineno, 3)
-
- xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == 'j']
- self.assertEqual(len(xnames[0].lookup('i')[1]), 1)
- self.assertEqual(xnames[0].lookup('i')[1][0].lineno, 2)
- self.assertEqual(len(xnames[1].lookup('i')[1]), 1)
- self.assertEqual(xnames[1].lookup('i')[1][0].lineno, 3)
+ """,
+ __name__,
+ )
+ xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "i"]
+ self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
+ self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 2)
+ self.assertEqual(len(xnames[1].lookup("i")[1]), 1)
+ self.assertEqual(xnames[1].lookup("i")[1][0].lineno, 3)
+
+ xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "j"]
+ self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
+ self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 2)
+ self.assertEqual(len(xnames[1].lookup("i")[1]), 1)
+ self.assertEqual(xnames[1].lookup("i")[1][0].lineno, 3)
def test_set_comps(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
print ({ i for i in range(10) })
print ({ i for i in range(10) })
- """, __name__)
- xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == 'i']
- self.assertEqual(len(xnames[0].lookup('i')[1]), 1)
- self.assertEqual(xnames[0].lookup('i')[1][0].lineno, 2)
- self.assertEqual(len(xnames[1].lookup('i')[1]), 1)
- self.assertEqual(xnames[1].lookup('i')[1][0].lineno, 3)
+ """,
+ __name__,
+ )
+ xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "i"]
+ self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
+ self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 2)
+ self.assertEqual(len(xnames[1].lookup("i")[1]), 1)
+ self.assertEqual(xnames[1].lookup("i")[1][0].lineno, 3)
def test_set_comp_closure(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
ten = { var for var in range(10) }
var
- """)
+ """
+ )
var = astroid.body[1].value
self.assertRaises(exceptions.NameInferenceError, var.inferred)
def test_generator_attributes(self):
- tree = builder.parse("""
+ tree = builder.parse(
+ """
def count():
"test"
yield 0
iterer = count()
num = iterer.next()
- """)
+ """
+ )
next_node = tree.body[2].value.func
gener = next_node.expr.inferred()[0]
if sys.version_info < (3, 0):
- self.assertIsInstance(gener.getattr('next')[0], nodes.FunctionDef)
+ self.assertIsInstance(gener.getattr("next")[0], nodes.FunctionDef)
else:
- self.assertIsInstance(gener.getattr('__next__')[0], nodes.FunctionDef)
- self.assertIsInstance(gener.getattr('send')[0], nodes.FunctionDef)
- self.assertIsInstance(gener.getattr('throw')[0], nodes.FunctionDef)
- self.assertIsInstance(gener.getattr('close')[0], nodes.FunctionDef)
+ self.assertIsInstance(gener.getattr("__next__")[0], nodes.FunctionDef)
+ self.assertIsInstance(gener.getattr("send")[0], nodes.FunctionDef)
+ self.assertIsInstance(gener.getattr("throw")[0], nodes.FunctionDef)
+ self.assertIsInstance(gener.getattr("close")[0], nodes.FunctionDef)
def test_explicit___name__(self):
- code = '''
+ code = """
class Pouet:
__name__ = "pouet"
p1 = Pouet()
@@ -233,36 +253,41 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
class NoName: pass
p3 = NoName()
- '''
+ """
astroid = builder.parse(code, __name__)
- p1 = next(astroid['p1'].infer())
- self.assertTrue(p1.getattr('__name__'))
- p2 = next(astroid['p2'].infer())
- self.assertTrue(p2.getattr('__name__'))
- self.assertTrue(astroid['NoName'].getattr('__name__'))
- p3 = next(astroid['p3'].infer())
- self.assertRaises(exceptions.AttributeInferenceError, p3.getattr, '__name__')
+ p1 = next(astroid["p1"].infer())
+ self.assertTrue(p1.getattr("__name__"))
+ p2 = next(astroid["p2"].infer())
+ self.assertTrue(p2.getattr("__name__"))
+ self.assertTrue(astroid["NoName"].getattr("__name__"))
+ p3 = next(astroid["p3"].infer())
+ self.assertRaises(exceptions.AttributeInferenceError, p3.getattr, "__name__")
def test_function_module_special(self):
- astroid = builder.parse('''
+ astroid = builder.parse(
+ '''
def initialize(linter):
"""initialize linter with checkers in this package """
package_load(linter, __path__[0])
- ''', 'data.__init__')
- path = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == '__path__'][0]
- self.assertEqual(len(path.lookup('__path__')[1]), 1)
+ ''',
+ "data.__init__",
+ )
+ path = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "__path__"][
+ 0
+ ]
+ self.assertEqual(len(path.lookup("__path__")[1]), 1)
def test_builtin_lookup(self):
- self.assertEqual(scoped_nodes.builtin_lookup('__dict__')[1], ())
- intstmts = scoped_nodes.builtin_lookup('int')[1]
+ self.assertEqual(scoped_nodes.builtin_lookup("__dict__")[1], ())
+ intstmts = scoped_nodes.builtin_lookup("int")[1]
self.assertEqual(len(intstmts), 1)
self.assertIsInstance(intstmts[0], nodes.ClassDef)
- self.assertEqual(intstmts[0].name, 'int')
+ self.assertEqual(intstmts[0].name, "int")
# pylint: disable=no-member; Infers two potential values
self.assertIs(intstmts[0], nodes.const_factory(1)._proxied)
def test_decorator_arguments_lookup(self):
- code = '''
+ code = """
def decorator(value):
def wrapper(function):
return function
@@ -274,7 +299,7 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
@decorator(member) #This will cause pylint to complain
def test(self):
pass
- '''
+ """
member = builder.extract_node(code, __name__).targets[0]
it = member.infer()
obj = next(it)
@@ -283,7 +308,7 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
self.assertRaises(StopIteration, functools.partial(next, it))
def test_inner_decorator_member_lookup(self):
- code = '''
+ code = """
class FileA:
def decorator(bla):
return bla
@@ -291,7 +316,7 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
@__(decorator)
def funcA():
return 4
- '''
+ """
decname = builder.extract_node(code, __name__)
it = decname.infer()
obj = next(it)
@@ -299,7 +324,7 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
self.assertRaises(StopIteration, functools.partial(next, it))
def test_static_method_lookup(self):
- code = '''
+ code = """
class FileA:
@staticmethod
def funcA():
@@ -311,15 +336,15 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
def __init__(self):
print (FileA.funcA())
- '''
+ """
astroid = builder.parse(code, __name__)
- it = astroid['Test']['__init__'].ilookup('FileA')
+ it = astroid["Test"]["__init__"].ilookup("FileA")
obj = next(it)
self.assertIsInstance(obj, nodes.ClassDef)
self.assertRaises(StopIteration, functools.partial(next, it))
def test_global_delete(self):
- code = '''
+ code = """
def run2():
f = Frobble()
@@ -331,13 +356,13 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
def run1():
f = Frobble()
- '''
+ """
astroid = builder.parse(code, __name__)
- stmts = astroid['run2'].lookup('Frobbel')[1]
+ stmts = astroid["run2"].lookup("Frobbel")[1]
self.assertEqual(len(stmts), 0)
- stmts = astroid['run1'].lookup('Frobbel')[1]
+ stmts = astroid["run1"].lookup("Frobbel")[1]
self.assertEqual(len(stmts), 0)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/tests/unittest_manager.py b/astroid/tests/unittest_manager.py
index defb1318..505bdf56 100644
--- a/astroid/tests/unittest_manager.py
+++ b/astroid/tests/unittest_manager.py
@@ -30,7 +30,7 @@ BUILTINS = six.moves.builtins.__name__
def _get_file_from_object(obj):
- if platform.python_implementation() == 'Jython':
+ if platform.python_implementation() == "Jython":
return obj.__file__.split("$py.class")[0] + ".py"
if sys.version_info >= (3, 4):
return obj.__file__
@@ -39,89 +39,95 @@ def _get_file_from_object(obj):
return obj.__file__
-class AstroidManagerTest(resources.SysPathSetup,
- resources.AstroidCacheSetupMixin,
- unittest.TestCase):
-
+class AstroidManagerTest(
+ resources.SysPathSetup, resources.AstroidCacheSetupMixin, unittest.TestCase
+):
def setUp(self):
super(AstroidManagerTest, self).setUp()
self.manager = manager.AstroidManager()
- self.manager.clear_cache(self._builtins) # take care of borg
+ self.manager.clear_cache(self._builtins) # take care of borg
def test_ast_from_file(self):
filepath = unittest.__file__
ast = self.manager.ast_from_file(filepath)
- self.assertEqual(ast.name, 'unittest')
- self.assertIn('unittest', self.manager.astroid_cache)
+ self.assertEqual(ast.name, "unittest")
+ self.assertIn("unittest", self.manager.astroid_cache)
def test_ast_from_file_cache(self):
filepath = unittest.__file__
self.manager.ast_from_file(filepath)
- ast = self.manager.ast_from_file('unhandledName', 'unittest')
- self.assertEqual(ast.name, 'unittest')
- self.assertIn('unittest', self.manager.astroid_cache)
+ ast = self.manager.ast_from_file("unhandledName", "unittest")
+ self.assertEqual(ast.name, "unittest")
+ self.assertIn("unittest", self.manager.astroid_cache)
def test_ast_from_file_astro_builder(self):
filepath = unittest.__file__
ast = self.manager.ast_from_file(filepath, None, True, True)
- self.assertEqual(ast.name, 'unittest')
- self.assertIn('unittest', self.manager.astroid_cache)
+ self.assertEqual(ast.name, "unittest")
+ self.assertIn("unittest", self.manager.astroid_cache)
def test_ast_from_file_name_astro_builder_exception(self):
- self.assertRaises(exceptions.AstroidBuildingError,
- self.manager.ast_from_file, 'unhandledName')
+ self.assertRaises(
+ exceptions.AstroidBuildingError, self.manager.ast_from_file, "unhandledName"
+ )
def test_do_not_expose_main(self):
- obj = self.manager.ast_from_module_name('__main__')
- self.assertEqual(obj.name, '__main__')
+ obj = self.manager.ast_from_module_name("__main__")
+ self.assertEqual(obj.name, "__main__")
self.assertEqual(obj.items(), [])
def test_ast_from_module_name(self):
- ast = self.manager.ast_from_module_name('unittest')
- self.assertEqual(ast.name, 'unittest')
- self.assertIn('unittest', self.manager.astroid_cache)
+ ast = self.manager.ast_from_module_name("unittest")
+ self.assertEqual(ast.name, "unittest")
+ self.assertIn("unittest", self.manager.astroid_cache)
def test_ast_from_module_name_not_python_source(self):
- ast = self.manager.ast_from_module_name('time')
- self.assertEqual(ast.name, 'time')
- self.assertIn('time', self.manager.astroid_cache)
+ ast = self.manager.ast_from_module_name("time")
+ self.assertEqual(ast.name, "time")
+ self.assertIn("time", self.manager.astroid_cache)
self.assertEqual(ast.pure_python, False)
def test_ast_from_module_name_astro_builder_exception(self):
- self.assertRaises(exceptions.AstroidBuildingError,
- self.manager.ast_from_module_name,
- 'unhandledModule')
+ self.assertRaises(
+ exceptions.AstroidBuildingError,
+ self.manager.ast_from_module_name,
+ "unhandledModule",
+ )
def _test_ast_from_old_namespace_package_protocol(self, root):
origpath = sys.path[:]
- paths = [resources.find('data/path_{}_{}'.format(root, index))
- for index in range(1, 4)]
+ paths = [
+ resources.find("data/path_{}_{}".format(root, index))
+ for index in range(1, 4)
+ ]
sys.path.extend(paths)
try:
- for name in ('foo', 'bar', 'baz'):
- module = self.manager.ast_from_module_name('package.' + name)
+ for name in ("foo", "bar", "baz"):
+ module = self.manager.ast_from_module_name("package." + name)
self.assertIsInstance(module, astroid.Module)
finally:
sys.path = origpath
def test_ast_from_namespace_pkgutil(self):
- self._test_ast_from_old_namespace_package_protocol('pkgutil')
+ self._test_ast_from_old_namespace_package_protocol("pkgutil")
def test_ast_from_namespace_pkg_resources(self):
- self._test_ast_from_old_namespace_package_protocol('pkg_resources')
+ self._test_ast_from_old_namespace_package_protocol("pkg_resources")
- @unittest.skipUnless(sys.version_info[:2] >= (3, 4), "Needs PEP 420 namespace protocol")
+ @unittest.skipUnless(
+ sys.version_info[:2] >= (3, 4), "Needs PEP 420 namespace protocol"
+ )
def test_implicit_namespace_package(self):
- data_dir = os.path.dirname(resources.find('data/namespace_pep_420'))
- contribute = os.path.join(data_dir, 'contribute_to_namespace')
+ data_dir = os.path.dirname(resources.find("data/namespace_pep_420"))
+ contribute = os.path.join(data_dir, "contribute_to_namespace")
for value in (data_dir, contribute):
sys.path.insert(0, value)
try:
- module = self.manager.ast_from_module_name('namespace_pep_420.module')
+ module = self.manager.ast_from_module_name("namespace_pep_420.module")
self.assertIsInstance(module, astroid.Module)
- self.assertEqual(module.name, 'namespace_pep_420.module')
- var = next(module.igetattr('var'))
+ self.assertEqual(module.name, "namespace_pep_420.module")
+ var = next(module.igetattr("var"))
self.assertIsInstance(var, astroid.Const)
self.assertEqual(var.value, 42)
finally:
@@ -129,154 +135,161 @@ class AstroidManagerTest(resources.SysPathSetup,
sys.path.pop(0)
def test_namespace_package_pth_support(self):
- pth = 'foogle_fax-0.12.5-py2.7-nspkg.pth'
+ pth = "foogle_fax-0.12.5-py2.7-nspkg.pth"
site.addpackage(resources.RESOURCE_PATH, pth, [])
- pkg_resources._namespace_packages['foogle'] = []
+ pkg_resources._namespace_packages["foogle"] = []
try:
- module = self.manager.ast_from_module_name('foogle.fax')
- submodule = next(module.igetattr('a'))
- value = next(submodule.igetattr('x'))
+ module = self.manager.ast_from_module_name("foogle.fax")
+ submodule = next(module.igetattr("a"))
+ value = next(submodule.igetattr("x"))
self.assertIsInstance(value, astroid.Const)
with self.assertRaises(exceptions.AstroidImportError):
- self.manager.ast_from_module_name('foogle.moogle')
+ self.manager.ast_from_module_name("foogle.moogle")
finally:
- del pkg_resources._namespace_packages['foogle']
- sys.modules.pop('foogle')
+ del pkg_resources._namespace_packages["foogle"]
+ sys.modules.pop("foogle")
def test_nested_namespace_import(self):
- pth = 'foogle_fax-0.12.5-py2.7-nspkg.pth'
+ pth = "foogle_fax-0.12.5-py2.7-nspkg.pth"
site.addpackage(resources.RESOURCE_PATH, pth, [])
- pkg_resources._namespace_packages['foogle'] = ['foogle.crank']
- pkg_resources._namespace_packages['foogle.crank'] = []
+ pkg_resources._namespace_packages["foogle"] = ["foogle.crank"]
+ pkg_resources._namespace_packages["foogle.crank"] = []
try:
- self.manager.ast_from_module_name('foogle.crank')
+ self.manager.ast_from_module_name("foogle.crank")
finally:
- del pkg_resources._namespace_packages['foogle']
- sys.modules.pop('foogle')
+ del pkg_resources._namespace_packages["foogle"]
+ sys.modules.pop("foogle")
def test_namespace_and_file_mismatch(self):
filepath = unittest.__file__
ast = self.manager.ast_from_file(filepath)
- self.assertEqual(ast.name, 'unittest')
- pth = 'foogle_fax-0.12.5-py2.7-nspkg.pth'
+ self.assertEqual(ast.name, "unittest")
+ pth = "foogle_fax-0.12.5-py2.7-nspkg.pth"
site.addpackage(resources.RESOURCE_PATH, pth, [])
- pkg_resources._namespace_packages['foogle'] = []
+ pkg_resources._namespace_packages["foogle"] = []
try:
with self.assertRaises(exceptions.AstroidImportError):
- self.manager.ast_from_module_name('unittest.foogle.fax')
+ self.manager.ast_from_module_name("unittest.foogle.fax")
finally:
- del pkg_resources._namespace_packages['foogle']
- sys.modules.pop('foogle')
+ del pkg_resources._namespace_packages["foogle"]
+ sys.modules.pop("foogle")
def _test_ast_from_zip(self, archive):
origpath = sys.path[:]
- sys.modules.pop('mypypa', None)
+ sys.modules.pop("mypypa", None)
archive_path = resources.find(archive)
sys.path.insert(0, archive_path)
try:
- module = self.manager.ast_from_module_name('mypypa')
- self.assertEqual(module.name, 'mypypa')
- end = os.path.join(archive, 'mypypa')
- self.assertTrue(module.file.endswith(end),
- "%s doesn't endswith %s" % (module.file, end))
+ module = self.manager.ast_from_module_name("mypypa")
+ self.assertEqual(module.name, "mypypa")
+ end = os.path.join(archive, "mypypa")
+ self.assertTrue(
+ module.file.endswith(end), "%s doesn't endswith %s" % (module.file, end)
+ )
finally:
# remove the module, else after importing egg, we don't get the zip
- if 'mypypa' in self.manager.astroid_cache:
- del self.manager.astroid_cache['mypypa']
- del self.manager._mod_file_cache[('mypypa', None)]
+ if "mypypa" in self.manager.astroid_cache:
+ del self.manager.astroid_cache["mypypa"]
+ del self.manager._mod_file_cache[("mypypa", None)]
if archive_path in sys.path_importer_cache:
del sys.path_importer_cache[archive_path]
sys.path = origpath
def test_ast_from_module_name_egg(self):
self._test_ast_from_zip(
- os.path.sep.join(['data', os.path.normcase('MyPyPa-0.1.0-py2.5.egg')])
+ os.path.sep.join(["data", os.path.normcase("MyPyPa-0.1.0-py2.5.egg")])
)
def test_ast_from_module_name_zip(self):
self._test_ast_from_zip(
- os.path.sep.join(['data', os.path.normcase('MyPyPa-0.1.0-py2.5.zip')])
+ os.path.sep.join(["data", os.path.normcase("MyPyPa-0.1.0-py2.5.zip")])
)
def test_zip_import_data(self):
"""check if zip_import_data works"""
- filepath = resources.find('data/MyPyPa-0.1.0-py2.5.zip/mypypa')
+ filepath = resources.find("data/MyPyPa-0.1.0-py2.5.zip/mypypa")
ast = self.manager.zip_import_data(filepath)
- self.assertEqual(ast.name, 'mypypa')
+ self.assertEqual(ast.name, "mypypa")
def test_zip_import_data_without_zipimport(self):
"""check if zip_import_data return None without zipimport"""
- self.assertEqual(self.manager.zip_import_data('path'), None)
+ self.assertEqual(self.manager.zip_import_data("path"), None)
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("unittest", None).location,
+ )
def test_file_from_module_name_astro_building_exception(self):
"""check if the method raises an exception with a wrong module name"""
- self.assertRaises(exceptions.AstroidBuildingError,
- self.manager.file_from_module_name, 'unhandledModule', None)
+ self.assertRaises(
+ exceptions.AstroidBuildingError,
+ self.manager.file_from_module_name,
+ "unhandledModule",
+ None,
+ )
def test_ast_from_module(self):
ast = self.manager.ast_from_module(unittest)
self.assertEqual(ast.pure_python, True)
import time
+
ast = self.manager.ast_from_module(time)
self.assertEqual(ast.pure_python, False)
def test_ast_from_module_cache(self):
"""check if the module is in the cache manager"""
ast = self.manager.ast_from_module(unittest)
- self.assertEqual(ast.name, 'unittest')
- self.assertIn('unittest', self.manager.astroid_cache)
+ self.assertEqual(ast.name, "unittest")
+ self.assertIn("unittest", self.manager.astroid_cache)
def test_ast_from_class(self):
ast = self.manager.ast_from_class(int)
- self.assertEqual(ast.name, 'int')
+ self.assertEqual(ast.name, "int")
self.assertEqual(ast.parent.frame().name, BUILTINS)
ast = self.manager.ast_from_class(object)
- self.assertEqual(ast.name, 'object')
+ self.assertEqual(ast.name, "object")
self.assertEqual(ast.parent.frame().name, BUILTINS)
- self.assertIn('__setattr__', ast)
+ self.assertIn("__setattr__", ast)
def test_ast_from_class_with_module(self):
"""check if the method works with the module name"""
ast = self.manager.ast_from_class(int, int.__module__)
- self.assertEqual(ast.name, 'int')
+ self.assertEqual(ast.name, "int")
self.assertEqual(ast.parent.frame().name, BUILTINS)
ast = self.manager.ast_from_class(object, object.__module__)
- self.assertEqual(ast.name, 'object')
+ self.assertEqual(ast.name, "object")
self.assertEqual(ast.parent.frame().name, BUILTINS)
- self.assertIn('__setattr__', ast)
+ self.assertIn("__setattr__", ast)
def test_ast_from_class_attr_error(self):
"""give a wrong class at the ast_from_class method"""
- self.assertRaises(exceptions.AstroidBuildingError,
- self.manager.ast_from_class, None)
+ self.assertRaises(
+ exceptions.AstroidBuildingError, self.manager.ast_from_class, None
+ )
def testFailedImportHooks(self):
def hook(modname):
- if modname == 'foo.bar':
+ if modname == "foo.bar":
return unittest
raise exceptions.AstroidBuildingError()
with self.assertRaises(exceptions.AstroidBuildingError):
- self.manager.ast_from_module_name('foo.bar')
+ self.manager.ast_from_module_name("foo.bar")
self.manager.register_failed_import_hook(hook)
- self.assertEqual(unittest, self.manager.ast_from_module_name('foo.bar'))
+ self.assertEqual(unittest, self.manager.ast_from_module_name("foo.bar"))
with self.assertRaises(exceptions.AstroidBuildingError):
- self.manager.ast_from_module_name('foo.bar.baz')
+ self.manager.ast_from_module_name("foo.bar.baz")
del self.manager._failed_import_hooks[0]
class BorgAstroidManagerTC(unittest.TestCase):
-
def test_borg(self):
"""test that the AstroidManager is really a borg, i.e. that two different
instances has same cache"""
@@ -288,5 +301,5 @@ class BorgAstroidManagerTC(unittest.TestCase):
self.assertIs(built, second_built)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/tests/unittest_modutils.py b/astroid/tests/unittest_modutils.py
index 36a980e8..eb569935 100644
--- a/astroid/tests/unittest_modutils.py
+++ b/astroid/tests/unittest_modutils.py
@@ -37,67 +37,78 @@ class ModuleFileTest(unittest.TestCase):
def tearDown(self):
for k in list(sys.path_importer_cache):
- if 'MyPyPa' in k:
+ if "MyPyPa" in k:
del sys.path_importer_cache[k]
def test_find_zipped_module(self):
found_spec = spec.find_spec(
- [self.package], [resources.find('data/MyPyPa-0.1.0-py2.5.zip')])
- self.assertEqual(found_spec.type,
- spec.ModuleType.PY_ZIPMODULE)
- self.assertEqual(found_spec.location.split(os.sep)[-3:],
- ["data", "MyPyPa-0.1.0-py2.5.zip", self.package])
+ [self.package], [resources.find("data/MyPyPa-0.1.0-py2.5.zip")]
+ )
+ self.assertEqual(found_spec.type, spec.ModuleType.PY_ZIPMODULE)
+ self.assertEqual(
+ found_spec.location.split(os.sep)[-3:],
+ ["data", "MyPyPa-0.1.0-py2.5.zip", self.package],
+ )
def test_find_egg_module(self):
found_spec = spec.find_spec(
- [self.package], [resources.find('data/MyPyPa-0.1.0-py2.5.egg')])
- self.assertEqual(found_spec.type,
- spec.ModuleType.PY_ZIPMODULE)
- self.assertEqual(found_spec.location.split(os.sep)[-3:],
- ["data", "MyPyPa-0.1.0-py2.5.egg", self.package])
+ [self.package], [resources.find("data/MyPyPa-0.1.0-py2.5.egg")]
+ )
+ self.assertEqual(found_spec.type, spec.ModuleType.PY_ZIPMODULE)
+ self.assertEqual(
+ found_spec.location.split(os.sep)[-3:],
+ ["data", "MyPyPa-0.1.0-py2.5.egg", self.package],
+ )
class LoadModuleFromNameTest(unittest.TestCase):
""" load a python module from it's name """
def test_knownValues_load_module_from_name_1(self):
- self.assertEqual(modutils.load_module_from_name('sys'), sys)
+ self.assertEqual(modutils.load_module_from_name("sys"), sys)
def test_knownValues_load_module_from_name_2(self):
- self.assertEqual(modutils.load_module_from_name('os.path'), os.path)
+ self.assertEqual(modutils.load_module_from_name("os.path"), os.path)
def test_raise_load_module_from_name_1(self):
- self.assertRaises(ImportError,
- modutils.load_module_from_name, 'os.path', use_sys=0)
+ self.assertRaises(
+ ImportError, modutils.load_module_from_name, "os.path", use_sys=0
+ )
class GetModulePartTest(unittest.TestCase):
"""given a dotted name return the module part of the name"""
def test_knownValues_get_module_part_1(self):
- self.assertEqual(modutils.get_module_part('astroid.modutils'),
- 'astroid.modutils')
+ self.assertEqual(
+ modutils.get_module_part("astroid.modutils"), "astroid.modutils"
+ )
def test_knownValues_get_module_part_2(self):
- self.assertEqual(modutils.get_module_part('astroid.modutils.get_module_part'),
- 'astroid.modutils')
+ self.assertEqual(
+ modutils.get_module_part("astroid.modutils.get_module_part"),
+ "astroid.modutils",
+ )
def test_knownValues_get_module_part_3(self):
"""relative import from given file"""
- self.assertEqual(modutils.get_module_part('node_classes.AssName',
- modutils.__file__), 'node_classes')
+ self.assertEqual(
+ modutils.get_module_part("node_classes.AssName", modutils.__file__),
+ "node_classes",
+ )
def test_knownValues_get_compiled_module_part(self):
- self.assertEqual(modutils.get_module_part('math.log10'), 'math')
- self.assertEqual(modutils.get_module_part('math.log10', __file__), 'math')
+ self.assertEqual(modutils.get_module_part("math.log10"), "math")
+ self.assertEqual(modutils.get_module_part("math.log10", __file__), "math")
def test_knownValues_get_builtin_module_part(self):
- self.assertEqual(modutils.get_module_part('sys.path'), 'sys')
- self.assertEqual(modutils.get_module_part('sys.path', '__file__'), 'sys')
+ self.assertEqual(modutils.get_module_part("sys.path"), "sys")
+ self.assertEqual(modutils.get_module_part("sys.path", "__file__"), "sys")
def test_get_module_part_exception(self):
- self.assertRaises(ImportError, modutils.get_module_part, 'unknown.module',
- modutils.__file__)
+ self.assertRaises(
+ ImportError, modutils.get_module_part, "unknown.module", modutils.__file__
+ )
class ModPathFromFileTest(unittest.TestCase):
@@ -105,45 +116,52 @@ class ModPathFromFileTest(unittest.TestCase):
def test_knownValues_modpath_from_file_1(self):
from xml.etree import ElementTree
- self.assertEqual(modutils.modpath_from_file(ElementTree.__file__),
- ['xml', 'etree', 'ElementTree'])
+
+ self.assertEqual(
+ modutils.modpath_from_file(ElementTree.__file__),
+ ["xml", "etree", "ElementTree"],
+ )
def test_knownValues_modpath_from_file_2(self):
- self.assertEqual(modutils.modpath_from_file('unittest_modutils.py',
- {os.getcwd(): 'arbitrary.pkg'}),
- ['arbitrary', 'pkg', 'unittest_modutils'])
+ self.assertEqual(
+ modutils.modpath_from_file(
+ "unittest_modutils.py", {os.getcwd(): "arbitrary.pkg"}
+ ),
+ ["arbitrary", "pkg", "unittest_modutils"],
+ )
def test_raise_modpath_from_file_Exception(self):
- self.assertRaises(Exception, modutils.modpath_from_file, '/turlututu')
+ self.assertRaises(Exception, modutils.modpath_from_file, "/turlututu")
def test_import_symlink_with_source_outside_of_path(self):
with tempfile.NamedTemporaryFile() as tmpfile:
- linked_file_name = 'symlinked_file.py'
+ linked_file_name = "symlinked_file.py"
try:
os.symlink(tmpfile.name, linked_file_name)
- self.assertEqual(modutils.modpath_from_file(linked_file_name),
- ['symlinked_file'])
+ self.assertEqual(
+ modutils.modpath_from_file(linked_file_name), ["symlinked_file"]
+ )
finally:
os.remove(linked_file_name)
def test_import_symlink_both_outside_of_path(self):
with tempfile.NamedTemporaryFile() as tmpfile:
- linked_file_name = os.path.join(tempfile.gettempdir(),
- 'symlinked_file.py')
+ linked_file_name = os.path.join(tempfile.gettempdir(), "symlinked_file.py")
try:
os.symlink(tmpfile.name, linked_file_name)
- self.assertRaises(ImportError,
- modutils.modpath_from_file, linked_file_name)
+ self.assertRaises(
+ ImportError, modutils.modpath_from_file, linked_file_name
+ )
finally:
os.remove(linked_file_name)
def test_load_from_module_symlink_on_symlinked_paths_in_syspath(self):
# constants
tmp = tempfile.gettempdir()
- deployment_path = os.path.join(tmp, 'deployment')
- path_to_include = os.path.join(tmp, 'path_to_include')
- real_secret_path = os.path.join(tmp, 'secret.py')
- symlink_secret_path = os.path.join(path_to_include, 'secret.py')
+ deployment_path = os.path.join(tmp, "deployment")
+ path_to_include = os.path.join(tmp, "path_to_include")
+ real_secret_path = os.path.join(tmp, "secret.py")
+ symlink_secret_path = os.path.join(path_to_include, "secret.py")
# setup double symlink
# /tmp/deployment
@@ -164,16 +182,13 @@ class ModPathFromFileTest(unittest.TestCase):
self.addCleanup(sys.path.pop)
# this should be equivalent to: import secret
- self.assertEqual(
- modutils.modpath_from_file(symlink_secret_path),
- ['secret'])
+ self.assertEqual(modutils.modpath_from_file(symlink_secret_path), ["secret"])
class LoadModuleFromPathTest(resources.SysPathSetup, unittest.TestCase):
-
def test_do_not_load_twice(self):
- modutils.load_module_from_modpath(['data', 'lmfp', 'foo'])
- modutils.load_module_from_modpath(['data', 'lmfp'])
+ modutils.load_module_from_modpath(["data", "lmfp", "foo"])
+ modutils.load_module_from_modpath(["data", "lmfp"])
# pylint: disable=no-member; just-once is added by a test file dynamically.
self.assertEqual(len(sys.just_once), 1)
del sys.just_once
@@ -186,19 +201,21 @@ class FileFromModPathTest(resources.SysPathSetup, unittest.TestCase):
def test_site_packages(self):
filename = _get_file_from_object(modutils)
- result = modutils.file_from_modpath(['astroid', 'modutils'])
+ result = modutils.file_from_modpath(["astroid", "modutils"])
self.assertEqual(os.path.realpath(result), os.path.realpath(filename))
def test_std_lib(self):
- path = modutils.file_from_modpath(['os', 'path']).replace('.pyc', '.py')
- self.assertEqual(os.path.realpath(path),
- os.path.realpath(os.path.__file__.replace('.pyc', '.py')))
+ path = modutils.file_from_modpath(["os", "path"]).replace(".pyc", ".py")
+ self.assertEqual(
+ os.path.realpath(path),
+ os.path.realpath(os.path.__file__.replace(".pyc", ".py")),
+ )
def test_builtin(self):
- self.assertIsNone(modutils.file_from_modpath(['sys']))
+ self.assertIsNone(modutils.file_from_modpath(["sys"]))
def test_unexisting(self):
- self.assertRaises(ImportError, modutils.file_from_modpath, ['turlututu'])
+ self.assertRaises(ImportError, modutils.file_from_modpath, ["turlututu"])
def test_unicode_in_package_init(self):
# file_from_modpath should not crash when reading an __init__
@@ -207,14 +224,14 @@ class FileFromModPathTest(resources.SysPathSetup, unittest.TestCase):
class GetSourceFileTest(unittest.TestCase):
-
def test(self):
filename = _get_file_from_object(os.path)
- self.assertEqual(modutils.get_source_file(os.path.__file__),
- os.path.normpath(filename))
+ self.assertEqual(
+ modutils.get_source_file(os.path.__file__), os.path.normpath(filename)
+ )
def test_raise(self):
- self.assertRaises(modutils.NoSourceFile, modutils.get_source_file, 'whatever')
+ self.assertRaises(modutils.NoSourceFile, modutils.get_source_file, "whatever")
class StandardLibModuleTest(resources.SysPathSetup, unittest.TestCase):
@@ -226,97 +243,98 @@ class StandardLibModuleTest(resources.SysPathSetup, unittest.TestCase):
def test_datetime(self):
# This is an interesting example, since datetime, on pypy,
# is under lib_pypy, rather than the usual Lib directory.
- self.assertTrue(modutils.is_standard_module('datetime'))
+ self.assertTrue(modutils.is_standard_module("datetime"))
def test_builtins(self):
if sys.version_info < (3, 0):
- self.assertTrue(modutils.is_standard_module('__builtin__'))
- self.assertFalse(modutils.is_standard_module('builtins'))
+ self.assertTrue(modutils.is_standard_module("__builtin__"))
+ self.assertFalse(modutils.is_standard_module("builtins"))
else:
- self.assertFalse(modutils.is_standard_module('__builtin__'))
- self.assertTrue(modutils.is_standard_module('builtins'))
+ self.assertFalse(modutils.is_standard_module("__builtin__"))
+ self.assertTrue(modutils.is_standard_module("builtins"))
def test_builtin(self):
- self.assertTrue(modutils.is_standard_module('sys'))
- self.assertTrue(modutils.is_standard_module('marshal'))
+ self.assertTrue(modutils.is_standard_module("sys"))
+ self.assertTrue(modutils.is_standard_module("marshal"))
def test_nonstandard(self):
- self.assertFalse(modutils.is_standard_module('astroid'))
+ self.assertFalse(modutils.is_standard_module("astroid"))
def test_unknown(self):
- self.assertFalse(modutils.is_standard_module('unknown'))
+ self.assertFalse(modutils.is_standard_module("unknown"))
def test_4(self):
- self.assertTrue(modutils.is_standard_module('hashlib'))
- self.assertTrue(modutils.is_standard_module('pickle'))
- self.assertTrue(modutils.is_standard_module('email'))
- self.assertEqual(modutils.is_standard_module('io'),
- sys.version_info >= (2, 6))
- self.assertEqual(modutils.is_standard_module('StringIO'),
- sys.version_info < (3, 0))
- self.assertTrue(modutils.is_standard_module('unicodedata'))
+ self.assertTrue(modutils.is_standard_module("hashlib"))
+ self.assertTrue(modutils.is_standard_module("pickle"))
+ self.assertTrue(modutils.is_standard_module("email"))
+ self.assertEqual(modutils.is_standard_module("io"), sys.version_info >= (2, 6))
+ self.assertEqual(
+ modutils.is_standard_module("StringIO"), sys.version_info < (3, 0)
+ )
+ self.assertTrue(modutils.is_standard_module("unicodedata"))
def test_custom_path(self):
- datadir = resources.find('')
+ datadir = resources.find("")
if datadir.startswith(modutils.EXT_LIB_DIR):
- self.skipTest('known breakage of is_standard_module on installed package')
+ self.skipTest("known breakage of is_standard_module on installed package")
- self.assertTrue(modutils.is_standard_module('data.module', (datadir,)))
- self.assertTrue(modutils.is_standard_module('data.module', (os.path.abspath(datadir),)))
+ self.assertTrue(modutils.is_standard_module("data.module", (datadir,)))
+ self.assertTrue(
+ modutils.is_standard_module("data.module", (os.path.abspath(datadir),))
+ )
def test_failing_edge_cases(self):
# using a subpackage/submodule path as std_path argument
- self.assertFalse(modutils.is_standard_module('xml.etree', etree.__path__))
+ self.assertFalse(modutils.is_standard_module("xml.etree", etree.__path__))
# using a module + object name as modname argument
- self.assertTrue(modutils.is_standard_module('sys.path'))
+ self.assertTrue(modutils.is_standard_module("sys.path"))
# this is because only the first package/module is considered
- self.assertTrue(modutils.is_standard_module('sys.whatever'))
- self.assertFalse(modutils.is_standard_module('xml.whatever', etree.__path__))
+ self.assertTrue(modutils.is_standard_module("sys.whatever"))
+ self.assertFalse(modutils.is_standard_module("xml.whatever", etree.__path__))
class IsRelativeTest(unittest.TestCase):
-
def test_knownValues_is_relative_1(self):
- self.assertTrue(modutils.is_relative('utils', email.__path__[0]))
+ self.assertTrue(modutils.is_relative("utils", email.__path__[0]))
def test_knownValues_is_relative_2(self):
- self.assertTrue(modutils.is_relative('ElementPath',
- etree.ElementTree.__file__))
+ self.assertTrue(modutils.is_relative("ElementPath", etree.ElementTree.__file__))
def test_knownValues_is_relative_3(self):
- self.assertFalse(modutils.is_relative('astroid', astroid.__path__[0]))
+ self.assertFalse(modutils.is_relative("astroid", astroid.__path__[0]))
class GetModuleFilesTest(unittest.TestCase):
-
def test_get_module_files_1(self):
- package = resources.find('data/find_test')
+ package = resources.find("data/find_test")
modules = set(modutils.get_module_files(package, []))
- expected = ['__init__.py', 'module.py', 'module2.py',
- 'noendingnewline.py', 'nonregr.py']
- self.assertEqual(modules,
- {os.path.join(package, x) for x in expected})
+ expected = [
+ "__init__.py",
+ "module.py",
+ "module2.py",
+ "noendingnewline.py",
+ "nonregr.py",
+ ]
+ self.assertEqual(modules, {os.path.join(package, x) for x in expected})
def test_get_all_files(self):
"""test that list_all returns all Python files from given location
"""
- non_package = resources.find('data/notamodule')
+ non_package = resources.find("data/notamodule")
modules = modutils.get_module_files(non_package, [], list_all=True)
- self.assertEqual(
- modules,
- [os.path.join(non_package, 'file.py')],
- )
+ self.assertEqual(modules, [os.path.join(non_package, "file.py")])
def test_load_module_set_attribute(self):
import xml.etree.ElementTree
import xml
+
del xml.etree.ElementTree
- del sys.modules['xml.etree.ElementTree']
- m = modutils.load_module_from_modpath(['xml', 'etree', 'ElementTree'])
- self.assertTrue(hasattr(xml, 'etree'))
- self.assertTrue(hasattr(xml.etree, 'ElementTree'))
+ del sys.modules["xml.etree.ElementTree"]
+ m = modutils.load_module_from_modpath(["xml", "etree", "ElementTree"])
+ self.assertTrue(hasattr(xml, "etree"))
+ self.assertTrue(hasattr(xml.etree, "ElementTree"))
self.assertTrue(m is xml.etree.ElementTree)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/tests/unittest_nodes.py b/astroid/tests/unittest_nodes.py
index e9e2d384..56b195c2 100644
--- a/astroid/tests/unittest_nodes.py
+++ b/astroid/tests/unittest_nodes.py
@@ -44,89 +44,95 @@ abuilder = builder.AstroidBuilder()
BUILTINS = six.moves.builtins.__name__
try:
import typed_ast # pylint: disable=unused-import
+
HAS_TYPED_AST = True
except ImportError:
HAS_TYPED_AST = False
class AsStringTest(resources.SysPathSetup, unittest.TestCase):
-
def test_tuple_as_string(self):
def build(string):
return abuilder.string_build(string).body[0].value
- self.assertEqual(build('1,').as_string(), '(1, )')
- self.assertEqual(build('1, 2, 3').as_string(), '(1, 2, 3)')
- self.assertEqual(build('(1, )').as_string(), '(1, )')
- self.assertEqual(build('1, 2, 3').as_string(), '(1, 2, 3)')
+ self.assertEqual(build("1,").as_string(), "(1, )")
+ self.assertEqual(build("1, 2, 3").as_string(), "(1, 2, 3)")
+ self.assertEqual(build("(1, )").as_string(), "(1, )")
+ self.assertEqual(build("1, 2, 3").as_string(), "(1, 2, 3)")
- @test_utils.require_version(minver='3.0')
+ @test_utils.require_version(minver="3.0")
def test_func_signature_issue_185(self):
- code = textwrap.dedent('''
+ code = textwrap.dedent(
+ """
def test(a, b, c=42, *, x=42, **kwargs):
print(a, b, c, args)
- ''')
+ """
+ )
node = parse(code)
self.assertEqual(node.as_string().strip(), code.strip())
def test_as_string_for_list_containing_uninferable(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
def foo():
bar = [arg] * 1
- ''')
+ """
+ )
binop = node.body[0].value
inferred = next(binop.infer())
- self.assertEqual(inferred.as_string(), '[Uninferable]')
- self.assertEqual(binop.as_string(), '[arg] * 1')
+ self.assertEqual(inferred.as_string(), "[Uninferable]")
+ self.assertEqual(binop.as_string(), "[arg] * 1")
def test_frozenset_as_string(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
frozenset((1, 2, 3)) #@
frozenset({1, 2, 3}) #@
frozenset([1, 2, 3,]) #@
frozenset(None) #@
frozenset(1) #@
- ''')
+ """
+ )
ast_nodes = [next(node.infer()) for node in ast_nodes]
- self.assertEqual(ast_nodes[0].as_string(), 'frozenset((1, 2, 3))')
- self.assertEqual(ast_nodes[1].as_string(), 'frozenset({1, 2, 3})')
- self.assertEqual(ast_nodes[2].as_string(), 'frozenset([1, 2, 3])')
+ self.assertEqual(ast_nodes[0].as_string(), "frozenset((1, 2, 3))")
+ self.assertEqual(ast_nodes[1].as_string(), "frozenset({1, 2, 3})")
+ self.assertEqual(ast_nodes[2].as_string(), "frozenset([1, 2, 3])")
- self.assertNotEqual(ast_nodes[3].as_string(), 'frozenset(None)')
- self.assertNotEqual(ast_nodes[4].as_string(), 'frozenset(1)')
+ self.assertNotEqual(ast_nodes[3].as_string(), "frozenset(None)")
+ self.assertNotEqual(ast_nodes[4].as_string(), "frozenset(1)")
def test_varargs_kwargs_as_string(self):
- ast = abuilder.string_build('raise_string(*args, **kwargs)').body[0]
- self.assertEqual(ast.as_string(), 'raise_string(*args, **kwargs)')
+ ast = abuilder.string_build("raise_string(*args, **kwargs)").body[0]
+ self.assertEqual(ast.as_string(), "raise_string(*args, **kwargs)")
def test_module_as_string(self):
"""check as_string on a whole module prepared to be returned identically
"""
- module = resources.build_file('data/module.py', 'data.module')
- with open(resources.find('data/module.py'), 'r') as fobj:
+ module = resources.build_file("data/module.py", "data.module")
+ with open(resources.find("data/module.py"), "r") as fobj:
self.assertMultiLineEqual(module.as_string(), fobj.read())
def test_module2_as_string(self):
"""check as_string on a whole module prepared to be returned identically
"""
- module2 = resources.build_file('data/module2.py', 'data.module2')
- with open(resources.find('data/module2.py'), 'r') as fobj:
+ module2 = resources.build_file("data/module2.py", "data.module2")
+ with open(resources.find("data/module2.py"), "r") as fobj:
self.assertMultiLineEqual(module2.as_string(), fobj.read())
def test_as_string(self):
"""check as_string for python syntax >= 2.7"""
- code = '''one_two = {1, 2}
+ code = """one_two = {1, 2}
b = {v: k for (k, v) in enumerate('string')}
-cdd = {k for k in b}\n\n'''
+cdd = {k for k in b}\n\n"""
ast = abuilder.string_build(code)
self.assertMultiLineEqual(ast.as_string(), code)
- @test_utils.require_version('3.0')
+ @test_utils.require_version("3.0")
def test_3k_as_string(self):
"""check as_string for python 3k syntax"""
- code = '''print()
+ code = """print()
def function(var):
nonlocal counter
@@ -135,31 +141,41 @@ def function(var):
except NameError as nexc:
(*hell, o) = b'hello'
raise AttributeError from nexc
-\n'''
+\n"""
ast = abuilder.string_build(code)
self.assertEqual(ast.as_string(), code)
- @test_utils.require_version('3.0')
+ @test_utils.require_version("3.0")
@unittest.expectedFailure
def test_3k_annotations_and_metaclass(self):
- code_annotations = textwrap.dedent('''
+ code_annotations = textwrap.dedent(
+ '''
def function(var:int):
nonlocal counter
class Language(metaclass=Natural):
"""natural language"""
- ''')
+ '''
+ )
ast = abuilder.string_build(code_annotations)
self.assertEqual(ast.as_string(), code_annotations)
def test_ellipsis(self):
- ast = abuilder.string_build('a[...]').body[0]
- self.assertEqual(ast.as_string(), 'a[...]')
+ ast = abuilder.string_build("a[...]").body[0]
+ self.assertEqual(ast.as_string(), "a[...]")
def test_slices(self):
- for code in ('a[0]', 'a[1:3]', 'a[:-1:step]', 'a[:, newaxis]',
- 'a[newaxis, :]', 'del L[::2]', 'del A[1]', 'del Br[:]'):
+ for code in (
+ "a[0]",
+ "a[1:3]",
+ "a[:-1:step]",
+ "a[:, newaxis]",
+ "a[newaxis, :]",
+ "del L[::2]",
+ "del A[1]",
+ "del Br[:]",
+ ):
ast = abuilder.string_build(code).body[0]
self.assertEqual(ast.as_string(), code)
@@ -183,7 +199,7 @@ if all[1] == bord[0:]:
self.assertEqual(ast.as_string(), code)
def test_operator_precedence(self):
- with open(resources.find('data/operator_precedence.py')) as f:
+ with open(resources.find("data/operator_precedence.py")) as f:
for code in f:
self.check_as_string_ast_equality(code)
@@ -205,12 +221,13 @@ if all[1] == bord[0:]:
class _NodeTest(unittest.TestCase):
"""test transformation of If Node"""
+
CODE = None
@property
def astroid(self):
try:
- return self.__class__.__dict__['CODE_Astroid']
+ return self.__class__.__dict__["CODE_Astroid"]
except KeyError:
module = builder.parse(self.CODE)
self.__class__.CODE_Astroid = module
@@ -219,6 +236,7 @@ class _NodeTest(unittest.TestCase):
class IfNodeTest(_NodeTest):
"""test transformation of If Node"""
+
CODE = """
if 0:
print()
@@ -332,7 +350,6 @@ class TryExcept2xNodeTest(_NodeTest):
pass
"""
-
def test_tuple_attribute(self):
handler = self.astroid.body[0].handlers[0]
self.assertIsInstance(handler.name, nodes.Tuple)
@@ -341,47 +358,49 @@ class TryExcept2xNodeTest(_NodeTest):
class ImportNodeTest(resources.SysPathSetup, unittest.TestCase):
def setUp(self):
super(ImportNodeTest, self).setUp()
- self.module = resources.build_file('data/module.py', 'data.module')
- self.module2 = resources.build_file('data/module2.py', 'data.module2')
+ self.module = resources.build_file("data/module.py", "data.module")
+ self.module2 = resources.build_file("data/module2.py", "data.module2")
def test_import_self_resolve(self):
- myos = next(self.module2.igetattr('myos'))
+ myos = next(self.module2.igetattr("myos"))
self.assertTrue(isinstance(myos, nodes.Module), myos)
- self.assertEqual(myos.name, 'os')
- self.assertEqual(myos.qname(), 'os')
- self.assertEqual(myos.pytype(), '%s.module' % BUILTINS)
+ self.assertEqual(myos.name, "os")
+ self.assertEqual(myos.qname(), "os")
+ self.assertEqual(myos.pytype(), "%s.module" % BUILTINS)
def test_from_self_resolve(self):
- namenode = next(self.module.igetattr('NameNode'))
+ namenode = next(self.module.igetattr("NameNode"))
self.assertTrue(isinstance(namenode, nodes.ClassDef), namenode)
- self.assertEqual(namenode.root().name, 'astroid.node_classes')
- self.assertEqual(namenode.qname(), 'astroid.node_classes.Name')
- self.assertEqual(namenode.pytype(), '%s.type' % BUILTINS)
- abspath = next(self.module2.igetattr('abspath'))
+ self.assertEqual(namenode.root().name, "astroid.node_classes")
+ self.assertEqual(namenode.qname(), "astroid.node_classes.Name")
+ self.assertEqual(namenode.pytype(), "%s.type" % BUILTINS)
+ abspath = next(self.module2.igetattr("abspath"))
self.assertTrue(isinstance(abspath, nodes.FunctionDef), abspath)
- self.assertEqual(abspath.root().name, 'os.path')
- self.assertEqual(abspath.qname(), 'os.path.abspath')
- self.assertEqual(abspath.pytype(), '%s.function' % BUILTINS)
+ self.assertEqual(abspath.root().name, "os.path")
+ self.assertEqual(abspath.qname(), "os.path.abspath")
+ self.assertEqual(abspath.pytype(), "%s.function" % BUILTINS)
def test_real_name(self):
- from_ = self.module['NameNode']
- self.assertEqual(from_.real_name('NameNode'), 'Name')
- imp_ = self.module['os']
- self.assertEqual(imp_.real_name('os'), 'os')
- self.assertRaises(exceptions.AttributeInferenceError, imp_.real_name, 'os.path')
- imp_ = self.module['NameNode']
- self.assertEqual(imp_.real_name('NameNode'), 'Name')
- self.assertRaises(exceptions.AttributeInferenceError, imp_.real_name, 'Name')
- imp_ = self.module2['YO']
- self.assertEqual(imp_.real_name('YO'), 'YO')
- self.assertRaises(exceptions.AttributeInferenceError, imp_.real_name, 'data')
+ from_ = self.module["NameNode"]
+ self.assertEqual(from_.real_name("NameNode"), "Name")
+ imp_ = self.module["os"]
+ self.assertEqual(imp_.real_name("os"), "os")
+ self.assertRaises(exceptions.AttributeInferenceError, imp_.real_name, "os.path")
+ imp_ = self.module["NameNode"]
+ self.assertEqual(imp_.real_name("NameNode"), "Name")
+ self.assertRaises(exceptions.AttributeInferenceError, imp_.real_name, "Name")
+ imp_ = self.module2["YO"]
+ self.assertEqual(imp_.real_name("YO"), "YO")
+ self.assertRaises(exceptions.AttributeInferenceError, imp_.real_name, "data")
def test_as_string(self):
- ast = self.module['modutils']
+ ast = self.module["modutils"]
self.assertEqual(ast.as_string(), "from astroid import modutils")
- ast = self.module['NameNode']
- self.assertEqual(ast.as_string(), "from astroid.node_classes import Name as NameNode")
- ast = self.module['os']
+ ast = self.module["NameNode"]
+ self.assertEqual(
+ ast.as_string(), "from astroid.node_classes import Name as NameNode"
+ )
+ ast = self.module["os"]
self.assertEqual(ast.as_string(), "import os.path")
code = """from . import here
from .. import door
@@ -392,14 +411,14 @@ from ..cave import wine\n\n"""
def test_bad_import_inference(self):
# Explication of bug
- '''When we import PickleError from nonexistent, a call to the infer
+ """When we import PickleError from nonexistent, a call to the infer
method of this From node will be made by unpack_infer.
inference.infer_from will try to import this module, which will fail and
raise a InferenceException (by mixins.do_import_module). The infer_name
will catch this exception and yield and Uninferable instead.
- '''
+ """
- code = '''
+ code = """
try:
from pickle import PickleError
except ImportError:
@@ -409,7 +428,7 @@ from ..cave import wine\n\n"""
pass
except PickleError:
pass
- '''
+ """
module = builder.parse(code)
handler_type = module.body[1].handlers[0].type
@@ -419,22 +438,22 @@ from ..cave import wine\n\n"""
# be returned, from the _pickle module, which is not
# present in the other version.
self.assertIsInstance(excs[0], nodes.ClassDef)
- self.assertEqual(excs[0].name, 'PickleError')
+ self.assertEqual(excs[0].name, "PickleError")
self.assertIs(excs[-1], util.Uninferable)
def test_absolute_import(self):
- module = resources.build_file('data/absimport.py')
+ module = resources.build_file("data/absimport.py")
ctx = contextmod.InferenceContext()
# will fail if absolute import failed
- ctx.lookupname = 'message'
- next(module['message'].infer(ctx))
- ctx.lookupname = 'email'
- m = next(module['email'].infer(ctx))
- self.assertFalse(m.file.startswith(os.path.join('data', 'email.py')))
+ ctx.lookupname = "message"
+ next(module["message"].infer(ctx))
+ ctx.lookupname = "email"
+ m = next(module["email"].infer(ctx))
+ self.assertFalse(m.file.startswith(os.path.join("data", "email.py")))
def test_more_absolute_import(self):
- module = resources.build_file('data/module1abs/__init__.py', 'data.module1abs')
- self.assertIn('sys', module.locals)
+ module = resources.build_file("data/module1abs/__init__.py", "data.module1abs")
+ self.assertIn("sys", module.locals)
class CmpNodeTest(unittest.TestCase):
@@ -444,7 +463,6 @@ class CmpNodeTest(unittest.TestCase):
class ConstNodeTest(unittest.TestCase):
-
def _test(self, value):
node = nodes.const_factory(value)
# pylint: disable=no-member; Infers two potential values
@@ -470,10 +488,10 @@ class ConstNodeTest(unittest.TestCase):
self._test(1.0j)
def test_str(self):
- self._test('a')
+ self._test("a")
def test_unicode(self):
- self._test('a')
+ self._test("a")
def test_copy(self):
"""
@@ -497,7 +515,7 @@ class NameNodeTest(unittest.TestCase):
builder.parse(code)
else:
ast = builder.parse(code)
- assign_true = ast['True']
+ assign_true = ast["True"]
self.assertIsInstance(assign_true, nodes.AssignName)
self.assertEqual(assign_true.name, "True")
del_true = ast.body[2].targets[0]
@@ -506,11 +524,13 @@ class NameNodeTest(unittest.TestCase):
class AnnAssignNodeTest(unittest.TestCase):
- @test_utils.require_version(minver='3.6')
+ @test_utils.require_version(minver="3.6")
def test_primitive(self):
- code = textwrap.dedent("""
+ code = textwrap.dedent(
+ """
test: int = 5
- """)
+ """
+ )
assign = builder.extract_node(code)
self.assertIsInstance(assign, nodes.AnnAssign)
self.assertEqual(assign.target.name, "test")
@@ -518,94 +538,107 @@ class AnnAssignNodeTest(unittest.TestCase):
self.assertEqual(assign.value.value, 5)
self.assertEqual(assign.simple, 1)
- @test_utils.require_version(minver='3.6')
+ @test_utils.require_version(minver="3.6")
def test_primitive_without_initial_value(self):
- code = textwrap.dedent("""
+ code = textwrap.dedent(
+ """
test: str
- """)
+ """
+ )
assign = builder.extract_node(code)
self.assertIsInstance(assign, nodes.AnnAssign)
self.assertEqual(assign.target.name, "test")
self.assertEqual(assign.annotation.name, "str")
self.assertEqual(assign.value, None)
- @test_utils.require_version(minver='3.6')
+ @test_utils.require_version(minver="3.6")
def test_complex(self):
- code = textwrap.dedent("""
+ code = textwrap.dedent(
+ """
test: Dict[List[str]] = {}
- """)
+ """
+ )
assign = builder.extract_node(code)
self.assertIsInstance(assign, nodes.AnnAssign)
self.assertEqual(assign.target.name, "test")
self.assertIsInstance(assign.annotation, astroid.Subscript)
self.assertIsInstance(assign.value, astroid.Dict)
- @test_utils.require_version(minver='3.6')
+ @test_utils.require_version(minver="3.6")
def test_as_string(self):
- code = textwrap.dedent("""
+ code = textwrap.dedent(
+ """
print()
test: int = 5
test2: str
test3: List[Dict[str, str]] = []
- """)
+ """
+ )
ast = abuilder.string_build(code)
self.assertEqual(ast.as_string().strip(), code.strip())
class ArgumentsNodeTC(unittest.TestCase):
def test_linenumbering(self):
- ast = builder.parse('''
+ ast = builder.parse(
+ """
def func(a,
b): pass
x = lambda x: None
- ''')
- self.assertEqual(ast['func'].args.fromlineno, 2)
- self.assertFalse(ast['func'].args.is_statement)
- xlambda = next(ast['x'].infer())
+ """
+ )
+ self.assertEqual(ast["func"].args.fromlineno, 2)
+ self.assertFalse(ast["func"].args.is_statement)
+ xlambda = next(ast["x"].infer())
self.assertEqual(xlambda.args.fromlineno, 4)
self.assertEqual(xlambda.args.tolineno, 4)
self.assertFalse(xlambda.args.is_statement)
if sys.version_info < (3, 0):
- self.assertEqual(ast['func'].args.tolineno, 3)
+ self.assertEqual(ast["func"].args.tolineno, 3)
else:
- self.skipTest('FIXME http://bugs.python.org/issue10445 '
- '(no line number on function args)')
+ self.skipTest(
+ "FIXME http://bugs.python.org/issue10445 "
+ "(no line number on function args)"
+ )
- @test_utils.require_version(minver='3.0')
+ @test_utils.require_version(minver="3.0")
def test_kwoargs(self):
- ast = builder.parse('''
+ ast = builder.parse(
+ """
def func(*, x):
pass
- ''')
- args = ast['func'].args
- self.assertTrue(args.is_argument('x'))
+ """
+ )
+ args = ast["func"].args
+ self.assertTrue(args.is_argument("x"))
class UnboundMethodNodeTest(unittest.TestCase):
-
def test_no_super_getattr(self):
# This is a test for issue
# https://bitbucket.org/logilab/astroid/issue/91, which tests
# that UnboundMethod doesn't call super when doing .getattr.
- ast = builder.parse('''
+ ast = builder.parse(
+ """
class A(object):
def test(self):
pass
meth = A.test
- ''')
- node = next(ast['meth'].infer())
+ """
+ )
+ node = next(ast["meth"].infer())
with self.assertRaises(exceptions.AttributeInferenceError):
- node.getattr('__missssing__')
- name = node.getattr('__name__')[0]
+ node.getattr("__missssing__")
+ name = node.getattr("__name__")[0]
self.assertIsInstance(name, nodes.Const)
- self.assertEqual(name.value, 'test')
+ self.assertEqual(name.value, "test")
class BoundMethodNodeTest(unittest.TestCase):
-
def test_is_property(self):
- ast = builder.parse('''
+ ast = builder.parse(
+ """
import abc
def cached_property():
@@ -647,19 +680,26 @@ class BoundMethodNodeTest(unittest.TestCase):
lazy_prop = cls.lazy_prop
lazyprop = cls.lazyprop
decorated_with_lazy = cls.decorated_with_lazy
- ''')
- for prop in ('builtin_property', 'abc_property', 'cached_p', 'reified',
- 'lazy_prop', 'lazyprop', 'decorated_with_lazy'):
+ """
+ )
+ for prop in (
+ "builtin_property",
+ "abc_property",
+ "cached_p",
+ "reified",
+ "lazy_prop",
+ "lazyprop",
+ "decorated_with_lazy",
+ ):
inferred = next(ast[prop].infer())
self.assertIsInstance(inferred, nodes.Const, prop)
self.assertEqual(inferred.value, 42, prop)
- inferred = next(ast['not_prop'].infer())
+ inferred = next(ast["not_prop"].infer())
self.assertIsInstance(inferred, bases.BoundMethod)
class AliasesTest(unittest.TestCase):
-
def setUp(self):
self.transformer = transforms.TransformVisitor()
@@ -669,45 +709,45 @@ class AliasesTest(unittest.TestCase):
def test_aliases(self):
def test_from(node):
- node.names = node.names + [('absolute_import', None)]
+ node.names = node.names + [("absolute_import", None)]
return node
def test_class(node):
- node.name = 'Bar'
+ node.name = "Bar"
return node
def test_function(node):
- node.name = 'another_test'
+ node.name = "another_test"
return node
def test_callfunc(node):
- if node.func.name == 'Foo':
- node.func.name = 'Bar'
+ if node.func.name == "Foo":
+ node.func.name = "Bar"
return node
return None
def test_assname(node):
- if node.name == 'foo':
- return nodes.AssignName('bar', node.lineno, node.col_offset,
- node.parent)
+ if node.name == "foo":
+ return nodes.AssignName(
+ "bar", node.lineno, node.col_offset, node.parent
+ )
return None
def test_assattr(node):
- if node.attrname == 'a':
- node.attrname = 'b'
+ if node.attrname == "a":
+ node.attrname = "b"
return node
return None
def test_getattr(node):
- if node.attrname == 'a':
- node.attrname = 'b'
+ if node.attrname == "a":
+ node.attrname = "b"
return node
return None
def test_genexpr(node):
if node.elt.value == 1:
- node.elt = nodes.Const(2, node.lineno, node.col_offset,
- node.parent)
+ node.elt = nodes.Const(2, node.lineno, node.col_offset, node.parent)
return node
return None
@@ -720,7 +760,7 @@ class AliasesTest(unittest.TestCase):
self.transformer.register_transform(nodes.Attribute, test_getattr)
self.transformer.register_transform(nodes.GeneratorExp, test_genexpr)
- string = '''
+ string = """
from __future__ import print_function
class Foo: pass
@@ -731,40 +771,41 @@ class AliasesTest(unittest.TestCase):
foo.a = test(42)
foo.a
(1 for _ in range(0, 42))
- '''
+ """
module = self.parse_transform(string)
self.assertEqual(len(module.body[0].names), 2)
self.assertIsInstance(module.body[0], nodes.ImportFrom)
- self.assertEqual(module.body[1].name, 'Bar')
+ self.assertEqual(module.body[1].name, "Bar")
self.assertIsInstance(module.body[1], nodes.ClassDef)
- self.assertEqual(module.body[2].name, 'another_test')
+ self.assertEqual(module.body[2].name, "another_test")
self.assertIsInstance(module.body[2], nodes.FunctionDef)
- self.assertEqual(module.body[3].targets[0].name, 'bar')
+ self.assertEqual(module.body[3].targets[0].name, "bar")
self.assertIsInstance(module.body[3].targets[0], nodes.AssignName)
- self.assertEqual(module.body[3].value.func.name, 'Bar')
+ self.assertEqual(module.body[3].value.func.name, "Bar")
self.assertIsInstance(module.body[3].value, nodes.Call)
- self.assertEqual(module.body[4].targets[0].attrname, 'b')
+ self.assertEqual(module.body[4].targets[0].attrname, "b")
self.assertIsInstance(module.body[4].targets[0], nodes.AssignAttr)
self.assertIsInstance(module.body[5], nodes.Expr)
- self.assertEqual(module.body[5].value.attrname, 'b')
+ self.assertEqual(module.body[5].value.attrname, "b")
self.assertIsInstance(module.body[5].value, nodes.Attribute)
self.assertEqual(module.body[6].value.elt.value, 2)
self.assertIsInstance(module.body[6].value, nodes.GeneratorExp)
-@test_utils.require_version('3.5')
+@test_utils.require_version("3.5")
class Python35AsyncTest(unittest.TestCase):
-
def test_async_await_keywords(self):
- async_def, async_for, async_with, await_node = builder.extract_node('''
+ async_def, async_for, async_with, await_node = builder.extract_node(
+ """
async def func(): #@
async for i in range(10): #@
f = __(await i)
async with test(): #@
pass
- ''')
+ """
+ )
self.assertIsInstance(async_def, nodes.AsyncFunctionDef)
self.assertIsInstance(async_for, nodes.AsyncFor)
self.assertIsInstance(async_with, nodes.AsyncWith)
@@ -776,96 +817,102 @@ class Python35AsyncTest(unittest.TestCase):
self.assertEqual(ast_node.as_string().strip(), code.strip())
def test_await_as_string(self):
- code = textwrap.dedent('''
+ code = textwrap.dedent(
+ """
async def function():
await 42
await x[0]
(await x)[0]
await (x + y)[0]
- ''')
+ """
+ )
self._test_await_async_as_string(code)
def test_asyncwith_as_string(self):
- code = textwrap.dedent('''
+ code = textwrap.dedent(
+ """
async def function():
async with 42:
pass
- ''')
+ """
+ )
self._test_await_async_as_string(code)
def test_asyncfor_as_string(self):
- code = textwrap.dedent('''
+ code = textwrap.dedent(
+ """
async def function():
async for i in range(10):
await 42
- ''')
+ """
+ )
self._test_await_async_as_string(code)
class ContextTest(unittest.TestCase):
-
def test_subscript_load(self):
- node = builder.extract_node('f[1]')
+ node = builder.extract_node("f[1]")
self.assertIs(node.ctx, astroid.Load)
def test_subscript_del(self):
- node = builder.extract_node('del f[1]')
+ node = builder.extract_node("del f[1]")
self.assertIs(node.targets[0].ctx, astroid.Del)
def test_subscript_store(self):
- node = builder.extract_node('f[1] = 2')
+ node = builder.extract_node("f[1] = 2")
subscript = node.targets[0]
self.assertIs(subscript.ctx, astroid.Store)
def test_list_load(self):
- node = builder.extract_node('[]')
+ node = builder.extract_node("[]")
self.assertIs(node.ctx, astroid.Load)
def test_list_del(self):
- node = builder.extract_node('del []')
+ node = builder.extract_node("del []")
self.assertIs(node.targets[0].ctx, astroid.Del)
def test_list_store(self):
with self.assertRaises(exceptions.AstroidSyntaxError):
- builder.extract_node('[0] = 2')
+ builder.extract_node("[0] = 2")
def test_tuple_load(self):
- node = builder.extract_node('(1, )')
+ node = builder.extract_node("(1, )")
self.assertIs(node.ctx, astroid.Load)
def test_tuple_store(self):
with self.assertRaises(exceptions.AstroidSyntaxError):
- builder.extract_node('(1, ) = 3')
+ builder.extract_node("(1, ) = 3")
- @test_utils.require_version(minver='3.5')
+ @test_utils.require_version(minver="3.5")
def test_starred_load(self):
- node = builder.extract_node('a = *b')
+ node = builder.extract_node("a = *b")
starred = node.value
self.assertIs(starred.ctx, astroid.Load)
- @test_utils.require_version(minver='3.0')
+ @test_utils.require_version(minver="3.0")
def test_starred_store(self):
- node = builder.extract_node('a, *b = 1, 2')
+ node = builder.extract_node("a, *b = 1, 2")
starred = node.targets[0].elts[1]
self.assertIs(starred.ctx, astroid.Store)
def test_unknown():
"""Test Unknown node"""
- assert isinstance(next(nodes.Unknown().infer()),
- type(util.Uninferable))
+ assert isinstance(next(nodes.Unknown().infer()), type(util.Uninferable))
assert isinstance(nodes.Unknown().name, str)
assert isinstance(nodes.Unknown().qname(), str)
@pytest.mark.skipif(not HAS_TYPED_AST, reason="requires typed_ast")
def test_type_comments_with():
- module = builder.parse('''
+ module = builder.parse(
+ """
with a as b: # type: int
pass
with a as b: # type: ignore
pass
- ''')
+ """
+ )
node = module.body[0]
ignored_node = module.body[1]
assert isinstance(node.type_annotation, astroid.Name)
@@ -875,48 +922,55 @@ def test_type_comments_with():
@pytest.mark.skipif(not HAS_TYPED_AST, reason="requires typed_ast")
def test_type_comments_for():
- module = builder.parse('''
+ module = builder.parse(
+ """
for a, b in [1, 2, 3]: # type: List[int]
pass
for a, b in [1, 2, 3]: # type: ignore
pass
- ''')
+ """
+ )
node = module.body[0]
ignored_node = module.body[1]
assert isinstance(node.type_annotation, astroid.Subscript)
- assert node.type_annotation.as_string() == 'List[int]'
+ assert node.type_annotation.as_string() == "List[int]"
assert ignored_node.type_annotation is None
@pytest.mark.skipif(not HAS_TYPED_AST, reason="requires typed_ast")
def test_type_coments_assign():
- module = builder.parse('''
+ module = builder.parse(
+ """
a, b = [1, 2, 3] # type: List[int]
a, b = [1, 2, 3] # type: ignore
- ''')
+ """
+ )
node = module.body[0]
ignored_node = module.body[1]
assert isinstance(node.type_annotation, astroid.Subscript)
- assert node.type_annotation.as_string() == 'List[int]'
+ assert node.type_annotation.as_string() == "List[int]"
assert ignored_node.type_annotation is None
@pytest.mark.skipif(not HAS_TYPED_AST, reason="requires typed_ast")
def test_type_comments_invalid_expression():
- module = builder.parse('''
+ module = builder.parse(
+ """
a, b = [1, 2, 3] # type: something completely invalid
a, b = [1, 2, 3] # typeee: 2*+4
a, b = [1, 2, 3] # type: List[int
- ''')
+ """
+ )
for node in module.body:
assert node.type_annotation is None
@pytest.mark.skipif(not HAS_TYPED_AST, reason="requires typed_ast")
def test_type_comments_invalid_function_comments():
- module = builder.parse('''
+ module = builder.parse(
+ """
def func():
# type: something completely invalid
pass
@@ -926,7 +980,8 @@ def test_type_comments_invalid_function_comments():
def func2():
# type: List[int
pass
- ''')
+ """
+ )
for node in module.body:
assert node.type_comment_returns is None
assert node.type_comment_args is None
@@ -934,7 +989,8 @@ def test_type_comments_invalid_function_comments():
@pytest.mark.skipif(not HAS_TYPED_AST, reason="requires typed_ast")
def test_type_comments_function():
- module = builder.parse('''
+ module = builder.parse(
+ """
def func():
# type: (int) -> str
pass
@@ -944,17 +1000,16 @@ def test_type_comments_function():
def func2():
# type: (int, int, str, List[int]) -> List[int]
pass
- ''')
+ """
+ )
expected_annotations = [
(["int"], astroid.Name, "str"),
(["int", "int", "int"], astroid.Tuple, "(str, str)"),
(["int", "int", "str", "List[int]"], astroid.Subscript, "List[int]"),
]
- for node, (
- expected_args,
- expected_returns_type,
- expected_returns_string
- ) in zip(module.body, expected_annotations):
+ for node, (expected_args, expected_returns_type, expected_returns_string) in zip(
+ module.body, expected_annotations
+ ):
assert node.type_comment_returns is not None
assert node.type_comment_args is not None
for expected_arg, actual_arg in zip(expected_args, node.type_comment_args):
@@ -964,7 +1019,8 @@ def test_type_comments_function():
def test_is_generator_for_yield_assignments():
- node = astroid.extract_node('''
+ node = astroid.extract_node(
+ """
class A:
def test(self):
a = yield
@@ -973,60 +1029,66 @@ def test_is_generator_for_yield_assignments():
yield a
a = A()
a.test
- ''')
+ """
+ )
inferred = next(node.infer())
assert isinstance(inferred, astroid.BoundMethod)
assert bool(inferred.is_generator())
class AsyncGeneratorTest:
-
- @test_utils.require_version(minver='3.6')
+ @test_utils.require_version(minver="3.6")
def test_async_generator(self):
- node = astroid.extract_node('''
+ node = astroid.extract_node(
+ """
async def a_iter(n):
for i in range(1, n + 1):
yield i
await asyncio.sleep(1)
a_iter(2) #@
- ''')
+ """
+ )
inferred = next(node.infer())
assert isinstance(inferred, bases.AsyncGenerator)
- assert inferred.getattr('__aiter__')
- assert inferred.getattr('__anext__')
- assert inferred.pytype() == 'builtins.async_generator'
- assert inferred.display_type() == 'AsyncGenerator'
+ assert inferred.getattr("__aiter__")
+ assert inferred.getattr("__anext__")
+ assert inferred.pytype() == "builtins.async_generator"
+ assert inferred.display_type() == "AsyncGenerator"
- @test_utils.require_version(maxver='3.5')
+ @test_utils.require_version(maxver="3.5")
def test_async_generator_is_generator_on_older_python(self):
- node = astroid.extract_node('''
+ node = astroid.extract_node(
+ """
async def a_iter(n):
for i in range(1, n + 1):
yield i
await asyncio.sleep(1)
a_iter(2) #@
- ''')
+ """
+ )
inferred = next(node.infer())
assert isinstance(inferred, bases.Generator)
- assert inferred.getattr('__iter__')
- assert inferred.getattr('__next__')
- assert inferred.pytype() == 'builtins.generator'
- assert inferred.display_type() == 'Generator'
+ assert inferred.getattr("__iter__")
+ assert inferred.getattr("__next__")
+ assert inferred.pytype() == "builtins.generator"
+ assert inferred.display_type() == "Generator"
@pytest.mark.skipif(sys.version_info[:2] < (3, 6), reason="needs f-string support")
def test_f_string_correct_line_numbering():
"""Test that we generate correct line numbers for f-strings"""
- node = astroid.extract_node('''
+ node = astroid.extract_node(
+ """
def func_foo(arg_bar, arg_foo):
dict_foo = {}
f'{arg_bar.attr_bar}' #@
- ''')
+ """
+ )
assert node.lineno == 5
assert node.last_child().lineno == 5
assert node.last_child().last_child().lineno == 5
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/tests/unittest_object_model.py b/astroid/tests/unittest_object_model.py
index 5f350605..3b2872a7 100644
--- a/astroid/tests/unittest_object_model.py
+++ b/astroid/tests/unittest_object_model.py
@@ -22,9 +22,9 @@ BUILTINS = MANAGER.astroid_cache[builtins.__name__]
class InstanceModelTest(unittest.TestCase):
-
def test_instance_special_model(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class A:
"test"
def __init__(self):
@@ -34,65 +34,70 @@ class InstanceModelTest(unittest.TestCase):
a.__module__ #@
a.__doc__ #@
a.__dict__ #@
- ''', module_name='fake_module')
+ """,
+ module_name="fake_module",
+ )
cls = next(ast_nodes[0].infer())
self.assertIsInstance(cls, astroid.ClassDef)
- self.assertEqual(cls.name, 'A')
+ self.assertEqual(cls.name, "A")
module = next(ast_nodes[1].infer())
self.assertIsInstance(module, astroid.Const)
- self.assertEqual(module.value, 'fake_module')
+ self.assertEqual(module.value, "fake_module")
doc = next(ast_nodes[2].infer())
self.assertIsInstance(doc, astroid.Const)
- self.assertEqual(doc.value, 'test')
+ self.assertEqual(doc.value, "test")
dunder_dict = next(ast_nodes[3].infer())
self.assertIsInstance(dunder_dict, astroid.Dict)
- attr = next(dunder_dict.getitem(astroid.Const('a')).infer())
+ attr = next(dunder_dict.getitem(astroid.Const("a")).infer())
self.assertIsInstance(attr, astroid.Const)
self.assertEqual(attr.value, 42)
@unittest.expectedFailure
def test_instance_local_attributes_overrides_object_model(self):
# The instance lookup needs to be changed in order for this to work.
- ast_node = builder.extract_node('''
+ ast_node = builder.extract_node(
+ """
class A:
@property
def __dict__(self):
return []
A().__dict__
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, astroid.List)
self.assertEqual(inferred.elts, [])
class BoundMethodModelTest(unittest.TestCase):
-
def test_bound_method_model(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class A:
def test(self): pass
a = A()
a.test.__func__ #@
a.test.__self__ #@
- ''')
+ """
+ )
func = next(ast_nodes[0].infer())
self.assertIsInstance(func, astroid.FunctionDef)
- self.assertEqual(func.name, 'test')
+ self.assertEqual(func.name, "test")
self_ = next(ast_nodes[1].infer())
self.assertIsInstance(self_, astroid.Instance)
- self.assertEqual(self_.name, 'A')
+ self.assertEqual(self_.name, "A")
class UnboundMethodModelTest(unittest.TestCase):
-
def test_unbound_method_model(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class A:
def test(self): pass
t = A.test
@@ -102,17 +107,18 @@ class UnboundMethodModelTest(unittest.TestCase):
t.im_class #@
t.im_func #@
t.im_self #@
- ''')
+ """
+ )
cls = next(ast_nodes[0].infer())
self.assertIsInstance(cls, astroid.ClassDef)
- unbound_name = 'function'
+ unbound_name = "function"
self.assertEqual(cls.name, unbound_name)
func = next(ast_nodes[1].infer())
self.assertIsInstance(func, astroid.FunctionDef)
- self.assertEqual(func.name, 'test')
+ self.assertEqual(func.name, "test")
self_ = next(ast_nodes[2].infer())
self.assertIsInstance(self_, astroid.Const)
@@ -124,53 +130,61 @@ class UnboundMethodModelTest(unittest.TestCase):
class ClassModelTest(unittest.TestCase):
-
def test_priority_to_local_defined_values(self):
- ast_node = builder.extract_node('''
+ ast_node = builder.extract_node(
+ """
class A:
__doc__ = "first"
A.__doc__ #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, astroid.Const)
self.assertEqual(inferred.value, "first")
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test__mro__old_style(self):
- ast_node = builder.extract_node('''
+ ast_node = builder.extract_node(
+ """
class A:
pass
A.__mro__
- ''')
+ """
+ )
with self.assertRaises(exceptions.InferenceError):
next(ast_node.infer())
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test__subclasses__old_style(self):
- ast_node = builder.extract_node('''
+ ast_node = builder.extract_node(
+ """
class A:
pass
A.__subclasses__
- ''')
+ """
+ )
with self.assertRaises(exceptions.InferenceError):
next(ast_node.infer())
def test_class_model_correct_mro_subclasses_proxied(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class A(object):
pass
A.mro #@
A.__subclasses__ #@
- ''')
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
self.assertIsInstance(inferred, astroid.BoundMethod)
self.assertIsInstance(inferred._proxied, astroid.FunctionDef)
self.assertIsInstance(inferred.bound, astroid.ClassDef)
- self.assertEqual(inferred.bound.name, 'type')
+ self.assertEqual(inferred.bound.name, "type")
def test_class_model(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class A(object):
"test"
@@ -187,69 +201,73 @@ class ClassModelTest(unittest.TestCase):
A.__class__ #@
A.__dict__ #@
A.__subclasses__() #@
- ''', module_name='fake_module')
+ """,
+ module_name="fake_module",
+ )
module = next(ast_nodes[0].infer())
self.assertIsInstance(module, astroid.Const)
- self.assertEqual(module.value, 'fake_module')
+ self.assertEqual(module.value, "fake_module")
name = next(ast_nodes[1].infer())
self.assertIsInstance(name, astroid.Const)
- self.assertEqual(name.value, 'A')
+ self.assertEqual(name.value, "A")
qualname = next(ast_nodes[2].infer())
self.assertIsInstance(qualname, astroid.Const)
- self.assertEqual(qualname.value, 'fake_module.A')
+ self.assertEqual(qualname.value, "fake_module.A")
doc = next(ast_nodes[3].infer())
self.assertIsInstance(doc, astroid.Const)
- self.assertEqual(doc.value, 'test')
+ self.assertEqual(doc.value, "test")
mro = next(ast_nodes[4].infer())
self.assertIsInstance(mro, astroid.Tuple)
- self.assertEqual([cls.name for cls in mro.elts],
- ['A', 'object'])
+ self.assertEqual([cls.name for cls in mro.elts], ["A", "object"])
called_mro = next(ast_nodes[5].infer())
self.assertEqual(called_mro.elts, mro.elts)
bases = next(ast_nodes[6].infer())
self.assertIsInstance(bases, astroid.Tuple)
- self.assertEqual([cls.name for cls in bases.elts],
- ['object'])
+ self.assertEqual([cls.name for cls in bases.elts], ["object"])
cls = next(ast_nodes[7].infer())
self.assertIsInstance(cls, astroid.ClassDef)
- self.assertEqual(cls.name, 'type')
+ self.assertEqual(cls.name, "type")
cls_dict = next(ast_nodes[8].infer())
self.assertIsInstance(cls_dict, astroid.Dict)
subclasses = next(ast_nodes[9].infer())
self.assertIsInstance(subclasses, astroid.List)
- self.assertEqual([cls.name for cls in subclasses.elts], ['B', 'C'])
+ self.assertEqual([cls.name for cls in subclasses.elts], ["B", "C"])
class ModuleModelTest(unittest.TestCase):
-
def test_priority_to_local_defined_values(self):
- ast_node = astroid.parse('''
+ ast_node = astroid.parse(
+ """
__file__ = "mine"
- ''')
- file_value = next(ast_node.igetattr('__file__'))
+ """
+ )
+ file_value = next(ast_node.igetattr("__file__"))
self.assertIsInstance(file_value, astroid.Const)
self.assertEqual(file_value.value, "mine")
def test__path__not_a_package(self):
- ast_node = builder.extract_node('''
+ ast_node = builder.extract_node(
+ """
import sys
sys.__path__ #@
- ''')
+ """
+ )
with self.assertRaises(exceptions.InferenceError):
next(ast_node.infer())
def test_module_model(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
import xml
xml.__path__ #@
xml.__name__ #@
@@ -260,7 +278,8 @@ class ModuleModelTest(unittest.TestCase):
xml.__cached__ #@
xml.__package__ #@
xml.__dict__ #@
- ''')
+ """
+ )
path = next(ast_nodes[0].infer())
self.assertIsInstance(path, astroid.List)
@@ -269,7 +288,7 @@ class ModuleModelTest(unittest.TestCase):
name = next(ast_nodes[1].infer())
self.assertIsInstance(name, astroid.Const)
- self.assertEqual(name.value, 'xml')
+ self.assertEqual(name.value, "xml")
doc = next(ast_nodes[2].infer())
self.assertIsInstance(doc, astroid.Const)
@@ -285,63 +304,70 @@ class ModuleModelTest(unittest.TestCase):
package = next(ast_nodes[7].infer())
self.assertIsInstance(package, astroid.Const)
- self.assertEqual(package.value, 'xml')
+ self.assertEqual(package.value, "xml")
dict_ = next(ast_nodes[8].infer())
self.assertIsInstance(dict_, astroid.Dict)
class FunctionModelTest(unittest.TestCase):
-
def test_partial_descriptor_support(self):
- bound, result = builder.extract_node('''
+ bound, result = builder.extract_node(
+ """
class A(object): pass
def test(self): return 42
f = test.__get__(A(), A)
f #@
f() #@
- ''')
+ """
+ )
bound = next(bound.infer())
self.assertIsInstance(bound, astroid.BoundMethod)
- self.assertEqual(bound._proxied._proxied.name, 'test')
+ self.assertEqual(bound._proxied._proxied.name, "test")
result = next(result.infer())
self.assertIsInstance(result, astroid.Const)
self.assertEqual(result.value, 42)
def test___get__has_extra_params_defined(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
def test(self): return 42
test.__get__
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, astroid.BoundMethod)
args = inferred.args.args
self.assertEqual(len(args), 2)
- self.assertEqual([arg.name for arg in args], ['self', 'type'])
+ self.assertEqual([arg.name for arg in args], ["self", "type"])
@unittest.expectedFailure
def test_descriptor_not_inferrring_self(self):
# We can't infer __get__(X, Y)() when the bounded function
# uses self, because of the tree's parent not being propagating good enough.
- result = builder.extract_node('''
+ result = builder.extract_node(
+ """
class A(object):
x = 42
def test(self): return self.x
f = test.__get__(A(), A)
f() #@
- ''')
+ """
+ )
result = next(result.infer())
self.assertIsInstance(result, astroid.Const)
self.assertEqual(result.value, 42)
def test_descriptors_binding_invalid(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class A: pass
def test(self): return 42
test.__get__()() #@
test.__get__(1)() #@
test.__get__(2, 3, 4) #@
- ''')
+ """
+ )
for node in ast_nodes:
with self.assertRaises(exceptions.InferenceError):
next(node.infer())
@@ -349,7 +375,8 @@ class FunctionModelTest(unittest.TestCase):
def test_descriptor_error_regression(self):
"""Make sure the following code does
node cause an exception"""
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
class MyClass:
text = "MyText"
@@ -362,12 +389,14 @@ class FunctionModelTest(unittest.TestCase):
cl = MyClass().mymethod2()()
cl #@
- ''')
+ """
+ )
[const] = node.inferred()
assert const.value == "MyText"
def test_function_model(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ '''
def func(a=1, b=2):
"""test"""
func.__name__ #@
@@ -379,23 +408,25 @@ class FunctionModelTest(unittest.TestCase):
func.__globals__ #@
func.__code__ #@
func.__closure__ #@
- ''', module_name='fake_module')
+ ''',
+ module_name="fake_module",
+ )
name = next(ast_nodes[0].infer())
self.assertIsInstance(name, astroid.Const)
- self.assertEqual(name.value, 'func')
+ self.assertEqual(name.value, "func")
doc = next(ast_nodes[1].infer())
self.assertIsInstance(doc, astroid.Const)
- self.assertEqual(doc.value, 'test')
+ self.assertEqual(doc.value, "test")
qualname = next(ast_nodes[2].infer())
self.assertIsInstance(qualname, astroid.Const)
- self.assertEqual(qualname.value, 'fake_module.func')
+ self.assertEqual(qualname.value, "fake_module.func")
module = next(ast_nodes[3].infer())
self.assertIsInstance(module, astroid.Const)
- self.assertEqual(module.value, 'fake_module')
+ self.assertEqual(module.value, "fake_module")
defaults = next(ast_nodes[4].infer())
self.assertIsInstance(defaults, astroid.Tuple)
@@ -410,53 +441,62 @@ class FunctionModelTest(unittest.TestCase):
for ast_node in ast_nodes[7:9]:
self.assertIs(next(ast_node.infer()), astroid.Uninferable)
- @test_utils.require_version(minver='3.0')
+ @test_utils.require_version(minver="3.0")
def test_empty_return_annotation(self):
- ast_node = builder.extract_node('''
+ ast_node = builder.extract_node(
+ """
def test(): pass
test.__annotations__
- ''')
+ """
+ )
annotations = next(ast_node.infer())
self.assertIsInstance(annotations, astroid.Dict)
self.assertEqual(len(annotations.items), 0)
- @test_utils.require_version(minver='3.0')
+ @test_utils.require_version(minver="3.0")
def test_builtin_dunder_init_does_not_crash_when_accessing_annotations(self):
- ast_node = builder.extract_node('''
+ ast_node = builder.extract_node(
+ """
class Class:
@classmethod
def class_method(cls):
cls.__init__.__annotations__ #@
- ''')
+ """
+ )
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, astroid.Dict)
self.assertEqual(len(inferred.items), 0)
- @test_utils.require_version(minver='3.0')
+ @test_utils.require_version(minver="3.0")
def test_annotations_kwdefaults(self):
- ast_node = builder.extract_node('''
+ ast_node = builder.extract_node(
+ """
def test(a: 1, *args: 2, f:4='lala', **kwarg:3)->2: pass
test.__annotations__ #@
test.__kwdefaults__ #@
- ''')
+ """
+ )
annotations = next(ast_node[0].infer())
self.assertIsInstance(annotations, astroid.Dict)
- self.assertIsInstance(annotations.getitem(astroid.Const('return')), astroid.Const)
- self.assertEqual(annotations.getitem(astroid.Const('return')).value, 2)
- self.assertIsInstance(annotations.getitem(astroid.Const('a')), astroid.Const)
- self.assertEqual(annotations.getitem(astroid.Const('a')).value, 1)
- self.assertEqual(annotations.getitem(astroid.Const('args')).value, 2)
- self.assertEqual(annotations.getitem(astroid.Const('kwarg')).value, 3)
+ self.assertIsInstance(
+ annotations.getitem(astroid.Const("return")), astroid.Const
+ )
+ self.assertEqual(annotations.getitem(astroid.Const("return")).value, 2)
+ self.assertIsInstance(annotations.getitem(astroid.Const("a")), astroid.Const)
+ self.assertEqual(annotations.getitem(astroid.Const("a")).value, 1)
+ self.assertEqual(annotations.getitem(astroid.Const("args")).value, 2)
+ self.assertEqual(annotations.getitem(astroid.Const("kwarg")).value, 3)
- self.assertEqual(annotations.getitem(astroid.Const('f')).value, 4)
+ self.assertEqual(annotations.getitem(astroid.Const("f")).value, 4)
kwdefaults = next(ast_node[1].infer())
self.assertIsInstance(kwdefaults, astroid.Dict)
# self.assertEqual(kwdefaults.getitem('f').value, 'lala')
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_function_model_for_python2(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
def test(a=1):
"a"
@@ -467,13 +507,14 @@ class FunctionModelTest(unittest.TestCase):
test.func_defaults #@
test.func_code #@
test.func_closure #@
- ''')
+ """
+ )
name = next(ast_nodes[0].infer())
self.assertIsInstance(name, astroid.Const)
- self.assertEqual(name.value, 'test')
+ self.assertEqual(name.value, "test")
doc = next(ast_nodes[1].infer())
self.assertIsInstance(doc, astroid.Const)
- self.assertEqual(doc.value, 'a')
+ self.assertEqual(doc.value, "a")
pydict = next(ast_nodes[2].infer())
self.assertIsInstance(pydict, astroid.Dict)
pyglobals = next(ast_nodes[3].infer())
@@ -485,9 +526,9 @@ class FunctionModelTest(unittest.TestCase):
class GeneratorModelTest(unittest.TestCase):
-
def test_model(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
def test():
"a"
yield
@@ -498,30 +539,31 @@ class GeneratorModelTest(unittest.TestCase):
gen.gi_code #@
gen.gi_frame #@
gen.send #@
- ''')
+ """
+ )
name = next(ast_nodes[0].infer())
- self.assertEqual(name.value, 'test')
+ self.assertEqual(name.value, "test")
doc = next(ast_nodes[1].infer())
- self.assertEqual(doc.value, 'a')
+ self.assertEqual(doc.value, "a")
gi_code = next(ast_nodes[2].infer())
self.assertIsInstance(gi_code, astroid.ClassDef)
- self.assertEqual(gi_code.name, 'gi_code')
+ self.assertEqual(gi_code.name, "gi_code")
gi_frame = next(ast_nodes[3].infer())
self.assertIsInstance(gi_frame, astroid.ClassDef)
- self.assertEqual(gi_frame.name, 'gi_frame')
+ self.assertEqual(gi_frame.name, "gi_frame")
send = next(ast_nodes[4].infer())
self.assertIsInstance(send, astroid.BoundMethod)
class ExceptionModelTest(unittest.TestCase):
-
def test_model_py3(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
try:
x[42]
except ValueError as err:
@@ -529,41 +571,45 @@ class ExceptionModelTest(unittest.TestCase):
err.__traceback__ #@
err.message #@
- ''')
+ """
+ )
args = next(ast_nodes[0].infer())
self.assertIsInstance(args, astroid.Tuple)
tb = next(ast_nodes[1].infer())
self.assertIsInstance(tb, astroid.Instance)
- self.assertEqual(tb.name, 'traceback')
+ self.assertEqual(tb.name, "traceback")
with self.assertRaises(exceptions.InferenceError):
next(ast_nodes[2].infer())
class DictObjectModelTest(unittest.TestCase):
-
def test__class__(self):
- ast_node = builder.extract_node('{}.__class__')
+ ast_node = builder.extract_node("{}.__class__")
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, astroid.ClassDef)
- self.assertEqual(inferred.name, 'dict')
+ self.assertEqual(inferred.name, "dict")
def test_attributes_inferred_as_methods(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
{}.values #@
{}.items #@
{}.keys #@
- ''')
+ """
+ )
for node in ast_nodes:
inferred = next(node.infer())
self.assertIsInstance(inferred, astroid.BoundMethod)
def test_wrapper_objects_for_dict_methods_python3(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
{1:1, 2:3}.values() #@
{1:1, 2:3}.keys() #@
{1:1, 2:3}.items() #@
- ''')
+ """
+ )
values = next(ast_nodes[0].infer())
self.assertIsInstance(values, objects.DictValues)
self.assertEqual([elt.value for elt in values.elts], [1, 3])
@@ -575,9 +621,9 @@ class DictObjectModelTest(unittest.TestCase):
class LruCacheModelTest(unittest.TestCase):
-
def test_lru_cache(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
import functools
class Foo(object):
@functools.lru_cache()
@@ -587,15 +633,16 @@ class LruCacheModelTest(unittest.TestCase):
f.foo.cache_clear #@
f.foo.__wrapped__ #@
f.foo.cache_info() #@
- ''')
+ """
+ )
cache_clear = next(ast_nodes[0].infer())
self.assertIsInstance(cache_clear, astroid.BoundMethod)
wrapped = next(ast_nodes[1].infer())
self.assertIsInstance(wrapped, astroid.FunctionDef)
- self.assertEqual(wrapped.name, 'foo')
+ self.assertEqual(wrapped.name, "foo")
cache_info = next(ast_nodes[2].infer())
self.assertIsInstance(cache_info, astroid.Instance)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/tests/unittest_objects.py b/astroid/tests/unittest_objects.py
index d6de786e..8c56c9fd 100644
--- a/astroid/tests/unittest_objects.py
+++ b/astroid/tests/unittest_objects.py
@@ -15,12 +15,14 @@ from astroid import nodes
from astroid import objects
from astroid import test_utils
-class ObjectsTest(unittest.TestCase):
+class ObjectsTest(unittest.TestCase):
def test_frozenset(self):
- node = builder.extract_node("""
+ node = builder.extract_node(
+ """
frozenset({1: 2, 2: 3}) #@
- """)
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, objects.FrozenSet)
@@ -37,9 +39,9 @@ class ObjectsTest(unittest.TestCase):
class SuperTests(unittest.TestCase):
-
def test_inferring_super_outside_methods(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class Module(object):
pass
class StaticMethod(object):
@@ -51,7 +53,8 @@ class SuperTests(unittest.TestCase):
super(Module, Module) #@
# no argument super is not recognised outside methods as well.
super() #@
- ''')
+ """
+ )
in_static = next(ast_nodes[0].value.infer())
self.assertIsInstance(in_static, bases.Instance)
self.assertEqual(in_static.qname(), "%s.super" % bases.BUILTINS)
@@ -65,22 +68,26 @@ class SuperTests(unittest.TestCase):
self.assertEqual(no_arguments.qname(), "%s.super" % bases.BUILTINS)
def test_inferring_unbound_super_doesnt_work(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
class Test(object):
def __init__(self):
super(Test) #@
- ''')
+ """
+ )
unbounded = next(node.infer())
self.assertIsInstance(unbounded, bases.Instance)
self.assertEqual(unbounded.qname(), "%s.super" % bases.BUILTINS)
def test_use_default_inference_on_not_inferring_args(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class Test(object):
def __init__(self):
super(Lala, self) #@
super(Test, lala) #@
- ''')
+ """
+ )
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, bases.Instance)
self.assertEqual(first.qname(), "%s.super" % bases.BUILTINS)
@@ -89,28 +96,32 @@ class SuperTests(unittest.TestCase):
self.assertIsInstance(second, bases.Instance)
self.assertEqual(second.qname(), "%s.super" % bases.BUILTINS)
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_super_on_old_style_class(self):
# super doesn't work on old style class, but leave
# that as an error for pylint. We'll infer Super objects,
# but every call will result in a failure at some point.
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
class OldStyle:
def __init__(self):
super(OldStyle, self) #@
- ''')
+ """
+ )
old = next(node.infer())
self.assertIsInstance(old, objects.Super)
self.assertIsInstance(old.mro_pointer, nodes.ClassDef)
- self.assertEqual(old.mro_pointer.name, 'OldStyle')
+ self.assertEqual(old.mro_pointer.name, "OldStyle")
with self.assertRaises(exceptions.SuperError) as cm:
old.super_mro()
- self.assertEqual(str(cm.exception),
- "Unable to call super on old-style classes.")
+ self.assertEqual(
+ str(cm.exception), "Unable to call super on old-style classes."
+ )
- @test_utils.require_version(minver='3.0')
+ @test_utils.require_version(minver="3.0")
def test_no_arguments_super(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class First(object): pass
class Second(First):
def test(self):
@@ -118,23 +129,25 @@ class SuperTests(unittest.TestCase):
@classmethod
def test_classmethod(cls):
super() #@
- ''')
+ """
+ )
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, objects.Super)
self.assertIsInstance(first.type, bases.Instance)
- self.assertEqual(first.type.name, 'Second')
+ self.assertEqual(first.type.name, "Second")
self.assertIsInstance(first.mro_pointer, nodes.ClassDef)
- self.assertEqual(first.mro_pointer.name, 'Second')
+ self.assertEqual(first.mro_pointer.name, "Second")
second = next(ast_nodes[1].infer())
self.assertIsInstance(second, objects.Super)
self.assertIsInstance(second.type, nodes.ClassDef)
- self.assertEqual(second.type.name, 'Second')
+ self.assertEqual(second.type.name, "Second")
self.assertIsInstance(second.mro_pointer, nodes.ClassDef)
- self.assertEqual(second.mro_pointer.name, 'Second')
+ self.assertEqual(second.mro_pointer.name, "Second")
def test_super_simple_cases(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class First(object): pass
class Second(First): pass
class Third(First):
@@ -149,7 +162,8 @@ class SuperTests(unittest.TestCase):
class Fourth(Third):
pass
- ''')
+ """
+ )
# .type is the object which provides the mro.
# .mro_pointer is the position in the mro from where
@@ -159,48 +173,50 @@ class SuperTests(unittest.TestCase):
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, objects.Super)
self.assertIsInstance(first.type, bases.Instance)
- self.assertEqual(first.type.name, 'Third')
+ self.assertEqual(first.type.name, "Third")
self.assertIsInstance(first.mro_pointer, nodes.ClassDef)
- self.assertEqual(first.mro_pointer.name, 'Third')
+ self.assertEqual(first.mro_pointer.name, "Third")
# super(Second, self)
second = next(ast_nodes[1].infer())
self.assertIsInstance(second, objects.Super)
self.assertIsInstance(second.type, bases.Instance)
- self.assertEqual(second.type.name, 'Third')
+ self.assertEqual(second.type.name, "Third")
self.assertIsInstance(first.mro_pointer, nodes.ClassDef)
- self.assertEqual(second.mro_pointer.name, 'Second')
+ self.assertEqual(second.mro_pointer.name, "Second")
# super(Third, Third)
third = next(ast_nodes[2].infer())
self.assertIsInstance(third, objects.Super)
self.assertIsInstance(third.type, nodes.ClassDef)
- self.assertEqual(third.type.name, 'Third')
+ self.assertEqual(third.type.name, "Third")
self.assertIsInstance(third.mro_pointer, nodes.ClassDef)
- self.assertEqual(third.mro_pointer.name, 'Third')
+ self.assertEqual(third.mro_pointer.name, "Third")
# super(Third, second)
fourth = next(ast_nodes[3].infer())
self.assertIsInstance(fourth, objects.Super)
self.assertIsInstance(fourth.type, nodes.ClassDef)
- self.assertEqual(fourth.type.name, 'Second')
+ self.assertEqual(fourth.type.name, "Second")
self.assertIsInstance(fourth.mro_pointer, nodes.ClassDef)
- self.assertEqual(fourth.mro_pointer.name, 'Third')
+ self.assertEqual(fourth.mro_pointer.name, "Third")
# Super(Fourth, Fourth)
fifth = next(ast_nodes[4].infer())
self.assertIsInstance(fifth, objects.Super)
self.assertIsInstance(fifth.type, nodes.ClassDef)
- self.assertEqual(fifth.type.name, 'Fourth')
+ self.assertEqual(fifth.type.name, "Fourth")
self.assertIsInstance(fifth.mro_pointer, nodes.ClassDef)
- self.assertEqual(fifth.mro_pointer.name, 'Fourth')
+ self.assertEqual(fifth.mro_pointer.name, "Fourth")
def test_super_infer(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
class Super(object):
def __init__(self):
super(Super, self) #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, objects.Super)
reinferred = next(inferred.infer())
@@ -208,7 +224,8 @@ class SuperTests(unittest.TestCase):
self.assertIs(inferred, reinferred)
def test_inferring_invalid_supers(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class Super(object):
def __init__(self):
# MRO pointer is not a type
@@ -219,15 +236,15 @@ class SuperTests(unittest.TestCase):
super(Bupper, self) #@
class Bupper(Super):
pass
- ''')
+ """
+ )
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, objects.Super)
with self.assertRaises(exceptions.SuperError) as cm:
first.super_mro()
self.assertIsInstance(cm.exception.super_.mro_pointer, nodes.Const)
self.assertEqual(cm.exception.super_.mro_pointer.value, 1)
- for node, invalid_type in zip(ast_nodes[1:],
- (nodes.Const, bases.Instance)):
+ for node, invalid_type in zip(ast_nodes[1:], (nodes.Const, bases.Instance)):
inferred = next(node.infer())
self.assertIsInstance(inferred, objects.Super, node)
with self.assertRaises(exceptions.SuperError) as cm:
@@ -235,25 +252,28 @@ class SuperTests(unittest.TestCase):
self.assertIsInstance(cm.exception.super_.type, invalid_type)
def test_proxied(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
class Super(object):
def __init__(self):
super(Super, self) #@
- ''')
+ """
+ )
inferred = next(node.infer())
proxied = inferred._proxied
self.assertEqual(proxied.qname(), "%s.super" % bases.BUILTINS)
self.assertIsInstance(proxied, nodes.ClassDef)
def test_super_bound_model(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class First(object):
def method(self):
pass
@classmethod
def class_method(cls):
pass
- class Super_Type_Type(First):
+ class Super_Type_Type(First):
def method(self):
super(Super_Type_Type, Super_Type_Type).method #@
super(Super_Type_Type, Super_Type_Type).class_method #@
@@ -262,44 +282,46 @@ class SuperTests(unittest.TestCase):
super(Super_Type_Type, Super_Type_Type).method #@
super(Super_Type_Type, Super_Type_Type).class_method #@
- class Super_Type_Object(First):
+ class Super_Type_Object(First):
def method(self):
super(Super_Type_Object, self).method #@
super(Super_Type_Object, self).class_method #@
- ''')
+ """
+ )
# Super(type, type) is the same for both functions and classmethods.
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, nodes.FunctionDef)
- self.assertEqual(first.name, 'method')
+ self.assertEqual(first.name, "method")
second = next(ast_nodes[1].infer())
self.assertIsInstance(second, bases.BoundMethod)
- self.assertEqual(second.bound.name, 'First')
- self.assertEqual(second.type, 'classmethod')
+ self.assertEqual(second.bound.name, "First")
+ self.assertEqual(second.type, "classmethod")
third = next(ast_nodes[2].infer())
self.assertIsInstance(third, nodes.FunctionDef)
- self.assertEqual(third.name, 'method')
+ self.assertEqual(third.name, "method")
fourth = next(ast_nodes[3].infer())
self.assertIsInstance(fourth, bases.BoundMethod)
- self.assertEqual(fourth.bound.name, 'First')
- self.assertEqual(fourth.type, 'classmethod')
+ self.assertEqual(fourth.bound.name, "First")
+ self.assertEqual(fourth.type, "classmethod")
# Super(type, obj) can lead to different attribute bindings
# depending on the type of the place where super was called.
fifth = next(ast_nodes[4].infer())
self.assertIsInstance(fifth, bases.BoundMethod)
- self.assertEqual(fifth.bound.name, 'First')
- self.assertEqual(fifth.type, 'method')
+ self.assertEqual(fifth.bound.name, "First")
+ self.assertEqual(fifth.type, "method")
sixth = next(ast_nodes[5].infer())
self.assertIsInstance(sixth, bases.BoundMethod)
- self.assertEqual(sixth.bound.name, 'First')
- self.assertEqual(sixth.type, 'classmethod')
+ self.assertEqual(sixth.bound.name, "First")
+ self.assertEqual(sixth.type, "classmethod")
def test_super_getattr_single_inheritance(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class First(object):
def test(self): pass
class Second(First):
@@ -317,47 +339,51 @@ class SuperTests(unittest.TestCase):
super(Third, Third).test2 #@
super(Third, Third).test #@
- ''')
+ """
+ )
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, bases.BoundMethod)
- self.assertEqual(first.bound.name, 'Second')
+ self.assertEqual(first.bound.name, "Second")
second = next(ast_nodes[1].infer())
self.assertIsInstance(second, bases.BoundMethod)
- self.assertEqual(second.bound.name, 'First')
+ self.assertEqual(second.bound.name, "First")
with self.assertRaises(exceptions.InferenceError):
next(ast_nodes[2].infer())
fourth = next(ast_nodes[3].infer())
with self.assertRaises(exceptions.AttributeInferenceError):
- fourth.getattr('test3')
+ fourth.getattr("test3")
with self.assertRaises(exceptions.AttributeInferenceError):
- next(fourth.igetattr('test3'))
+ next(fourth.igetattr("test3"))
first_unbound = next(ast_nodes[4].infer())
self.assertIsInstance(first_unbound, nodes.FunctionDef)
- self.assertEqual(first_unbound.name, 'test2')
- self.assertEqual(first_unbound.parent.name, 'Second')
+ self.assertEqual(first_unbound.name, "test2")
+ self.assertEqual(first_unbound.parent.name, "Second")
second_unbound = next(ast_nodes[5].infer())
self.assertIsInstance(second_unbound, nodes.FunctionDef)
- self.assertEqual(second_unbound.name, 'test')
- self.assertEqual(second_unbound.parent.name, 'First')
+ self.assertEqual(second_unbound.name, "test")
+ self.assertEqual(second_unbound.parent.name, "First")
def test_super_invalid_mro(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
class A(object):
test = 42
class Super(A, A):
def __init__(self):
super(Super, self) #@
- ''')
+ """
+ )
inferred = next(node.infer())
with self.assertRaises(exceptions.AttributeInferenceError):
- next(inferred.getattr('test'))
+ next(inferred.getattr("test"))
def test_super_complex_mro(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class A(object):
def spam(self): return "A"
def foo(self): return "A"
@@ -375,64 +401,66 @@ class SuperTests(unittest.TestCase):
super(E, self).spam #@
super(E, self).foo #@
super(E, self).static #@
- ''')
+ """
+ )
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, bases.BoundMethod)
- self.assertEqual(first.bound.name, 'C')
+ self.assertEqual(first.bound.name, "C")
second = next(ast_nodes[1].infer())
self.assertIsInstance(second, bases.BoundMethod)
- self.assertEqual(second.bound.name, 'B')
+ self.assertEqual(second.bound.name, "B")
third = next(ast_nodes[2].infer())
self.assertIsInstance(third, bases.BoundMethod)
- self.assertEqual(third.bound.name, 'B')
+ self.assertEqual(third.bound.name, "B")
fourth = next(ast_nodes[3].infer())
- self.assertEqual(fourth.bound.name, 'A')
+ self.assertEqual(fourth.bound.name, "A")
static = next(ast_nodes[4].infer())
self.assertIsInstance(static, nodes.FunctionDef)
- self.assertEqual(static.parent.scope().name, 'A')
+ self.assertEqual(static.parent.scope().name, "A")
def test_super_data_model(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class X(object): pass
class A(X):
def __init__(self):
super(A, self) #@
super(A, A) #@
super(X, A) #@
- ''')
+ """
+ )
first = next(ast_nodes[0].infer())
- thisclass = first.getattr('__thisclass__')[0]
+ thisclass = first.getattr("__thisclass__")[0]
self.assertIsInstance(thisclass, nodes.ClassDef)
- self.assertEqual(thisclass.name, 'A')
- selfclass = first.getattr('__self_class__')[0]
+ self.assertEqual(thisclass.name, "A")
+ selfclass = first.getattr("__self_class__")[0]
self.assertIsInstance(selfclass, nodes.ClassDef)
- self.assertEqual(selfclass.name, 'A')
- self_ = first.getattr('__self__')[0]
+ self.assertEqual(selfclass.name, "A")
+ self_ = first.getattr("__self__")[0]
self.assertIsInstance(self_, bases.Instance)
- self.assertEqual(self_.name, 'A')
- cls = first.getattr('__class__')[0]
+ self.assertEqual(self_.name, "A")
+ cls = first.getattr("__class__")[0]
self.assertEqual(cls, first._proxied)
second = next(ast_nodes[1].infer())
- thisclass = second.getattr('__thisclass__')[0]
- self.assertEqual(thisclass.name, 'A')
- self_ = second.getattr('__self__')[0]
+ thisclass = second.getattr("__thisclass__")[0]
+ self.assertEqual(thisclass.name, "A")
+ self_ = second.getattr("__self__")[0]
self.assertIsInstance(self_, nodes.ClassDef)
- self.assertEqual(self_.name, 'A')
+ self.assertEqual(self_.name, "A")
third = next(ast_nodes[2].infer())
- thisclass = third.getattr('__thisclass__')[0]
- self.assertEqual(thisclass.name, 'X')
- selfclass = third.getattr('__self_class__')[0]
- self.assertEqual(selfclass.name, 'A')
+ thisclass = third.getattr("__thisclass__")[0]
+ self.assertEqual(thisclass.name, "X")
+ selfclass = third.getattr("__self_class__")[0]
+ self.assertEqual(selfclass.name, "A")
def assertEqualMro(self, klass, expected_mro):
- self.assertEqual(
- [member.name for member in klass.super_mro()],
- expected_mro)
+ self.assertEqual([member.name for member in klass.super_mro()], expected_mro)
def test_super_mro(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class A(object): pass
class B(A): pass
class C(A): pass
@@ -444,13 +472,14 @@ class SuperTests(unittest.TestCase):
super(B, 1) #@
super(1, B) #@
- ''')
+ """
+ )
first = next(ast_nodes[0].infer())
- self.assertEqualMro(first, ['C', 'B', 'A', 'object'])
+ self.assertEqualMro(first, ["C", "B", "A", "object"])
second = next(ast_nodes[1].infer())
- self.assertEqualMro(second, ['B', 'A', 'object'])
+ self.assertEqualMro(second, ["B", "A", "object"])
third = next(ast_nodes[2].infer())
- self.assertEqualMro(third, ['A', 'object'])
+ self.assertEqualMro(third, ["A", "object"])
fourth = next(ast_nodes[3].infer())
with self.assertRaises(exceptions.SuperError):
@@ -460,25 +489,29 @@ class SuperTests(unittest.TestCase):
fifth.super_mro()
def test_super_yes_objects(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
from collections import Missing
class A(object):
def __init__(self):
super(Missing, self) #@
super(A, Missing) #@
- ''')
+ """
+ )
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, bases.Instance)
second = next(ast_nodes[1].infer())
self.assertIsInstance(second, bases.Instance)
def test_super_invalid_types(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
import collections
class A(object):
def __init__(self):
super(A, collections) #@
- ''')
+ """
+ )
inferred = next(node.infer())
with self.assertRaises(exceptions.SuperError):
inferred.super_mro()
@@ -486,7 +519,8 @@ class SuperTests(unittest.TestCase):
inferred.super_mro()
def test_super_properties(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
class Foo(object):
@property
def dict(self):
@@ -498,7 +532,8 @@ class SuperTests(unittest.TestCase):
return super(Bar, self).dict
Bar().dict
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 42)
@@ -517,5 +552,5 @@ class SuperTests(unittest.TestCase):
self.assertEqual(super_obj.qname(), "super")
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/tests/unittest_protocols.py b/astroid/tests/unittest_protocols.py
index 2c6c380c..79648dcf 100644
--- a/astroid/tests/unittest_protocols.py
+++ b/astroid/tests/unittest_protocols.py
@@ -31,7 +31,6 @@ def _add_transform(manager, node, transform, predicate=None):
class ProtocolTests(unittest.TestCase):
-
def assertConstNodesEqual(self, nodes_list_expected, nodes_list_got):
self.assertEqual(len(nodes_list_expected), len(nodes_list_got))
for node in nodes_list_got:
@@ -47,33 +46,36 @@ class ProtocolTests(unittest.TestCase):
self.assertEqual(expected_name, node.name)
def test_assigned_stmts_simple_for(self):
- assign_stmts = extract_node("""
+ assign_stmts = extract_node(
+ """
for a in (1, 2, 3): #@
pass
for b in range(3): #@
pass
- """)
+ """
+ )
for1_assnode = next(assign_stmts[0].nodes_of_class(AssignName))
assigned = list(for1_assnode.assigned_stmts())
self.assertConstNodesEqual([1, 2, 3], assigned)
for2_assnode = next(assign_stmts[1].nodes_of_class(AssignName))
- self.assertRaises(InferenceError,
- list, for2_assnode.assigned_stmts())
+ self.assertRaises(InferenceError, list, for2_assnode.assigned_stmts())
- @require_version(minver='3.0')
+ @require_version(minver="3.0")
def test_assigned_stmts_starred_for(self):
- assign_stmts = extract_node("""
+ assign_stmts = extract_node(
+ """
for *a, b in ((1, 2, 3), (4, 5, 6, 7)): #@
pass
- """)
+ """
+ )
for1_starred = next(assign_stmts.nodes_of_class(Starred))
assigned = next(for1_starred.assigned_stmts())
assert isinstance(assigned, astroid.List)
- assert assigned.as_string() == '[1, 2]'
+ assert assigned.as_string() == "[1, 2]"
def _get_starred_stmts(self, code):
assign_stmt = extract_node("{} #@".format(code))
@@ -95,70 +97,72 @@ class ProtocolTests(unittest.TestCase):
starred = next(assign_stmt.nodes_of_class(Starred))
self.assertRaises(InferenceError, list, starred.assigned_stmts())
- @require_version(minver='3.0')
+ @require_version(minver="3.0")
def test_assigned_stmts_starred_assnames(self):
- self._helper_starred_expected_const(
- "a, *b = (1, 2, 3, 4) #@", [2, 3, 4])
- self._helper_starred_expected_const(
- "*a, b = (1, 2, 3) #@", [1, 2])
- self._helper_starred_expected_const(
- "a, *b, c = (1, 2, 3, 4, 5) #@",
- [2, 3, 4])
- self._helper_starred_expected_const(
- "a, *b = (1, 2) #@", [2])
- self._helper_starred_expected_const(
- "*b, a = (1, 2) #@", [1])
- self._helper_starred_expected_const(
- "[*b] = (1, 2) #@", [1, 2])
-
- @require_version(minver='3.0')
+ self._helper_starred_expected_const("a, *b = (1, 2, 3, 4) #@", [2, 3, 4])
+ self._helper_starred_expected_const("*a, b = (1, 2, 3) #@", [1, 2])
+ self._helper_starred_expected_const("a, *b, c = (1, 2, 3, 4, 5) #@", [2, 3, 4])
+ self._helper_starred_expected_const("a, *b = (1, 2) #@", [2])
+ self._helper_starred_expected_const("*b, a = (1, 2) #@", [1])
+ self._helper_starred_expected_const("[*b] = (1, 2) #@", [1, 2])
+
+ @require_version(minver="3.0")
def test_assigned_stmts_starred_yes(self):
# Not something iterable and known
self._helper_starred_expected("a, *b = range(3) #@", util.Uninferable)
# Not something inferrable
self._helper_starred_expected("a, *b = balou() #@", util.Uninferable)
# In function, unknown.
- self._helper_starred_expected("""
+ self._helper_starred_expected(
+ """
def test(arg):
- head, *tail = arg #@""", util.Uninferable)
+ head, *tail = arg #@""",
+ util.Uninferable,
+ )
# These cases aren't worth supporting.
self._helper_starred_expected(
- "a, (*b, c), d = (1, (2, 3, 4), 5) #@", util.Uninferable)
+ "a, (*b, c), d = (1, (2, 3, 4), 5) #@", util.Uninferable
+ )
- @require_version(minver='3.0')
+ @require_version(minver="3.0")
def test_assign_stmts_starred_fails(self):
# Too many starred
self._helper_starred_inference_error("a, *b, *c = (1, 2, 3) #@")
# This could be solved properly, but it complicates needlessly the
# code for assigned_stmts, without offering real benefit.
self._helper_starred_inference_error(
- "(*a, b), (c, *d) = (1, 2, 3), (4, 5, 6) #@")
+ "(*a, b), (c, *d) = (1, 2, 3), (4, 5, 6) #@"
+ )
def test_assigned_stmts_assignments(self):
- assign_stmts = extract_node("""
+ assign_stmts = extract_node(
+ """
c = a #@
d, e = b, c #@
- """)
+ """
+ )
simple_assnode = next(assign_stmts[0].nodes_of_class(AssignName))
assigned = list(simple_assnode.assigned_stmts())
- self.assertNameNodesEqual(['a'], assigned)
+ self.assertNameNodesEqual(["a"], assigned)
assnames = assign_stmts[1].nodes_of_class(AssignName)
simple_mul_assnode_1 = next(assnames)
assigned = list(simple_mul_assnode_1.assigned_stmts())
- self.assertNameNodesEqual(['b'], assigned)
+ self.assertNameNodesEqual(["b"], assigned)
simple_mul_assnode_2 = next(assnames)
assigned = list(simple_mul_assnode_2.assigned_stmts())
- self.assertNameNodesEqual(['c'], assigned)
+ self.assertNameNodesEqual(["c"], assigned)
- @require_version(minver='3.6')
+ @require_version(minver="3.6")
def test_assigned_stmts_annassignments(self):
- annassign_stmts = extract_node("""
+ annassign_stmts = extract_node(
+ """
a: str = "abc" #@
b: str #@
- """)
+ """
+ )
simple_annassign_node = next(annassign_stmts[0].nodes_of_class(AssignName))
assigned = list(simple_annassign_node.assigned_stmts())
self.assertEqual(1, len(assigned))
@@ -172,18 +176,19 @@ class ProtocolTests(unittest.TestCase):
def test_sequence_assigned_stmts_not_accepting_empty_node(self):
def transform(node):
- node.root().locals['__all__'] = [node.value]
+ node.root().locals["__all__"] = [node.value]
manager = astroid.MANAGER
with _add_transform(manager, astroid.Assign, transform):
- module = astroid.parse('''
+ module = astroid.parse(
+ """
__all__ = ['a']
- ''')
+ """
+ )
module.wildcard_import_names()
def test_not_passing_uninferable_in_seq_inference(self):
class Visitor:
-
def visit(self, node):
for child in node.get_children():
child.accept(self)
@@ -199,12 +204,14 @@ class ProtocolTests(unittest.TestCase):
for _ in node.infer():
pass
- parsed = extract_node("""
+ parsed = extract_node(
+ """
a = []
x = [a*2, a]*2*2
- """)
+ """
+ )
parsed.accept(Visitor())
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/tests/unittest_python3.py b/astroid/tests/unittest_python3.py
index 9b570858..6c36914e 100644
--- a/astroid/tests/unittest_python3.py
+++ b/astroid/tests/unittest_python3.py
@@ -26,21 +26,23 @@ class Python3TC(unittest.TestCase):
def setUpClass(cls):
cls.builder = AstroidBuilder()
- @require_version('3.4')
+ @require_version("3.4")
def test_starred_notation(self):
- astroid = self.builder.string_build("*a, b = [1, 2, 3]", 'test', 'test')
+ astroid = self.builder.string_build("*a, b = [1, 2, 3]", "test", "test")
# Get the star node
node = next(next(next(astroid.get_children()).get_children()).get_children())
self.assertTrue(isinstance(node.assign_type(), Assign))
- @require_version('3.4')
+ @require_version("3.4")
def test_yield_from(self):
- body = dedent("""
+ body = dedent(
+ """
def func():
yield from iter([1, 2])
- """)
+ """
+ )
astroid = self.builder.string_build(body)
func = astroid.body[0]
self.assertIsInstance(func, FunctionDef)
@@ -48,117 +50,143 @@ class Python3TC(unittest.TestCase):
self.assertIsInstance(yieldfrom_stmt, Expr)
self.assertIsInstance(yieldfrom_stmt.value, YieldFrom)
- self.assertEqual(yieldfrom_stmt.as_string(),
- 'yield from iter([1, 2])')
+ self.assertEqual(yieldfrom_stmt.as_string(), "yield from iter([1, 2])")
- @require_version('3.4')
+ @require_version("3.4")
def test_yield_from_is_generator(self):
- body = dedent("""
+ body = dedent(
+ """
def func():
yield from iter([1, 2])
- """)
+ """
+ )
astroid = self.builder.string_build(body)
func = astroid.body[0]
self.assertIsInstance(func, FunctionDef)
self.assertTrue(func.is_generator())
- @require_version('3.4')
+ @require_version("3.4")
def test_yield_from_as_string(self):
- body = dedent("""
+ body = dedent(
+ """
def func():
yield from iter([1, 2])
value = yield from other()
- """)
+ """
+ )
astroid = self.builder.string_build(body)
func = astroid.body[0]
self.assertEqual(func.as_string().strip(), body.strip())
# metaclass tests
- @require_version('3.4')
+ @require_version("3.4")
def test_simple_metaclass(self):
astroid = self.builder.string_build("class Test(metaclass=type): pass")
klass = astroid.body[0]
metaclass = klass.metaclass()
self.assertIsInstance(metaclass, ClassDef)
- self.assertEqual(metaclass.name, 'type')
+ self.assertEqual(metaclass.name, "type")
- @require_version('3.4')
+ @require_version("3.4")
def test_metaclass_error(self):
astroid = self.builder.string_build("class Test(metaclass=typ): pass")
klass = astroid.body[0]
self.assertFalse(klass.metaclass())
- @require_version('3.4')
+ @require_version("3.4")
def test_metaclass_imported(self):
- astroid = self.builder.string_build(dedent("""
+ astroid = self.builder.string_build(
+ dedent(
+ """
from abc import ABCMeta
- class Test(metaclass=ABCMeta): pass"""))
+ class Test(metaclass=ABCMeta): pass"""
+ )
+ )
klass = astroid.body[1]
metaclass = klass.metaclass()
self.assertIsInstance(metaclass, ClassDef)
- self.assertEqual(metaclass.name, 'ABCMeta')
+ self.assertEqual(metaclass.name, "ABCMeta")
- @require_version('3.4')
+ @require_version("3.4")
def test_metaclass_multiple_keywords(self):
- astroid = self.builder.string_build("class Test(magic=None, metaclass=type): pass")
+ astroid = self.builder.string_build(
+ "class Test(magic=None, metaclass=type): pass"
+ )
klass = astroid.body[0]
metaclass = klass.metaclass()
self.assertIsInstance(metaclass, ClassDef)
- self.assertEqual(metaclass.name, 'type')
+ self.assertEqual(metaclass.name, "type")
- @require_version('3.4')
+ @require_version("3.4")
def test_as_string(self):
- body = dedent("""
+ body = dedent(
+ """
from abc import ABCMeta
- class Test(metaclass=ABCMeta): pass""")
+ class Test(metaclass=ABCMeta): pass"""
+ )
astroid = self.builder.string_build(body)
klass = astroid.body[1]
- self.assertEqual(klass.as_string(),
- '\n\nclass Test(metaclass=ABCMeta):\n pass\n')
+ self.assertEqual(
+ klass.as_string(), "\n\nclass Test(metaclass=ABCMeta):\n pass\n"
+ )
- @require_version('3.4')
+ @require_version("3.4")
def test_old_syntax_works(self):
- astroid = self.builder.string_build(dedent("""
+ astroid = self.builder.string_build(
+ dedent(
+ """
class Test:
__metaclass__ = type
class SubTest(Test): pass
- """))
- klass = astroid['SubTest']
+ """
+ )
+ )
+ klass = astroid["SubTest"]
metaclass = klass.metaclass()
self.assertIsNone(metaclass)
- @require_version('3.4')
+ @require_version("3.4")
def test_metaclass_yes_leak(self):
- astroid = self.builder.string_build(dedent("""
+ astroid = self.builder.string_build(
+ dedent(
+ """
# notice `ab` instead of `abc`
from ab import ABCMeta
class Meta(metaclass=ABCMeta): pass
- """))
- klass = astroid['Meta']
+ """
+ )
+ )
+ klass = astroid["Meta"]
self.assertIsNone(klass.metaclass())
- @require_version('3.4')
+ @require_version("3.4")
def test_parent_metaclass(self):
- astroid = self.builder.string_build(dedent("""
+ astroid = self.builder.string_build(
+ dedent(
+ """
from abc import ABCMeta
class Test(metaclass=ABCMeta): pass
class SubTest(Test): pass
- """))
- klass = astroid['SubTest']
+ """
+ )
+ )
+ klass = astroid["SubTest"]
self.assertTrue(klass.newstyle)
metaclass = klass.metaclass()
self.assertIsInstance(metaclass, ClassDef)
- self.assertEqual(metaclass.name, 'ABCMeta')
+ self.assertEqual(metaclass.name, "ABCMeta")
- @require_version('3.4')
+ @require_version("3.4")
def test_metaclass_ancestors(self):
- astroid = self.builder.string_build(dedent("""
+ astroid = self.builder.string_build(
+ dedent(
+ """
from abc import ABCMeta
class FirstMeta(metaclass=ABCMeta): pass
@@ -172,11 +200,10 @@ class Python3TC(unittest.TestCase):
class SecondImpl(FirstImpl): pass
class ThirdImpl(Simple, SecondMeta):
pass
- """))
- classes = {
- 'ABCMeta': ('FirstImpl', 'SecondImpl'),
- 'type': ('ThirdImpl', )
- }
+ """
+ )
+ )
+ classes = {"ABCMeta": ("FirstImpl", "SecondImpl"), "type": ("ThirdImpl",)}
for metaclass, names in classes.items():
for name in names:
impl = astroid[name]
@@ -184,71 +211,87 @@ class Python3TC(unittest.TestCase):
self.assertIsInstance(meta, ClassDef)
self.assertEqual(meta.name, metaclass)
- @require_version('3.4')
+ @require_version("3.4")
def test_annotation_support(self):
- astroid = self.builder.string_build(dedent("""
+ astroid = self.builder.string_build(
+ dedent(
+ """
def test(a: int, b: str, c: None, d, e,
*args: float, **kwargs: int)->int:
pass
- """))
- func = astroid['test']
+ """
+ )
+ )
+ func = astroid["test"]
self.assertIsInstance(func.args.varargannotation, Name)
- self.assertEqual(func.args.varargannotation.name, 'float')
+ self.assertEqual(func.args.varargannotation.name, "float")
self.assertIsInstance(func.args.kwargannotation, Name)
- self.assertEqual(func.args.kwargannotation.name, 'int')
+ self.assertEqual(func.args.kwargannotation.name, "int")
self.assertIsInstance(func.returns, Name)
- self.assertEqual(func.returns.name, 'int')
+ self.assertEqual(func.returns.name, "int")
arguments = func.args
self.assertIsInstance(arguments.annotations[0], Name)
- self.assertEqual(arguments.annotations[0].name, 'int')
+ self.assertEqual(arguments.annotations[0].name, "int")
self.assertIsInstance(arguments.annotations[1], Name)
- self.assertEqual(arguments.annotations[1].name, 'str')
+ self.assertEqual(arguments.annotations[1].name, "str")
self.assertIsInstance(arguments.annotations[2], Const)
self.assertIsNone(arguments.annotations[2].value)
self.assertIsNone(arguments.annotations[3])
self.assertIsNone(arguments.annotations[4])
- astroid = self.builder.string_build(dedent("""
+ astroid = self.builder.string_build(
+ dedent(
+ """
def test(a: int=1, b: str=2):
pass
- """))
- func = astroid['test']
+ """
+ )
+ )
+ func = astroid["test"]
self.assertIsInstance(func.args.annotations[0], Name)
- self.assertEqual(func.args.annotations[0].name, 'int')
+ self.assertEqual(func.args.annotations[0].name, "int")
self.assertIsInstance(func.args.annotations[1], Name)
- self.assertEqual(func.args.annotations[1].name, 'str')
+ self.assertEqual(func.args.annotations[1].name, "str")
self.assertIsNone(func.returns)
- @require_version('3.4')
+ @require_version("3.4")
def test_kwonlyargs_annotations_supper(self):
- node = self.builder.string_build(dedent("""
+ node = self.builder.string_build(
+ dedent(
+ """
def test(*, a: int, b: str, c: None, d, e):
pass
- """))
- func = node['test']
+ """
+ )
+ )
+ func = node["test"]
arguments = func.args
self.assertIsInstance(arguments.kwonlyargs_annotations[0], Name)
- self.assertEqual(arguments.kwonlyargs_annotations[0].name, 'int')
+ self.assertEqual(arguments.kwonlyargs_annotations[0].name, "int")
self.assertIsInstance(arguments.kwonlyargs_annotations[1], Name)
- self.assertEqual(arguments.kwonlyargs_annotations[1].name, 'str')
+ self.assertEqual(arguments.kwonlyargs_annotations[1].name, "str")
self.assertIsInstance(arguments.kwonlyargs_annotations[2], Const)
self.assertIsNone(arguments.kwonlyargs_annotations[2].value)
self.assertIsNone(arguments.kwonlyargs_annotations[3])
self.assertIsNone(arguments.kwonlyargs_annotations[4])
- @require_version('3.4')
+ @require_version("3.4")
def test_annotation_as_string(self):
- code1 = dedent('''
+ code1 = dedent(
+ """
def test(a, b:int=4, c=2, f:'lala'=4)->2:
- pass''')
- code2 = dedent('''
+ pass"""
+ )
+ code2 = dedent(
+ """
def test(a:typing.Generic[T], c:typing.Any=24)->typing.Iterable:
- pass''')
+ pass"""
+ )
for code in (code1, code2):
func = extract_node(code)
self.assertEqual(func.as_string(), code)
- @require_version('3.5')
+ @require_version("3.5")
def test_unpacking_in_dicts(self):
code = "{'x': 1, **{'y': 2}}"
node = extract_node(code)
@@ -257,46 +300,50 @@ class Python3TC(unittest.TestCase):
self.assertIsInstance(keys[0], nodes.Const)
self.assertIsInstance(keys[1], nodes.DictUnpack)
- @require_version('3.5')
+ @require_version("3.5")
def test_nested_unpacking_in_dicts(self):
code = "{'x': 1, **{'y': 2, **{'z': 3}}}"
node = extract_node(code)
self.assertEqual(node.as_string(), code)
- @require_version('3.5')
+ @require_version("3.5")
def test_unpacking_in_dict_getitem(self):
- node = extract_node('{1:2, **{2:3, 3:4}, **{5: 6}}')
+ node = extract_node("{1:2, **{2:3, 3:4}, **{5: 6}}")
for key, expected in ((1, 2), (2, 3), (3, 4), (5, 6)):
value = node.getitem(nodes.Const(key))
self.assertIsInstance(value, nodes.Const)
self.assertEqual(value.value, expected)
- @require_version('3.6')
+ @require_version("3.6")
def test_format_string(self):
code = "f'{greetings} {person}'"
node = extract_node(code)
self.assertEqual(node.as_string(), code)
- @require_version('3.6')
+ @require_version("3.6")
def test_underscores_in_numeral_literal(self):
- pairs = [
- ('10_1000', 101000),
- ('10_000_000', 10000000),
- ('0x_FF_FF', 65535),
- ]
+ pairs = [("10_1000", 101000), ("10_000_000", 10000000), ("0x_FF_FF", 65535)]
for value, expected in pairs:
node = extract_node(value)
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, expected)
- @require_version('3.6')
+ @require_version("3.6")
def test_async_comprehensions(self):
async_comprehensions = [
- extract_node("async def f(): return __([i async for i in aiter() if i % 2])"),
- extract_node("async def f(): return __({i async for i in aiter() if i % 2})"),
- extract_node("async def f(): return __((i async for i in aiter() if i % 2))"),
- extract_node("async def f(): return __({i: i async for i in aiter() if i % 2})")
+ extract_node(
+ "async def f(): return __([i async for i in aiter() if i % 2])"
+ ),
+ extract_node(
+ "async def f(): return __({i async for i in aiter() if i % 2})"
+ ),
+ extract_node(
+ "async def f(): return __((i async for i in aiter() if i % 2))"
+ ),
+ extract_node(
+ "async def f(): return __({i: i async for i in aiter() if i % 2})"
+ ),
]
non_async_comprehensions = [
extract_node("async def f(): return __({i: i for i in iter() if i % 2})")
@@ -307,7 +354,7 @@ class Python3TC(unittest.TestCase):
for comp in non_async_comprehensions:
self.assertFalse(comp.generators[0].is_async)
- @require_version('3.7')
+ @require_version("3.7")
def test_async_comprehensions_outside_coroutine(self):
# When async and await will become keywords, async comprehensions
# will be allowed outside of coroutines body
@@ -331,7 +378,7 @@ class Python3TC(unittest.TestCase):
node = extract_node(comp)
self.assertTrue(node.generators[0].is_async)
- @require_version('3.6')
+ @require_version("3.6")
def test_async_comprehensions_as_string(self):
func_bodies = [
"return [i async for i in aiter() if condition(i)]",
@@ -349,12 +396,16 @@ class Python3TC(unittest.TestCase):
"return {fun: await fun() async for fun in funcs if await smth}",
]
for func_body in func_bodies:
- code = dedent('''
+ code = dedent(
+ """
async def f():
- {}'''.format(func_body))
+ {}""".format(
+ func_body
+ )
+ )
func = extract_node(code)
self.assertEqual(func.as_string().strip(), code.strip())
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/tests/unittest_raw_building.py b/astroid/tests/unittest_raw_building.py
index 38f33200..97d0441b 100644
--- a/astroid/tests/unittest_raw_building.py
+++ b/astroid/tests/unittest_raw_building.py
@@ -13,56 +13,57 @@ import unittest
from astroid.builder import AstroidBuilder
from astroid.raw_building import (
- attach_dummy_node, build_module,
- build_class, build_function, build_from_import
+ attach_dummy_node,
+ build_module,
+ build_class,
+ build_function,
+ build_from_import,
)
from astroid import test_utils
class RawBuildingTC(unittest.TestCase):
-
def test_attach_dummy_node(self):
- node = build_module('MyModule')
- attach_dummy_node(node, 'DummyNode')
+ node = build_module("MyModule")
+ attach_dummy_node(node, "DummyNode")
self.assertEqual(1, len(list(node.get_children())))
def test_build_module(self):
- node = build_module('MyModule')
- self.assertEqual(node.name, 'MyModule')
+ node = build_module("MyModule")
+ self.assertEqual(node.name, "MyModule")
self.assertEqual(node.pure_python, False)
self.assertEqual(node.package, False)
self.assertEqual(node.parent, None)
def test_build_class(self):
- node = build_class('MyClass')
- self.assertEqual(node.name, 'MyClass')
+ node = build_class("MyClass")
+ self.assertEqual(node.name, "MyClass")
self.assertEqual(node.doc, None)
def test_build_function(self):
- node = build_function('MyFunction')
- self.assertEqual(node.name, 'MyFunction')
+ node = build_function("MyFunction")
+ self.assertEqual(node.name, "MyFunction")
self.assertEqual(node.doc, None)
def test_build_function_args(self):
- args = ['myArgs1', 'myArgs2']
- node = build_function('MyFunction', args)
- self.assertEqual('myArgs1', node.args.args[0].name)
- self.assertEqual('myArgs2', node.args.args[1].name)
+ args = ["myArgs1", "myArgs2"]
+ 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']
- node = build_function('MyFunction', None, defaults)
+ defaults = ["defaults1", "defaults2"]
+ node = build_function("MyFunction", None, defaults)
self.assertEqual(2, len(node.args.defaults))
def test_build_from_import(self):
- names = ['exceptions, inference, inspector']
- node = build_from_import('astroid', names)
+ names = ["exceptions, inference, inspector"]
+ node = build_from_import("astroid", names)
self.assertEqual(len(names), len(node.names))
- @unittest.skipIf(platform.python_implementation() == 'PyPy',
- 'Only affects CPython')
- @test_utils.require_version(minver='3.0')
+ @unittest.skipIf(platform.python_implementation() == "PyPy", "Only affects CPython")
+ @test_utils.require_version(minver="3.0")
def test_io_is__io(self):
# _io module calls itself io. This leads
# to cyclic dependencies when astroid tries to resolve
@@ -73,9 +74,9 @@ class RawBuildingTC(unittest.TestCase):
builder = AstroidBuilder()
module = builder.inspect_build(_io)
- buffered_reader = module.getattr('BufferedReader')[0]
- self.assertEqual(buffered_reader.root().name, 'io')
+ buffered_reader = module.getattr("BufferedReader")[0]
+ self.assertEqual(buffered_reader.root().name, "io")
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/tests/unittest_regrtest.py b/astroid/tests/unittest_regrtest.py
index 376f7da8..b83fa69f 100644
--- a/astroid/tests/unittest_regrtest.py
+++ b/astroid/tests/unittest_regrtest.py
@@ -26,11 +26,9 @@ from astroid.tests import resources
from astroid import transforms
-class NonRegressionTests(resources.AstroidCacheSetupMixin,
- unittest.TestCase):
-
+class NonRegressionTests(resources.AstroidCacheSetupMixin, unittest.TestCase):
def setUp(self):
- sys.path.insert(0, resources.find('data'))
+ sys.path.insert(0, resources.find("data"))
MANAGER.always_load_extensions = True
MANAGER.astroid_cache[BUILTINS] = self._builtins
@@ -41,7 +39,7 @@ class NonRegressionTests(resources.AstroidCacheSetupMixin,
MANAGER.clear_cache(self._builtins)
MANAGER.always_load_extensions = False
sys.path.pop(0)
- sys.path_importer_cache.pop(resources.find('data'), None)
+ sys.path_importer_cache.pop(resources.find("data"), None)
def brainless_manager(self):
manager = AstroidManager()
@@ -52,48 +50,46 @@ class NonRegressionTests(resources.AstroidCacheSetupMixin,
manager.astroid_cache = {}
manager._mod_file_cache = {}
manager._transform = transforms.TransformVisitor()
- manager.clear_cache() # trigger proper bootstraping
+ manager.clear_cache() # trigger proper bootstraping
return manager
def test_module_path(self):
man = self.brainless_manager()
- mod = man.ast_from_module_name('package.import_package_subpackage_module')
- package = next(mod.igetattr('package'))
- self.assertEqual(package.name, 'package')
- subpackage = next(package.igetattr('subpackage'))
+ mod = man.ast_from_module_name("package.import_package_subpackage_module")
+ package = next(mod.igetattr("package"))
+ self.assertEqual(package.name, "package")
+ subpackage = next(package.igetattr("subpackage"))
self.assertIsInstance(subpackage, nodes.Module)
self.assertTrue(subpackage.package)
- self.assertEqual(subpackage.name, 'package.subpackage')
- module = next(subpackage.igetattr('module'))
- self.assertEqual(module.name, 'package.subpackage.module')
-
+ self.assertEqual(subpackage.name, "package.subpackage")
+ module = next(subpackage.igetattr("module"))
+ self.assertEqual(module.name, "package.subpackage.module")
def test_package_sidepackage(self):
manager = self.brainless_manager()
- assert 'package.sidepackage' not in MANAGER.astroid_cache
- package = manager.ast_from_module_name('absimp')
+ assert "package.sidepackage" not in MANAGER.astroid_cache
+ package = manager.ast_from_module_name("absimp")
self.assertIsInstance(package, nodes.Module)
self.assertTrue(package.package)
- subpackage = next(package.getattr('sidepackage')[0].infer())
+ subpackage = next(package.getattr("sidepackage")[0].infer())
self.assertIsInstance(subpackage, nodes.Module)
self.assertTrue(subpackage.package)
- self.assertEqual(subpackage.name, 'absimp.sidepackage')
-
+ self.assertEqual(subpackage.name, "absimp.sidepackage")
def test_living_property(self):
builder = AstroidBuilder()
builder._done = {}
builder._module = sys.modules[__name__]
- builder.object_build(build_module('module_name', ''), Whatever)
+ builder.object_build(build_module("module_name", ""), Whatever)
def test_numpy_crash(self):
"""test don't crash on numpy"""
- #a crash occurred somewhere in the past, and an
+ # a crash occurred somewhere in the past, and an
# InferenceError instead of a crash was better, but now we even infer!
try:
- import numpy # pylint: disable=unused-import
+ import numpy # pylint: disable=unused-import
except ImportError:
- self.skipTest('test skipped: numpy is not available')
+ self.skipTest("test skipped: numpy is not available")
builder = AstroidBuilder()
data = """
from numpy import multiply
@@ -105,13 +101,13 @@ multiply(1, 2, 3)
inferred = callfunc.inferred()
self.assertEqual(len(inferred), 1)
- @require_version('3.0')
+ @require_version("3.0")
def test_nameconstant(self):
# used to fail for Python 3.4
builder = AstroidBuilder()
astroid = builder.string_build("def test(x=True): pass")
default = astroid.body[0].args.args[0]
- self.assertEqual(default.name, 'x')
+ self.assertEqual(default.name, "x")
self.assertEqual(next(default.infer()).value, True)
def test_recursion_regression_issue25(self):
@@ -133,7 +129,7 @@ def run():
classes = astroid.nodes_of_class(nodes.ClassDef)
for klass in classes:
# triggers the _is_metaclass call
- klass.type # pylint: disable=pointless-statement
+ klass.type # pylint: disable=pointless-statement
def test_decorator_callchain_issue42(self):
builder = AstroidBuilder()
@@ -151,7 +147,7 @@ def crash():
pass
"""
astroid = builder.string_build(data, __name__, __file__)
- self.assertEqual(astroid['crash'].type, 'function')
+ self.assertEqual(astroid["crash"].type, "function")
def test_filter_stmts_scoping(self):
builder = AstroidBuilder()
@@ -164,14 +160,16 @@ def test():
return compiler
"""
astroid = builder.string_build(data, __name__, __file__)
- test = astroid['test']
+ test = astroid["test"]
result = next(test.infer_call_result(astroid))
self.assertIsInstance(result, Instance)
base = next(result._proxied.bases[0].infer())
- self.assertEqual(base.name, 'int')
+ self.assertEqual(base.name, "int")
def test_ancestors_patching_class_recursion(self):
- node = AstroidBuilder().string_build(textwrap.dedent("""
+ node = AstroidBuilder().string_build(
+ textwrap.dedent(
+ """
import string
Template = string.Template
@@ -186,16 +184,19 @@ def test():
string.Template = A
else:
string.Template = B
- """))
- klass = node['A']
+ """
+ )
+ )
+ klass = node["A"]
ancestors = list(klass.ancestors())
- self.assertEqual(ancestors[0].qname(), 'string.Template')
+ self.assertEqual(ancestors[0].qname(), "string.Template")
def test_ancestors_yes_in_bases(self):
# Test for issue https://bitbucket.org/logilab/astroid/issue/84
# This used to crash astroid with a TypeError, because an Uninferable
# node was present in the bases
- node = extract_node("""
+ node = extract_node(
+ """
def with_metaclass(meta, *bases):
class metaclass(meta):
def __new__(cls, name, this_bases, d):
@@ -206,19 +207,21 @@ def test():
class A(with_metaclass(object, lala.lala)): #@
pass
- """)
+ """
+ )
ancestors = list(node.ancestors())
self.assertEqual(len(ancestors), 1)
- self.assertEqual(ancestors[0].qname(),
- "{}.object".format(BUILTINS))
+ self.assertEqual(ancestors[0].qname(), "{}.object".format(BUILTINS))
def test_ancestors_missing_from_function(self):
# Test for https://www.logilab.org/ticket/122793
- node = extract_node('''
+ node = extract_node(
+ """
def gen(): yield
GEN = gen()
next(GEN)
- ''')
+ """
+ )
self.assertRaises(exceptions.InferenceError, next, node.infer())
def test_unicode_in_docstring(self):
@@ -226,7 +229,8 @@ def test():
# Test for https://bitbucket.org/logilab/astroid/issues/273/
# In a regular file, "coding: utf-8" would have been used.
- node = extract_node('''
+ node = extract_node(
+ """
from __future__ import unicode_literals
class MyClass(object):
@@ -234,26 +238,31 @@ def test():
"With unicode : %s "
instance = MyClass()
- ''' % "\u2019")
+ """
+ % "\u2019"
+ )
next(node.value.infer()).as_string()
def test_binop_generates_nodes_with_parents(self):
- node = extract_node('''
+ node = extract_node(
+ """
def no_op(*args):
pass
def foo(*args):
def inner(*more_args):
args + more_args #@
return inner
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Tuple)
self.assertIsNotNone(inferred.parent)
self.assertIsInstance(inferred.parent, nodes.BinOp)
def test_decorator_names_inference_error_leaking(self):
- node = extract_node('''
+ node = extract_node(
+ """
class Parent(object):
@property
def foo(self):
@@ -263,38 +272,46 @@ def test():
@Parent.foo.getter
def foo(self): #@
return super(Child, self).foo + ['oink']
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertEqual(inferred.decoratornames(), set())
def test_ssl_protocol(self):
- node = extract_node('''
+ node = extract_node(
+ """
import ssl
ssl.PROTOCOL_TLSv1
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Const)
def test_recursive_property_method(self):
- node = extract_node('''
+ node = extract_node(
+ """
class APropert():
@property
def property(self):
return self
APropert().property
- ''')
+ """
+ )
next(node.infer())
def test_uninferable_string_argument_of_namedtuple(self):
- node = extract_node('''
+ node = extract_node(
+ """
import collections
collections.namedtuple('{}'.format("a"), '')()
- ''')
+ """
+ )
next(node.infer())
- @require_version(maxver='3.0')
+ @require_version(maxver="3.0")
def test_reassignment_in_except_handler(self):
- node = extract_node('''
+ node = extract_node(
+ """
import exceptions
try:
{}["a"]
@@ -302,7 +319,8 @@ def test():
pass
IndexError #@
- ''')
+ """
+ )
self.assertEqual(len(node.inferred()), 1)
@@ -310,5 +328,5 @@ class Whatever:
a = property(lambda x: x, lambda x: x)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/tests/unittest_scoped_nodes.py b/astroid/tests/unittest_scoped_nodes.py
index 33f151cf..5c78a5b5 100644
--- a/astroid/tests/unittest_scoped_nodes.py
+++ b/astroid/tests/unittest_scoped_nodes.py
@@ -31,16 +31,17 @@ from astroid import nodes
from astroid import scoped_nodes
from astroid import util
from astroid.exceptions import (
- InferenceError, AttributeInferenceError,
- NoDefault, ResolveError, MroError,
- InconsistentMroError, DuplicateBasesError,
+ InferenceError,
+ AttributeInferenceError,
+ NoDefault,
+ ResolveError,
+ MroError,
+ InconsistentMroError,
+ DuplicateBasesError,
TooManyLevelsError,
- NameInferenceError
-)
-from astroid.bases import (
- BUILTINS, Instance,
- BoundMethod, UnboundMethod, Generator
+ NameInferenceError,
)
+from astroid.bases import BUILTINS, Instance, BoundMethod, UnboundMethod, Generator
from astroid import test_utils
from astroid.tests import resources
@@ -57,233 +58,244 @@ def _test_dict_interface(self, node, test_attr):
class ModuleLoader(resources.SysPathSetup):
def setUp(self):
super(ModuleLoader, self).setUp()
- self.module = resources.build_file('data/module.py', 'data.module')
- self.module2 = resources.build_file('data/module2.py', 'data.module2')
- self.nonregr = resources.build_file('data/nonregr.py', 'data.nonregr')
- self.pack = resources.build_file('data/__init__.py', 'data')
+ self.module = resources.build_file("data/module.py", "data.module")
+ self.module2 = resources.build_file("data/module2.py", "data.module2")
+ self.nonregr = resources.build_file("data/nonregr.py", "data.nonregr")
+ self.pack = resources.build_file("data/__init__.py", "data")
class ModuleNodeTest(ModuleLoader, unittest.TestCase):
-
def test_special_attributes(self):
- self.assertEqual(len(self.module.getattr('__name__')), 1)
- self.assertIsInstance(self.module.getattr('__name__')[0], nodes.Const)
- self.assertEqual(self.module.getattr('__name__')[0].value, 'data.module')
- self.assertEqual(len(self.module.getattr('__doc__')), 1)
- self.assertIsInstance(self.module.getattr('__doc__')[0], nodes.Const)
- self.assertEqual(self.module.getattr('__doc__')[0].value, 'test module for astroid\n')
- self.assertEqual(len(self.module.getattr('__file__')), 1)
- self.assertIsInstance(self.module.getattr('__file__')[0], nodes.Const)
- self.assertEqual(self.module.getattr('__file__')[0].value,
- os.path.abspath(resources.find('data/module.py')))
- self.assertEqual(len(self.module.getattr('__dict__')), 1)
- self.assertIsInstance(self.module.getattr('__dict__')[0], nodes.Dict)
- self.assertRaises(AttributeInferenceError, self.module.getattr, '__path__')
- self.assertEqual(len(self.pack.getattr('__path__')), 1)
- self.assertIsInstance(self.pack.getattr('__path__')[0], nodes.List)
+ self.assertEqual(len(self.module.getattr("__name__")), 1)
+ self.assertIsInstance(self.module.getattr("__name__")[0], nodes.Const)
+ self.assertEqual(self.module.getattr("__name__")[0].value, "data.module")
+ self.assertEqual(len(self.module.getattr("__doc__")), 1)
+ self.assertIsInstance(self.module.getattr("__doc__")[0], nodes.Const)
+ self.assertEqual(
+ self.module.getattr("__doc__")[0].value, "test module for astroid\n"
+ )
+ self.assertEqual(len(self.module.getattr("__file__")), 1)
+ self.assertIsInstance(self.module.getattr("__file__")[0], nodes.Const)
+ self.assertEqual(
+ self.module.getattr("__file__")[0].value,
+ os.path.abspath(resources.find("data/module.py")),
+ )
+ self.assertEqual(len(self.module.getattr("__dict__")), 1)
+ self.assertIsInstance(self.module.getattr("__dict__")[0], nodes.Dict)
+ self.assertRaises(AttributeInferenceError, self.module.getattr, "__path__")
+ self.assertEqual(len(self.pack.getattr("__path__")), 1)
+ self.assertIsInstance(self.pack.getattr("__path__")[0], nodes.List)
def test_dict_interface(self):
- _test_dict_interface(self, self.module, 'YO')
+ _test_dict_interface(self, self.module, "YO")
def test_getattr(self):
- yo = self.module.getattr('YO')[0]
+ yo = self.module.getattr("YO")[0]
self.assertIsInstance(yo, nodes.ClassDef)
- self.assertEqual(yo.name, 'YO')
- red = next(self.module.igetattr('redirect'))
+ self.assertEqual(yo.name, "YO")
+ red = next(self.module.igetattr("redirect"))
self.assertIsInstance(red, nodes.FunctionDef)
- self.assertEqual(red.name, 'four_args')
- namenode = next(self.module.igetattr('NameNode'))
+ self.assertEqual(red.name, "four_args")
+ namenode = next(self.module.igetattr("NameNode"))
self.assertIsInstance(namenode, nodes.ClassDef)
- self.assertEqual(namenode.name, 'Name')
+ self.assertEqual(namenode.name, "Name")
# resolve packageredirection
- mod = resources.build_file('data/appl/myConnection.py',
- 'data.appl.myConnection')
- ssl = next(mod.igetattr('SSL1'))
- cnx = next(ssl.igetattr('Connection'))
+ mod = resources.build_file(
+ "data/appl/myConnection.py", "data.appl.myConnection"
+ )
+ ssl = next(mod.igetattr("SSL1"))
+ cnx = next(ssl.igetattr("Connection"))
self.assertEqual(cnx.__class__, nodes.ClassDef)
- self.assertEqual(cnx.name, 'Connection')
- self.assertEqual(cnx.root().name, 'data.SSL1.Connection1')
- self.assertEqual(len(self.nonregr.getattr('enumerate')), 2)
- self.assertRaises(InferenceError, self.nonregr.igetattr, 'YOAA')
+ self.assertEqual(cnx.name, "Connection")
+ self.assertEqual(cnx.root().name, "data.SSL1.Connection1")
+ self.assertEqual(len(self.nonregr.getattr("enumerate")), 2)
+ self.assertRaises(InferenceError, self.nonregr.igetattr, "YOAA")
def test_wildcard_import_names(self):
- m = resources.build_file('data/all.py', 'all')
- self.assertEqual(m.wildcard_import_names(), ['Aaa', '_bla', 'name'])
- m = resources.build_file('data/notall.py', 'notall')
+ m = resources.build_file("data/all.py", "all")
+ self.assertEqual(m.wildcard_import_names(), ["Aaa", "_bla", "name"])
+ m = resources.build_file("data/notall.py", "notall")
res = sorted(m.wildcard_import_names())
- self.assertEqual(res, ['Aaa', 'func', 'name', 'other'])
+ self.assertEqual(res, ["Aaa", "func", "name", "other"])
def test_public_names(self):
- m = builder.parse('''
+ m = builder.parse(
+ """
name = 'a'
_bla = 2
other = 'o'
class Aaa: pass
def func(): print('yo')
__all__ = 'Aaa', '_bla', 'name'
- ''')
- values = sorted(['Aaa', 'name', 'other', 'func'])
+ """
+ )
+ values = sorted(["Aaa", "name", "other", "func"])
self.assertEqual(sorted(m.public_names()), values)
- m = builder.parse('''
+ m = builder.parse(
+ """
name = 'a'
_bla = 2
other = 'o'
class Aaa: pass
def func(): return 'yo'
- ''')
+ """
+ )
res = sorted(m.public_names())
self.assertEqual(res, values)
- m = builder.parse('''
+ m = builder.parse(
+ """
from missing import tzop
trop = "test"
__all__ = (trop, "test1", tzop, 42)
- ''')
+ """
+ )
res = sorted(m.public_names())
self.assertEqual(res, ["trop", "tzop"])
- m = builder.parse('''
+ m = builder.parse(
+ """
test = tzop = 42
__all__ = ('test', ) + ('tzop', )
- ''')
+ """
+ )
res = sorted(m.public_names())
- self.assertEqual(res, ['test', 'tzop'])
+ self.assertEqual(res, ["test", "tzop"])
def test_module_getattr(self):
- data = '''
+ data = """
appli = application
appli += 2
del appli
- '''
+ """
astroid = builder.parse(data, __name__)
# test del statement not returned by getattr
- self.assertEqual(len(astroid.getattr('appli')), 2,
- astroid.getattr('appli'))
+ self.assertEqual(len(astroid.getattr("appli")), 2, astroid.getattr("appli"))
def test_relative_to_absolute_name(self):
# package
- mod = nodes.Module('very.multi.package', 'doc')
+ mod = nodes.Module("very.multi.package", "doc")
mod.package = True
- modname = mod.relative_to_absolute_name('utils', 1)
- self.assertEqual(modname, 'very.multi.package.utils')
- modname = mod.relative_to_absolute_name('utils', 2)
- self.assertEqual(modname, 'very.multi.utils')
- modname = mod.relative_to_absolute_name('utils', 0)
- self.assertEqual(modname, 'very.multi.package.utils')
- modname = mod.relative_to_absolute_name('', 1)
- self.assertEqual(modname, 'very.multi.package')
+ modname = mod.relative_to_absolute_name("utils", 1)
+ self.assertEqual(modname, "very.multi.package.utils")
+ modname = mod.relative_to_absolute_name("utils", 2)
+ self.assertEqual(modname, "very.multi.utils")
+ modname = mod.relative_to_absolute_name("utils", 0)
+ self.assertEqual(modname, "very.multi.package.utils")
+ modname = mod.relative_to_absolute_name("", 1)
+ self.assertEqual(modname, "very.multi.package")
# non package
- mod = nodes.Module('very.multi.module', 'doc')
+ mod = nodes.Module("very.multi.module", "doc")
mod.package = False
- modname = mod.relative_to_absolute_name('utils', 0)
- self.assertEqual(modname, 'very.multi.utils')
- modname = mod.relative_to_absolute_name('utils', 1)
- self.assertEqual(modname, 'very.multi.utils')
- modname = mod.relative_to_absolute_name('utils', 2)
- self.assertEqual(modname, 'very.utils')
- modname = mod.relative_to_absolute_name('', 1)
- self.assertEqual(modname, 'very.multi')
+ modname = mod.relative_to_absolute_name("utils", 0)
+ self.assertEqual(modname, "very.multi.utils")
+ modname = mod.relative_to_absolute_name("utils", 1)
+ self.assertEqual(modname, "very.multi.utils")
+ modname = mod.relative_to_absolute_name("utils", 2)
+ self.assertEqual(modname, "very.utils")
+ modname = mod.relative_to_absolute_name("", 1)
+ self.assertEqual(modname, "very.multi")
def test_relative_to_absolute_name_beyond_top_level(self):
- mod = nodes.Module('a.b.c', '')
+ mod = nodes.Module("a.b.c", "")
mod.package = True
for level in (5, 4):
with self.assertRaises(TooManyLevelsError) as cm:
- mod.relative_to_absolute_name('test', level)
+ mod.relative_to_absolute_name("test", level)
- expected = ("Relative import with too many levels "
- "({level}) for module {name!r}".format(
- level=level - 1, name=mod.name))
+ expected = (
+ "Relative import with too many levels "
+ "({level}) for module {name!r}".format(level=level - 1, name=mod.name)
+ )
self.assertEqual(expected, str(cm.exception))
def test_import_1(self):
- data = '''from . import subpackage'''
- sys.path.insert(0, resources.find('data'))
- astroid = builder.parse(data, 'package', 'data/package/__init__.py')
+ data = """from . import subpackage"""
+ sys.path.insert(0, resources.find("data"))
+ astroid = builder.parse(data, "package", "data/package/__init__.py")
try:
- m = astroid.import_module('', level=1)
- self.assertEqual(m.name, 'package')
- inferred = list(astroid.igetattr('subpackage'))
+ m = astroid.import_module("", level=1)
+ self.assertEqual(m.name, "package")
+ inferred = list(astroid.igetattr("subpackage"))
self.assertEqual(len(inferred), 1)
- self.assertEqual(inferred[0].name, 'package.subpackage')
+ self.assertEqual(inferred[0].name, "package.subpackage")
finally:
del sys.path[0]
-
def test_import_2(self):
- data = '''from . import subpackage as pouet'''
- astroid = builder.parse(data, 'package', 'data/package/__init__.py')
- sys.path.insert(0, resources.find('data'))
+ data = """from . import subpackage as pouet"""
+ astroid = builder.parse(data, "package", "data/package/__init__.py")
+ sys.path.insert(0, resources.find("data"))
try:
- m = astroid.import_module('', level=1)
- self.assertEqual(m.name, 'package')
- inferred = list(astroid.igetattr('pouet'))
+ m = astroid.import_module("", level=1)
+ self.assertEqual(m.name, "package")
+ inferred = list(astroid.igetattr("pouet"))
self.assertEqual(len(inferred), 1)
- self.assertEqual(inferred[0].name, 'package.subpackage')
+ self.assertEqual(inferred[0].name, "package.subpackage")
finally:
del sys.path[0]
-
def test_file_stream_in_memory(self):
- data = '''irrelevant_variable is irrelevant'''
- astroid = builder.parse(data, 'in_memory')
+ data = """irrelevant_variable is irrelevant"""
+ astroid = builder.parse(data, "in_memory")
with astroid.stream() as stream:
self.assertEqual(stream.read().decode(), data)
def test_file_stream_physical(self):
- path = resources.find('data/all.py')
- astroid = builder.AstroidBuilder().file_build(path, 'all')
- with open(path, 'rb') as file_io:
+ path = resources.find("data/all.py")
+ astroid = builder.AstroidBuilder().file_build(path, "all")
+ with open(path, "rb") as file_io:
with astroid.stream() as stream:
self.assertEqual(stream.read(), file_io.read())
def test_file_stream_api(self):
- path = resources.find('data/all.py')
- astroid = builder.AstroidBuilder().file_build(path, 'all')
+ path = resources.find("data/all.py")
+ astroid = builder.AstroidBuilder().file_build(path, "all")
with self.assertRaises(AttributeError):
# pylint: disable=pointless-statement,no-member
astroid.file_stream
def test_stream_api(self):
- path = resources.find('data/all.py')
- astroid = builder.AstroidBuilder().file_build(path, 'all')
+ path = resources.find("data/all.py")
+ astroid = builder.AstroidBuilder().file_build(path, "all")
stream = astroid.stream()
- self.assertTrue(hasattr(stream, 'close'))
+ self.assertTrue(hasattr(stream, "close"))
with stream:
- with open(path, 'rb') as file_io:
+ with open(path, "rb") as file_io:
self.assertEqual(stream.read(), file_io.read())
class FunctionNodeTest(ModuleLoader, unittest.TestCase):
-
def test_special_attributes(self):
- func = self.module2['make_class']
- self.assertEqual(len(func.getattr('__name__')), 1)
- self.assertIsInstance(func.getattr('__name__')[0], nodes.Const)
- self.assertEqual(func.getattr('__name__')[0].value, 'make_class')
- self.assertEqual(len(func.getattr('__doc__')), 1)
- self.assertIsInstance(func.getattr('__doc__')[0], nodes.Const)
- self.assertEqual(func.getattr('__doc__')[0].value,
- 'check base is correctly resolved to Concrete0')
- self.assertEqual(len(self.module.getattr('__dict__')), 1)
- self.assertIsInstance(self.module.getattr('__dict__')[0], nodes.Dict)
+ func = self.module2["make_class"]
+ self.assertEqual(len(func.getattr("__name__")), 1)
+ self.assertIsInstance(func.getattr("__name__")[0], nodes.Const)
+ self.assertEqual(func.getattr("__name__")[0].value, "make_class")
+ self.assertEqual(len(func.getattr("__doc__")), 1)
+ self.assertIsInstance(func.getattr("__doc__")[0], nodes.Const)
+ self.assertEqual(
+ func.getattr("__doc__")[0].value,
+ "check base is correctly resolved to Concrete0",
+ )
+ self.assertEqual(len(self.module.getattr("__dict__")), 1)
+ self.assertIsInstance(self.module.getattr("__dict__")[0], nodes.Dict)
def test_dict_interface(self):
- _test_dict_interface(self, self.module['global_access'], 'local')
+ _test_dict_interface(self, self.module["global_access"], "local")
def test_default_value(self):
- func = self.module2['make_class']
- self.assertIsInstance(func.args.default_value('base'), nodes.Attribute)
- self.assertRaises(NoDefault, func.args.default_value, 'args')
- self.assertRaises(NoDefault, func.args.default_value, 'kwargs')
- self.assertRaises(NoDefault, func.args.default_value, 'any')
- #self.assertIsInstance(func.mularg_class('args'), nodes.Tuple)
- #self.assertIsInstance(func.mularg_class('kwargs'), nodes.Dict)
- #self.assertIsNone(func.mularg_class('base'))
+ func = self.module2["make_class"]
+ self.assertIsInstance(func.args.default_value("base"), nodes.Attribute)
+ self.assertRaises(NoDefault, func.args.default_value, "args")
+ self.assertRaises(NoDefault, func.args.default_value, "kwargs")
+ self.assertRaises(NoDefault, func.args.default_value, "any")
+ # self.assertIsInstance(func.mularg_class('args'), nodes.Tuple)
+ # self.assertIsInstance(func.mularg_class('kwargs'), nodes.Dict)
+ # self.assertIsNone(func.mularg_class('base'))
def test_navigation(self):
- function = self.module['global_access']
+ function = self.module["global_access"]
self.assertEqual(function.statement(), function)
l_sibling = function.previous_sibling()
# check taking parent if child is not a stmt
@@ -292,7 +304,7 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
self.assertIs(l_sibling, child.previous_sibling())
r_sibling = function.next_sibling()
self.assertIsInstance(r_sibling, nodes.ClassDef)
- self.assertEqual(r_sibling.name, 'YO')
+ self.assertEqual(r_sibling.name, "YO")
self.assertIs(r_sibling, child.next_sibling())
last = r_sibling.next_sibling().next_sibling().next_sibling()
self.assertIsInstance(last, nodes.Assign)
@@ -303,55 +315,63 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
def test_nested_args(self):
if sys.version_info >= (3, 0):
self.skipTest("nested args has been removed in py3.x")
- code = '''
+ code = """
def nested_args(a, (b, c, d)):
"nested arguments test"
- '''
+ """
tree = builder.parse(code)
- func = tree['nested_args']
- self.assertEqual(sorted(func.locals), ['a', 'b', 'c', 'd'])
- self.assertEqual(func.args.format_args(), 'a, (b, c, d)')
+ func = tree["nested_args"]
+ self.assertEqual(sorted(func.locals), ["a", "b", "c", "d"])
+ self.assertEqual(func.args.format_args(), "a, (b, c, d)")
def test_four_args(self):
- func = self.module['four_args']
+ func = self.module["four_args"]
local = sorted(func.keys())
- self.assertEqual(local, ['a', 'b', 'c', 'd'])
- self.assertEqual(func.type, 'function')
+ self.assertEqual(local, ["a", "b", "c", "d"])
+ self.assertEqual(func.type, "function")
def test_format_args(self):
- func = self.module2['make_class']
- self.assertEqual(func.args.format_args(),
- 'any, base=data.module.YO, *args, **kwargs')
- func = self.module['four_args']
- self.assertEqual(func.args.format_args(), 'a, b, c, d')
+ func = self.module2["make_class"]
+ self.assertEqual(
+ func.args.format_args(), "any, base=data.module.YO, *args, **kwargs"
+ )
+ func = self.module["four_args"]
+ self.assertEqual(func.args.format_args(), "a, b, c, d")
- @test_utils.require_version('3.0')
+ @test_utils.require_version("3.0")
def test_format_args_keyword_only_args(self):
- node = builder.parse('''
+ node = (
+ builder.parse(
+ """
def test(a: int, *, b: dict):
pass
- ''').body[-1].args
+ """
+ )
+ .body[-1]
+ .args
+ )
formatted = node.format_args()
- self.assertEqual(formatted, 'a:int, *, b:dict')
+ self.assertEqual(formatted, "a:int, *, b:dict")
def test_is_generator(self):
- self.assertTrue(self.module2['generator'].is_generator())
- self.assertFalse(self.module2['not_a_generator'].is_generator())
- self.assertFalse(self.module2['make_class'].is_generator())
+ self.assertTrue(self.module2["generator"].is_generator())
+ self.assertFalse(self.module2["not_a_generator"].is_generator())
+ self.assertFalse(self.module2["make_class"].is_generator())
def test_is_abstract(self):
- method = self.module2['AbstractClass']['to_override']
+ method = self.module2["AbstractClass"]["to_override"]
self.assertTrue(method.is_abstract(pass_is_abstract=False))
- self.assertEqual(method.qname(), 'data.module2.AbstractClass.to_override')
- self.assertEqual(method.pytype(), '%s.instancemethod' % BUILTINS)
- method = self.module2['AbstractClass']['return_something']
+ self.assertEqual(method.qname(), "data.module2.AbstractClass.to_override")
+ self.assertEqual(method.pytype(), "%s.instancemethod" % BUILTINS)
+ method = self.module2["AbstractClass"]["return_something"]
self.assertFalse(method.is_abstract(pass_is_abstract=False))
# non regression : test raise "string" doesn't cause an exception in is_abstract
- func = self.module2['raise_string']
+ func = self.module2["raise_string"]
self.assertFalse(func.is_abstract(pass_is_abstract=False))
def test_is_abstract_decorated(self):
- methods = builder.extract_node("""
+ methods = builder.extract_node(
+ """
import abc
class Klass(object):
@@ -367,37 +387,38 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
@some_other_decorator
def method2(self): #@
pass
- """)
+ """
+ )
self.assertTrue(methods[0].is_abstract(pass_is_abstract=False))
self.assertTrue(methods[1].is_abstract(pass_is_abstract=False))
self.assertFalse(methods[2].is_abstract(pass_is_abstract=False))
-## def test_raises(self):
-## method = self.module2['AbstractClass']['to_override']
-## self.assertEqual([str(term) for term in method.raises()],
-## ["Call(Name('NotImplementedError'), [], None, None)"] )
+ ## def test_raises(self):
+ ## method = self.module2['AbstractClass']['to_override']
+ ## self.assertEqual([str(term) for term in method.raises()],
+ ## ["Call(Name('NotImplementedError'), [], None, None)"] )
-## def test_returns(self):
-## method = self.module2['AbstractClass']['return_something']
-## # use string comp since Node doesn't handle __cmp__
-## self.assertEqual([str(term) for term in method.returns()],
-## ["Const('toto')", "Const(None)"])
+ ## def test_returns(self):
+ ## method = self.module2['AbstractClass']['return_something']
+ ## # use string comp since Node doesn't handle __cmp__
+ ## self.assertEqual([str(term) for term in method.returns()],
+ ## ["Const('toto')", "Const(None)"])
def test_lambda_pytype(self):
- data = '''
+ data = """
def f():
g = lambda: None
- '''
+ """
astroid = builder.parse(data)
- g = list(astroid['f'].ilookup('g'))[0]
- self.assertEqual(g.pytype(), '%s.function' % BUILTINS)
+ g = list(astroid["f"].ilookup("g"))[0]
+ self.assertEqual(g.pytype(), "%s.function" % BUILTINS)
def test_lambda_qname(self):
- astroid = builder.parse('lmbd = lambda: None', __name__)
- self.assertEqual('%s.<lambda>' % __name__, astroid['lmbd'].parent.value.qname())
+ astroid = builder.parse("lmbd = lambda: None", __name__)
+ self.assertEqual("%s.<lambda>" % __name__, astroid["lmbd"].parent.value.qname())
def test_is_method(self):
- data = '''
+ data = """
class A:
def meth1(self):
return 1
@@ -414,30 +435,30 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
@staticmethod
def sfunction():
return -1
- '''
+ """
astroid = builder.parse(data)
- self.assertTrue(astroid['A']['meth1'].is_method())
- self.assertTrue(astroid['A']['meth2'].is_method())
- self.assertTrue(astroid['A']['meth3'].is_method())
- self.assertFalse(astroid['function'].is_method())
- self.assertFalse(astroid['sfunction'].is_method())
+ self.assertTrue(astroid["A"]["meth1"].is_method())
+ self.assertTrue(astroid["A"]["meth2"].is_method())
+ self.assertTrue(astroid["A"]["meth3"].is_method())
+ self.assertFalse(astroid["function"].is_method())
+ self.assertFalse(astroid["sfunction"].is_method())
def test_argnames(self):
if sys.version_info < (3, 0):
- code = 'def f(a, (b, c), *args, **kwargs): pass'
+ code = "def f(a, (b, c), *args, **kwargs): pass"
else:
- code = 'def f(a, b, c, *args, **kwargs): pass'
+ code = "def f(a, b, c, *args, **kwargs): pass"
astroid = builder.parse(code, __name__)
- self.assertEqual(astroid['f'].argnames(), ['a', 'b', 'c', 'args', 'kwargs'])
+ self.assertEqual(astroid["f"].argnames(), ["a", "b", "c", "args", "kwargs"])
def test_return_nothing(self):
"""test inferred value on a function with empty return"""
- data = '''
+ data = """
def func():
return
a = func()
- '''
+ """
astroid = builder.parse(data)
call = astroid.body[1].value
func_vals = call.inferred()
@@ -454,16 +475,17 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
test.bar = 1
test()
"""
- astroid = builder.parse(data, 'mod')
+ astroid = builder.parse(data, "mod")
func = astroid.body[2].value.func.inferred()[0]
self.assertIsInstance(func, nodes.FunctionDef)
- self.assertEqual(func.name, 'test')
- one = func.getattr('bar')[0].inferred()[0]
+ self.assertEqual(func.name, "test")
+ one = func.getattr("bar")[0].inferred()[0]
self.assertIsInstance(one, nodes.Const)
self.assertEqual(one.value, 1)
def test_type_builtin_descriptor_subclasses(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
class classonlymethod(classmethod):
pass
class staticonlymethod(staticmethod):
@@ -482,19 +504,17 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
@staticmethod
def stcmethod(cls):
pass
- """)
- node = astroid.locals['Node'][0]
- self.assertEqual(node.locals['clsmethod_subclass'][0].type,
- 'classmethod')
- self.assertEqual(node.locals['clsmethod'][0].type,
- 'classmethod')
- self.assertEqual(node.locals['staticmethod_subclass'][0].type,
- 'staticmethod')
- self.assertEqual(node.locals['stcmethod'][0].type,
- 'staticmethod')
+ """
+ )
+ node = astroid.locals["Node"][0]
+ self.assertEqual(node.locals["clsmethod_subclass"][0].type, "classmethod")
+ self.assertEqual(node.locals["clsmethod"][0].type, "classmethod")
+ self.assertEqual(node.locals["staticmethod_subclass"][0].type, "staticmethod")
+ self.assertEqual(node.locals["stcmethod"][0].type, "staticmethod")
def test_decorator_builtin_descriptors(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
def static_decorator(platform=None, order=50):
def wrapper(f):
f.cgm_module = True
@@ -553,181 +573,196 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
def staticmethod_wrapped():
pass
@long_classmethod_decorator()
- def long_classmethod(cls):
+ def long_classmethod(cls):
pass
- """)
- node = astroid.locals['SomeClass'][0]
- self.assertEqual(node.locals['static'][0].type,
- 'staticmethod')
- self.assertEqual(node.locals['classmethod'][0].type,
- 'classmethod')
- self.assertEqual(node.locals['not_so_static'][0].type,
- 'method')
- self.assertEqual(node.locals['not_so_classmethod'][0].type,
- 'method')
- self.assertEqual(node.locals['classmethod_wrapped'][0].type,
- 'classmethod')
- self.assertEqual(node.locals['staticmethod_wrapped'][0].type,
- 'staticmethod')
- self.assertEqual(node.locals['long_classmethod'][0].type,
- 'classmethod')
+ """
+ )
+ node = astroid.locals["SomeClass"][0]
+ self.assertEqual(node.locals["static"][0].type, "staticmethod")
+ self.assertEqual(node.locals["classmethod"][0].type, "classmethod")
+ self.assertEqual(node.locals["not_so_static"][0].type, "method")
+ self.assertEqual(node.locals["not_so_classmethod"][0].type, "method")
+ self.assertEqual(node.locals["classmethod_wrapped"][0].type, "classmethod")
+ self.assertEqual(node.locals["staticmethod_wrapped"][0].type, "staticmethod")
+ self.assertEqual(node.locals["long_classmethod"][0].type, "classmethod")
def test_igetattr(self):
- func = builder.extract_node('''
+ func = builder.extract_node(
+ """
def test():
pass
- ''')
- func.instance_attrs['value'] = [nodes.Const(42)]
- value = func.getattr('value')
+ """
+ )
+ func.instance_attrs["value"] = [nodes.Const(42)]
+ value = func.getattr("value")
self.assertEqual(len(value), 1)
self.assertIsInstance(value[0], nodes.Const)
self.assertEqual(value[0].value, 42)
- inferred = next(func.igetattr('value'))
+ inferred = next(func.igetattr("value"))
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 42)
- @test_utils.require_version(minver='3.0')
+ @test_utils.require_version(minver="3.0")
def test_return_annotation_is_not_the_last(self):
- func = builder.extract_node('''
+ func = builder.extract_node(
+ """
def test() -> bytes:
pass
pass
return
- ''')
+ """
+ )
last_child = func.last_child()
self.assertIsInstance(last_child, nodes.Return)
self.assertEqual(func.tolineno, 5)
- @test_utils.require_version(minver='3.6')
+ @test_utils.require_version(minver="3.6")
def test_method_init_subclass(self):
- klass = builder.extract_node('''
+ klass = builder.extract_node(
+ """
class MyClass:
def __init_subclass__(cls):
pass
- ''')
- method = klass['__init_subclass__']
- self.assertEqual([n.name for n in method.args.args], ['cls'])
- self.assertEqual(method.type, 'classmethod')
+ """
+ )
+ method = klass["__init_subclass__"]
+ self.assertEqual([n.name for n in method.args.args], ["cls"])
+ self.assertEqual(method.type, "classmethod")
- @test_utils.require_version(minver='3.0')
+ @test_utils.require_version(minver="3.0")
def test_dunder_class_local_to_method(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
class MyClass:
def test(self):
__class__ #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.ClassDef)
- self.assertEqual(inferred.name, 'MyClass')
+ self.assertEqual(inferred.name, "MyClass")
- @test_utils.require_version(minver='3.0')
+ @test_utils.require_version(minver="3.0")
def test_dunder_class_local_to_function(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
def test(self):
__class__ #@
- ''')
+ """
+ )
with self.assertRaises(NameInferenceError):
next(node.infer())
- @test_utils.require_version(minver='3.0')
+ @test_utils.require_version(minver="3.0")
def test_dunder_class_local_to_classmethod(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
class MyClass:
@classmethod
def test(cls):
__class__ #@
- ''')
+ """
+ )
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.ClassDef)
- self.assertEqual(inferred.name, 'MyClass')
+ self.assertEqual(inferred.name, "MyClass")
class ClassNodeTest(ModuleLoader, unittest.TestCase):
-
def test_dict_interface(self):
- _test_dict_interface(self, self.module['YOUPI'], 'method')
+ _test_dict_interface(self, self.module["YOUPI"], "method")
def test_cls_special_attributes_1(self):
- cls = self.module['YO']
- self.assertEqual(len(cls.getattr('__bases__')), 1)
- self.assertEqual(len(cls.getattr('__name__')), 1)
- self.assertIsInstance(cls.getattr('__name__')[0], nodes.Const)
- self.assertEqual(cls.getattr('__name__')[0].value, 'YO')
- self.assertEqual(len(cls.getattr('__doc__')), 1)
- self.assertIsInstance(cls.getattr('__doc__')[0], nodes.Const)
- self.assertEqual(cls.getattr('__doc__')[0].value, 'hehe\n haha')
+ cls = self.module["YO"]
+ self.assertEqual(len(cls.getattr("__bases__")), 1)
+ self.assertEqual(len(cls.getattr("__name__")), 1)
+ self.assertIsInstance(cls.getattr("__name__")[0], nodes.Const)
+ self.assertEqual(cls.getattr("__name__")[0].value, "YO")
+ self.assertEqual(len(cls.getattr("__doc__")), 1)
+ self.assertIsInstance(cls.getattr("__doc__")[0], nodes.Const)
+ self.assertEqual(cls.getattr("__doc__")[0].value, "hehe\n haha")
# YO is an old styled class for Python 2.7
# May want to stop locals from referencing namespaced variables in the future
module_attr_num = 4 if sys.version_info > (3, 3) else 1
- self.assertEqual(len(cls.getattr('__module__')), module_attr_num)
- self.assertIsInstance(cls.getattr('__module__')[0], nodes.Const)
- self.assertEqual(cls.getattr('__module__')[0].value, 'data.module')
- self.assertEqual(len(cls.getattr('__dict__')), 1)
+ self.assertEqual(len(cls.getattr("__module__")), module_attr_num)
+ self.assertIsInstance(cls.getattr("__module__")[0], nodes.Const)
+ self.assertEqual(cls.getattr("__module__")[0].value, "data.module")
+ self.assertEqual(len(cls.getattr("__dict__")), 1)
if not cls.newstyle:
- self.assertRaises(AttributeInferenceError, cls.getattr, '__mro__')
+ self.assertRaises(AttributeInferenceError, cls.getattr, "__mro__")
for cls in (nodes.List._proxied, nodes.Const(1)._proxied):
- self.assertEqual(len(cls.getattr('__bases__')), 1)
- self.assertEqual(len(cls.getattr('__name__')), 1)
- self.assertEqual(len(cls.getattr('__doc__')), 1, (cls, cls.getattr('__doc__')))
- self.assertEqual(cls.getattr('__doc__')[0].value, cls.doc)
- self.assertEqual(len(cls.getattr('__module__')), 4)
- self.assertEqual(len(cls.getattr('__dict__')), 1)
- self.assertEqual(len(cls.getattr('__mro__')), 1)
+ self.assertEqual(len(cls.getattr("__bases__")), 1)
+ self.assertEqual(len(cls.getattr("__name__")), 1)
+ self.assertEqual(
+ len(cls.getattr("__doc__")), 1, (cls, cls.getattr("__doc__"))
+ )
+ self.assertEqual(cls.getattr("__doc__")[0].value, cls.doc)
+ self.assertEqual(len(cls.getattr("__module__")), 4)
+ self.assertEqual(len(cls.getattr("__dict__")), 1)
+ self.assertEqual(len(cls.getattr("__mro__")), 1)
def test__mro__attribute(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
class A(object): pass
class B(object): pass
- class C(A, B): pass
- ''')
- mro = node.getattr('__mro__')[0]
+ class C(A, B): pass
+ """
+ )
+ mro = node.getattr("__mro__")[0]
self.assertIsInstance(mro, nodes.Tuple)
self.assertEqual(mro.elts, node.mro())
def test__bases__attribute(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
class A(object): pass
class B(object): pass
class C(A, B): pass
class D(C): pass
- ''')
- bases = node.getattr('__bases__')[0]
+ """
+ )
+ bases = node.getattr("__bases__")[0]
self.assertIsInstance(bases, nodes.Tuple)
self.assertEqual(len(bases.elts), 1)
self.assertIsInstance(bases.elts[0], nodes.ClassDef)
- self.assertEqual(bases.elts[0].name, 'C')
+ self.assertEqual(bases.elts[0].name, "C")
def test_cls_special_attributes_2(self):
- astroid = builder.parse('''
+ astroid = builder.parse(
+ """
class A(object): pass
class B(object): pass
A.__bases__ += (B,)
- ''', __name__)
- self.assertEqual(len(astroid['A'].getattr('__bases__')), 2)
- self.assertIsInstance(astroid['A'].getattr('__bases__')[1], nodes.Tuple)
- self.assertIsInstance(astroid['A'].getattr('__bases__')[0], nodes.AssignAttr)
+ """,
+ __name__,
+ )
+ self.assertEqual(len(astroid["A"].getattr("__bases__")), 2)
+ self.assertIsInstance(astroid["A"].getattr("__bases__")[1], nodes.Tuple)
+ self.assertIsInstance(astroid["A"].getattr("__bases__")[0], nodes.AssignAttr)
def test_instance_special_attributes(self):
- for inst in (Instance(self.module['YO']), nodes.List(), nodes.Const(1)):
- self.assertRaises(AttributeInferenceError, inst.getattr, '__mro__')
- self.assertRaises(AttributeInferenceError, inst.getattr, '__bases__')
- self.assertRaises(AttributeInferenceError, inst.getattr, '__name__')
- self.assertEqual(len(inst.getattr('__dict__')), 1)
- self.assertEqual(len(inst.getattr('__doc__')), 1)
+ for inst in (Instance(self.module["YO"]), nodes.List(), nodes.Const(1)):
+ self.assertRaises(AttributeInferenceError, inst.getattr, "__mro__")
+ self.assertRaises(AttributeInferenceError, inst.getattr, "__bases__")
+ self.assertRaises(AttributeInferenceError, inst.getattr, "__name__")
+ self.assertEqual(len(inst.getattr("__dict__")), 1)
+ self.assertEqual(len(inst.getattr("__doc__")), 1)
def test_navigation(self):
- klass = self.module['YO']
+ klass = self.module["YO"]
self.assertEqual(klass.statement(), klass)
l_sibling = klass.previous_sibling()
self.assertTrue(isinstance(l_sibling, nodes.FunctionDef), l_sibling)
- self.assertEqual(l_sibling.name, 'global_access')
+ self.assertEqual(l_sibling.name, "global_access")
r_sibling = klass.next_sibling()
self.assertIsInstance(r_sibling, nodes.ClassDef)
- self.assertEqual(r_sibling.name, 'YOUPI')
+ self.assertEqual(r_sibling.name, "YOUPI")
def test_local_attr_ancestors(self):
- module = builder.parse('''
+ module = builder.parse(
+ """
class A():
def __init__(self): pass
class B(A): pass
@@ -735,84 +770,86 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
class D(object): pass
class F(): pass
class E(F, D): pass
- ''')
+ """
+ )
# Test old-style (Python 2) / new-style (Python 3+) ancestors lookups
- klass2 = module['C']
- it = klass2.local_attr_ancestors('__init__')
+ klass2 = module["C"]
+ it = klass2.local_attr_ancestors("__init__")
anc_klass = next(it)
self.assertIsInstance(anc_klass, nodes.ClassDef)
- self.assertEqual(anc_klass.name, 'A')
+ self.assertEqual(anc_klass.name, "A")
if sys.version_info[0] == 2:
self.assertRaises(StopIteration, partial(next, it))
else:
anc_klass = next(it)
self.assertIsInstance(anc_klass, nodes.ClassDef)
- self.assertEqual(anc_klass.name, 'object')
+ self.assertEqual(anc_klass.name, "object")
self.assertRaises(StopIteration, partial(next, it))
- it = klass2.local_attr_ancestors('method')
+ it = klass2.local_attr_ancestors("method")
self.assertRaises(StopIteration, partial(next, it))
# Test mixed-style ancestor lookups
- klass2 = module['E']
- it = klass2.local_attr_ancestors('__init__')
+ klass2 = module["E"]
+ it = klass2.local_attr_ancestors("__init__")
anc_klass = next(it)
self.assertIsInstance(anc_klass, nodes.ClassDef)
- self.assertEqual(anc_klass.name, 'object')
+ self.assertEqual(anc_klass.name, "object")
self.assertRaises(StopIteration, partial(next, it))
def test_local_attr_mro(self):
- module = builder.parse('''
+ module = builder.parse(
+ """
class A(object):
def __init__(self): pass
class B(A):
def __init__(self, arg, arg2): pass
class C(A): pass
class D(C, B): pass
- ''')
- dclass = module['D']
- init = dclass.local_attr('__init__')[0]
+ """
+ )
+ dclass = module["D"]
+ init = dclass.local_attr("__init__")[0]
self.assertIsInstance(init, nodes.FunctionDef)
- self.assertEqual(init.parent.name, 'B')
+ self.assertEqual(init.parent.name, "B")
- cclass = module['C']
- init = cclass.local_attr('__init__')[0]
+ cclass = module["C"]
+ init = cclass.local_attr("__init__")[0]
self.assertIsInstance(init, nodes.FunctionDef)
- self.assertEqual(init.parent.name, 'A')
+ self.assertEqual(init.parent.name, "A")
- ancestors = list(dclass.local_attr_ancestors('__init__'))
- self.assertEqual([node.name for node in ancestors], ['B', 'A', 'object'])
+ ancestors = list(dclass.local_attr_ancestors("__init__"))
+ self.assertEqual([node.name for node in ancestors], ["B", "A", "object"])
def test_instance_attr_ancestors(self):
- klass2 = self.module['YOUPI']
- it = klass2.instance_attr_ancestors('yo')
+ klass2 = self.module["YOUPI"]
+ it = klass2.instance_attr_ancestors("yo")
anc_klass = next(it)
self.assertIsInstance(anc_klass, nodes.ClassDef)
- self.assertEqual(anc_klass.name, 'YO')
+ self.assertEqual(anc_klass.name, "YO")
self.assertRaises(StopIteration, partial(next, it))
- klass2 = self.module['YOUPI']
- it = klass2.instance_attr_ancestors('member')
+ klass2 = self.module["YOUPI"]
+ it = klass2.instance_attr_ancestors("member")
self.assertRaises(StopIteration, partial(next, it))
def test_methods(self):
- expected_methods = {'__init__', 'class_method', 'method', 'static_method'}
- klass2 = self.module['YOUPI']
+ expected_methods = {"__init__", "class_method", "method", "static_method"}
+ klass2 = self.module["YOUPI"]
methods = {m.name for m in klass2.methods()}
- self.assertTrue(
- methods.issuperset(expected_methods))
+ self.assertTrue(methods.issuperset(expected_methods))
methods = {m.name for m in klass2.mymethods()}
self.assertSetEqual(expected_methods, methods)
- klass2 = self.module2['Specialization']
+ klass2 = self.module2["Specialization"]
methods = {m.name for m in klass2.mymethods()}
self.assertSetEqual(set(), methods)
- method_locals = klass2.local_attr('method')
+ method_locals = klass2.local_attr("method")
self.assertEqual(len(method_locals), 1)
- self.assertEqual(method_locals[0].name, 'method')
- self.assertRaises(AttributeInferenceError, klass2.local_attr, 'nonexistent')
+ self.assertEqual(method_locals[0].name, "method")
+ self.assertRaises(AttributeInferenceError, klass2.local_attr, "nonexistent")
methods = {m.name for m in klass2.methods()}
self.assertTrue(methods.issuperset(expected_methods))
- #def test_rhs(self):
+ # def test_rhs(self):
# my_dict = self.module['MY_DICT']
# self.assertIsInstance(my_dict.rhs(), nodes.Dict)
# a = self.module['YO']['a']
@@ -822,40 +859,39 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
@unittest.skipIf(sys.version_info[0] >= 3, "Python 2 class semantics required.")
def test_ancestors(self):
- klass = self.module['YOUPI']
- self.assertEqual(['YO'], [a.name for a in klass.ancestors()])
- klass = self.module2['Specialization']
- self.assertEqual(['YOUPI', 'YO'], [a.name for a in klass.ancestors()])
+ klass = self.module["YOUPI"]
+ self.assertEqual(["YO"], [a.name for a in klass.ancestors()])
+ klass = self.module2["Specialization"]
+ self.assertEqual(["YOUPI", "YO"], [a.name for a in klass.ancestors()])
@unittest.skipIf(sys.version_info[0] < 3, "Python 3 class semantics required.")
def test_ancestors_py3(self):
- klass = self.module['YOUPI']
- self.assertEqual(['YO', 'object'], [a.name for a in klass.ancestors()])
- klass = self.module2['Specialization']
- self.assertEqual(['YOUPI', 'YO', 'object'], [a.name for a in klass.ancestors()])
+ klass = self.module["YOUPI"]
+ self.assertEqual(["YO", "object"], [a.name for a in klass.ancestors()])
+ klass = self.module2["Specialization"]
+ self.assertEqual(["YOUPI", "YO", "object"], [a.name for a in klass.ancestors()])
def test_type(self):
- klass = self.module['YOUPI']
- self.assertEqual(klass.type, 'class')
- klass = self.module2['Metaclass']
- self.assertEqual(klass.type, 'metaclass')
- klass = self.module2['MyException']
- self.assertEqual(klass.type, 'exception')
- klass = self.module2['MyError']
- self.assertEqual(klass.type, 'exception')
+ klass = self.module["YOUPI"]
+ self.assertEqual(klass.type, "class")
+ klass = self.module2["Metaclass"]
+ self.assertEqual(klass.type, "metaclass")
+ klass = self.module2["MyException"]
+ self.assertEqual(klass.type, "exception")
+ klass = self.module2["MyError"]
+ self.assertEqual(klass.type, "exception")
# the following class used to be detected as a metaclass
# after the fix which used instance._proxied in .ancestors(),
# when in fact it is a normal class
- klass = self.module2['NotMetaclass']
- self.assertEqual(klass.type, 'class')
+ klass = self.module2["NotMetaclass"]
+ self.assertEqual(klass.type, "class")
def test_inner_classes(self):
- eee = self.nonregr['Ccc']['Eee']
- self.assertEqual([n.name for n in eee.ancestors()], ['Ddd', 'Aaa', 'object'])
-
+ eee = self.nonregr["Ccc"]["Eee"]
+ self.assertEqual([n.name for n in eee.ancestors()], ["Ddd", "Aaa", "object"])
def test_classmethod_attributes(self):
- data = '''
+ data = """
class WebAppObject(object):
def registered(cls, application):
cls.appli = application
@@ -863,43 +899,48 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
cls.config = application.config
return cls
registered = classmethod(registered)
- '''
+ """
astroid = builder.parse(data, __name__)
- cls = astroid['WebAppObject']
- assert_keys = ['__module__', '__qualname__', 'appli', 'config', 'registered', 'schema']
+ cls = astroid["WebAppObject"]
+ assert_keys = [
+ "__module__",
+ "__qualname__",
+ "appli",
+ "config",
+ "registered",
+ "schema",
+ ]
if sys.version_info < (3, 3):
- assert_keys.pop(assert_keys.index('__qualname__'))
+ assert_keys.pop(assert_keys.index("__qualname__"))
self.assertEqual(sorted(cls.locals.keys()), assert_keys)
def test_class_getattr(self):
- data = '''
+ data = """
class WebAppObject(object):
appli = application
appli += 2
del self.appli
- '''
+ """
astroid = builder.parse(data, __name__)
- cls = astroid['WebAppObject']
+ cls = astroid["WebAppObject"]
# test del statement not returned by getattr
- self.assertEqual(len(cls.getattr('appli')), 2)
-
+ self.assertEqual(len(cls.getattr("appli")), 2)
def test_instance_getattr(self):
- data = '''
+ data = """
class WebAppObject(object):
def __init__(self, application):
self.appli = application
self.appli += 2
del self.appli
- '''
+ """
astroid = builder.parse(data)
- inst = Instance(astroid['WebAppObject'])
+ inst = Instance(astroid["WebAppObject"])
# test del statement not returned by getattr
- self.assertEqual(len(inst.getattr('appli')), 2)
-
+ self.assertEqual(len(inst.getattr("appli")), 2)
def test_instance_getattr_with_class_attr(self):
- data = '''
+ data = """
class Parent:
aa = 1
cc = 1
@@ -915,16 +956,15 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
if val < self.bb:
val = self.bb
self.aa += val
- '''
+ """
astroid = builder.parse(data)
- inst = Instance(astroid['Klass'])
- self.assertEqual(len(inst.getattr('aa')), 3, inst.getattr('aa'))
- self.assertEqual(len(inst.getattr('bb')), 1, inst.getattr('bb'))
- self.assertEqual(len(inst.getattr('cc')), 2, inst.getattr('cc'))
-
+ inst = Instance(astroid["Klass"])
+ self.assertEqual(len(inst.getattr("aa")), 3, inst.getattr("aa"))
+ self.assertEqual(len(inst.getattr("bb")), 1, inst.getattr("bb"))
+ self.assertEqual(len(inst.getattr("cc")), 2, inst.getattr("cc"))
def test_getattr_method_transform(self):
- data = '''
+ data = """
class Clazz(object):
def m1(self, value):
@@ -938,23 +978,23 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
Clazz.m3 = func
inst = Clazz()
inst.m4 = func
- '''
+ """
astroid = builder.parse(data)
- cls = astroid['Clazz']
+ cls = astroid["Clazz"]
# test del statement not returned by getattr
- for method in ('m1', 'm2', 'm3'):
+ for method in ("m1", "m2", "m3"):
inferred = list(cls.igetattr(method))
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], UnboundMethod)
inferred = list(Instance(cls).igetattr(method))
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], BoundMethod)
- inferred = list(Instance(cls).igetattr('m4'))
+ inferred = list(Instance(cls).igetattr("m4"))
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], nodes.FunctionDef)
def test_getattr_from_grandpa(self):
- data = '''
+ data = """
class Future:
attr = 1
@@ -963,17 +1003,17 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
class Past(Present):
pass
- '''
+ """
astroid = builder.parse(data)
- past = astroid['Past']
- attr = past.getattr('attr')
+ past = astroid["Past"]
+ attr = past.getattr("attr")
self.assertEqual(len(attr), 1)
attr1 = attr[0]
self.assertIsInstance(attr1, nodes.AssignName)
- self.assertEqual(attr1.name, 'attr')
+ self.assertEqual(attr1.name, "attr")
def test_function_with_decorator_lineno(self):
- data = '''
+ data = """
@f(a=2,
b=3)
def g1(x):
@@ -983,79 +1023,92 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
b=3)
def g2():
pass
- '''
+ """
astroid = builder.parse(data)
- self.assertEqual(astroid['g1'].fromlineno, 4)
- self.assertEqual(astroid['g1'].tolineno, 5)
- self.assertEqual(astroid['g2'].fromlineno, 9)
- self.assertEqual(astroid['g2'].tolineno, 10)
+ self.assertEqual(astroid["g1"].fromlineno, 4)
+ self.assertEqual(astroid["g1"].tolineno, 5)
+ self.assertEqual(astroid["g2"].fromlineno, 9)
+ self.assertEqual(astroid["g2"].tolineno, 10)
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_simple_metaclass(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
class Test(object):
__metaclass__ = type
- """)
- klass = astroid['Test']
+ """
+ )
+ klass = astroid["Test"]
metaclass = klass.metaclass()
self.assertIsInstance(metaclass, scoped_nodes.ClassDef)
- self.assertEqual(metaclass.name, 'type')
+ self.assertEqual(metaclass.name, "type")
def test_metaclass_error(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
class Test(object):
__metaclass__ = typ
- """)
- klass = astroid['Test']
+ """
+ )
+ klass = astroid["Test"]
self.assertFalse(klass.metaclass())
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_metaclass_imported(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
from abc import ABCMeta
class Test(object):
__metaclass__ = ABCMeta
- """)
- klass = astroid['Test']
+ """
+ )
+ klass = astroid["Test"]
metaclass = klass.metaclass()
self.assertIsInstance(metaclass, scoped_nodes.ClassDef)
- self.assertEqual(metaclass.name, 'ABCMeta')
+ self.assertEqual(metaclass.name, "ABCMeta")
def test_metaclass_yes_leak(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
# notice `ab` instead of `abc`
from ab import ABCMeta
class Meta(object):
__metaclass__ = ABCMeta
- """)
- klass = astroid['Meta']
+ """
+ )
+ klass = astroid["Meta"]
self.assertIsNone(klass.metaclass())
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_newstyle_and_metaclass_good(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
from abc import ABCMeta
class Test:
__metaclass__ = ABCMeta
- """)
- klass = astroid['Test']
+ """
+ )
+ klass = astroid["Test"]
self.assertTrue(klass.newstyle)
- self.assertEqual(klass.metaclass().name, 'ABCMeta')
- astroid = builder.parse("""
+ self.assertEqual(klass.metaclass().name, "ABCMeta")
+ astroid = builder.parse(
+ """
from abc import ABCMeta
__metaclass__ = ABCMeta
class Test:
pass
- """)
- klass = astroid['Test']
+ """
+ )
+ klass = astroid["Test"]
self.assertTrue(klass.newstyle)
- self.assertEqual(klass.metaclass().name, 'ABCMeta')
+ self.assertEqual(klass.metaclass().name, "ABCMeta")
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_nested_metaclass(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
from abc import ABCMeta
class A(object):
__metaclass__ = ABCMeta
@@ -1065,34 +1118,38 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
class C:
__metaclass__ = type
class D: pass
- """)
- a = astroid['A']
- b = a.locals['B'][0]
- c = astroid['C']
- d = c.locals['D'][0]
- self.assertEqual(a.metaclass().name, 'ABCMeta')
+ """
+ )
+ a = astroid["A"]
+ b = a.locals["B"][0]
+ c = astroid["C"]
+ d = c.locals["D"][0]
+ self.assertEqual(a.metaclass().name, "ABCMeta")
self.assertFalse(b.newstyle)
self.assertIsNone(b.metaclass())
- self.assertEqual(c.metaclass().name, 'type')
- self.assertEqual(d.metaclass().name, 'ABCMeta')
+ self.assertEqual(c.metaclass().name, "type")
+ self.assertEqual(d.metaclass().name, "ABCMeta")
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_parent_metaclass(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
from abc import ABCMeta
class Test:
__metaclass__ = ABCMeta
class SubTest(Test): pass
- """)
- klass = astroid['SubTest']
+ """
+ )
+ klass = astroid["SubTest"]
self.assertTrue(klass.newstyle)
metaclass = klass.metaclass()
self.assertIsInstance(metaclass, scoped_nodes.ClassDef)
- self.assertEqual(metaclass.name, 'ABCMeta')
+ self.assertEqual(metaclass.name, "ABCMeta")
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_metaclass_ancestors(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
from abc import ABCMeta
class FirstMeta(object):
@@ -1108,11 +1165,9 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
class SecondImpl(FirstImpl): pass
class ThirdImpl(Simple, SecondMeta):
pass
- """)
- classes = {
- 'ABCMeta': ('FirstImpl', 'SecondImpl'),
- 'type': ('ThirdImpl', )
- }
+ """
+ )
+ classes = {"ABCMeta": ("FirstImpl", "SecondImpl"), "type": ("ThirdImpl",)}
for metaclass, names in classes.items():
for name in names:
impl = astroid[name]
@@ -1121,19 +1176,22 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
self.assertEqual(meta.name, metaclass)
def test_metaclass_type(self):
- klass = builder.extract_node("""
+ klass = builder.extract_node(
+ """
def with_metaclass(meta, base=object):
return meta("NewBase", (base, ), {})
class ClassWithMeta(with_metaclass(type)): #@
pass
- """)
+ """
+ )
self.assertEqual(
- ['NewBase', 'object'],
- [base.name for base in klass.ancestors()])
+ ["NewBase", "object"], [base.name for base in klass.ancestors()]
+ )
def test_no_infinite_metaclass_loop(self):
- klass = builder.extract_node("""
+ klass = builder.extract_node(
+ """
class SSS(object):
class JJJ(object):
@@ -1148,14 +1206,16 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
class BBB(AAA.JJJ):
pass
- """)
+ """
+ )
self.assertFalse(scoped_nodes._is_metaclass(klass))
ancestors = [base.name for base in klass.ancestors()]
- self.assertIn('object', ancestors)
- self.assertIn('JJJ', ancestors)
+ self.assertIn("object", ancestors)
+ self.assertIn("JJJ", ancestors)
def test_no_infinite_metaclass_loop_with_redefine(self):
- ast_nodes = builder.extract_node("""
+ ast_nodes = builder.extract_node(
+ """
import datetime
class A(datetime.date): #@
@@ -1168,49 +1228,54 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
datetime.date = A
datetime.date = B
- """)
+ """
+ )
for klass in ast_nodes:
self.assertEqual(None, klass.metaclass())
def test_metaclass_generator_hack(self):
- klass = builder.extract_node("""
+ klass = builder.extract_node(
+ """
import six
class WithMeta(six.with_metaclass(type, object)): #@
pass
- """)
- self.assertEqual(
- ['object'],
- [base.name for base in klass.ancestors()])
- self.assertEqual(
- 'type', klass.metaclass().name)
+ """
+ )
+ self.assertEqual(["object"], [base.name for base in klass.ancestors()])
+ self.assertEqual("type", klass.metaclass().name)
def test_using_six_add_metaclass(self):
- klass = builder.extract_node('''
+ klass = builder.extract_node(
+ """
import six
import abc
@six.add_metaclass(abc.ABCMeta)
class WithMeta(object):
pass
- ''')
+ """
+ )
inferred = next(klass.infer())
metaclass = inferred.metaclass()
self.assertIsInstance(metaclass, scoped_nodes.ClassDef)
- self.assertIn(metaclass.qname(), ('abc.ABCMeta', '_py_abc.ABCMeta'))
+ self.assertIn(metaclass.qname(), ("abc.ABCMeta", "_py_abc.ABCMeta"))
def test_using_invalid_six_add_metaclass_call(self):
- klass = builder.extract_node('''
+ klass = builder.extract_node(
+ """
import six
@six.add_metaclass()
class Invalid(object):
pass
- ''')
+ """
+ )
inferred = next(klass.infer())
self.assertIsNone(inferred.metaclass())
def test_nonregr_infer_callresult(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
class Delegate(object):
def __get__(self, obj, cls):
return getattr(obj._subject, self.attribute)
@@ -1220,14 +1285,16 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
builder = CompositeBuilder(result, composite)
tgts = builder()
- """)
- instance = astroid['tgts']
+ """
+ )
+ instance = astroid["tgts"]
# used to raise "'_Yes' object is not iterable", see
# https://bitbucket.org/logilab/astroid/issue/17
self.assertEqual(list(instance.infer()), [util.Uninferable])
def test_slots(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
from collections import deque
from textwrap import dedent
@@ -1251,114 +1318,129 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
pass
class Ten(object): #@
__slots__ = dict({"a": "b", "c": "d"})
- """)
+ """
+ )
expected = [
- ('First', ('a', 'b')),
- ('Second', ('a', )),
- ('Third', None),
- ('Fourth', ('a', 'b')),
- ('Fifth', None),
- ('Sixth', None),
- ('Seventh', ('dedent', )),
- ('Eight', ('parens', )),
- ('Ninth', None),
- ('Ten', ('a', 'c')),
+ ("First", ("a", "b")),
+ ("Second", ("a",)),
+ ("Third", None),
+ ("Fourth", ("a", "b")),
+ ("Fifth", None),
+ ("Sixth", None),
+ ("Seventh", ("dedent",)),
+ ("Eight", ("parens",)),
+ ("Ninth", None),
+ ("Ten", ("a", "c")),
]
for cls, expected_value in expected:
slots = astroid[cls].slots()
if expected_value is None:
self.assertIsNone(slots)
else:
- self.assertEqual(list(expected_value),
- [node.value for node in slots])
+ self.assertEqual(list(expected_value), [node.value for node in slots])
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_slots_py2(self):
- module = builder.parse("""
+ module = builder.parse(
+ """
class UnicodeSlots(object):
__slots__ = (u"a", u"b", "c")
- """)
- slots = module['UnicodeSlots'].slots()
+ """
+ )
+ slots = module["UnicodeSlots"].slots()
self.assertEqual(len(slots), 3)
self.assertEqual(slots[0].value, "a")
self.assertEqual(slots[1].value, "b")
self.assertEqual(slots[2].value, "c")
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_slots_py2_not_implemented(self):
- module = builder.parse("""
+ module = builder.parse(
+ """
class OldStyle:
__slots__ = ("a", "b")
- """)
+ """
+ )
msg = "The concept of slots is undefined for old-style classes."
with self.assertRaises(NotImplementedError) as cm:
- module['OldStyle'].slots()
+ module["OldStyle"].slots()
self.assertEqual(str(cm.exception), msg)
def test_slots_for_dict_keys(self):
- module = builder.parse('''
+ module = builder.parse(
+ """
class Issue(object):
SlotDefaults = {'id': 0, 'id1':1}
__slots__ = SlotDefaults.keys()
- ''')
- cls = module['Issue']
+ """
+ )
+ cls = module["Issue"]
slots = cls.slots()
self.assertEqual(len(slots), 2)
- self.assertEqual(slots[0].value, 'id')
- self.assertEqual(slots[1].value, 'id1')
+ self.assertEqual(slots[0].value, "id")
+ self.assertEqual(slots[1].value, "id1")
def test_slots_empty_list_of_slots(self):
- module = builder.parse("""
+ module = builder.parse(
+ """
class Klass(object):
__slots__ = ()
- """)
- cls = module['Klass']
+ """
+ )
+ cls = module["Klass"]
self.assertEqual(cls.slots(), [])
def test_slots_taken_from_parents(self):
- module = builder.parse('''
+ module = builder.parse(
+ """
class FirstParent(object):
__slots__ = ('a', 'b', 'c')
class SecondParent(FirstParent):
__slots__ = ('d', 'e')
class Third(SecondParent):
__slots__ = ('d', )
- ''')
- cls = module['Third']
+ """
+ )
+ cls = module["Third"]
slots = cls.slots()
- self.assertEqual(sorted({slot.value for slot in slots}),
- ['a', 'b', 'c', 'd', 'e'])
+ self.assertEqual(
+ sorted({slot.value for slot in slots}), ["a", "b", "c", "d", "e"]
+ )
def test_all_ancestors_need_slots(self):
- module = builder.parse('''
+ module = builder.parse(
+ """
class A(object):
__slots__ = ('a', )
class B(A): pass
class C(B):
__slots__ = ('a', )
- ''')
- cls = module['C']
+ """
+ )
+ cls = module["C"]
self.assertIsNone(cls.slots())
- cls = module['B']
+ cls = module["B"]
self.assertIsNone(cls.slots())
def assertEqualMro(self, klass, expected_mro):
- self.assertEqual(
- [member.name for member in klass.mro()],
- expected_mro)
+ self.assertEqual([member.name for member in klass.mro()], expected_mro)
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_no_mro_for_old_style(self):
- node = builder.extract_node("""
- class Old: pass""")
+ node = builder.extract_node(
+ """
+ class Old: pass"""
+ )
with self.assertRaises(NotImplementedError) as cm:
node.mro()
- self.assertEqual(str(cm.exception), "Could not obtain mro for "
- "old-style classes.")
+ self.assertEqual(
+ str(cm.exception), "Could not obtain mro for " "old-style classes."
+ )
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_mro_for_classes_with_old_style_in_mro(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
class Factory:
pass
class ClientFactory(Factory):
@@ -1373,18 +1455,26 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
pass
class RetryFactory(WampWebSocketClientFactory, ReconnectingClientFactory):
pas
- ''')
+ """
+ )
self.assertEqualMro(
node,
- ['RetryFactory', 'WampWebSocketClientFactory',
- 'WebSocketClientFactory', 'WebSocketAdapterFactory', 'object',
- 'ReconnectingClientFactory', 'ClientFactory',
- 'Factory']
+ [
+ "RetryFactory",
+ "WampWebSocketClientFactory",
+ "WebSocketClientFactory",
+ "WebSocketAdapterFactory",
+ "object",
+ "ReconnectingClientFactory",
+ "ClientFactory",
+ "Factory",
+ ],
)
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_combined_newstyle_oldstyle_in_mro(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
class Old:
pass
class New(object):
@@ -1395,12 +1485,14 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
pass
class NewOld(New2, Old): #@
pass
- ''')
- self.assertEqualMro(node, ['NewOld', 'New2', 'New', 'New1', 'object', 'Old'])
+ """
+ )
+ self.assertEqualMro(node, ["NewOld", "New2", "New", "New1", "object", "Old"])
self.assertTrue(node.newstyle)
def test_with_metaclass_mro(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
import six
class C(object):
@@ -1409,11 +1501,13 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
pass
class A(six.with_metaclass(type, B)):
pass
- """)
- self.assertEqualMro(astroid['A'], ['A', 'B', 'C', 'object'])
+ """
+ )
+ self.assertEqualMro(astroid["A"], ["A", "B", "C", "object"])
def test_mro(self):
- astroid = builder.parse("""
+ astroid = builder.parse(
+ """
class C(object): pass
class D(dict, C): pass
@@ -1447,50 +1541,65 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
class Inner(OuterC.Inner, OuterB.Inner):
pass
class Duplicates(str, str): pass
-
- """)
- self.assertEqualMro(astroid['D'], ['D', 'dict', 'C', 'object'])
- self.assertEqualMro(astroid['D1'], ['D1', 'B1', 'C1', 'A1', 'object'])
- self.assertEqualMro(astroid['E1'], ['E1', 'C1', 'B1', 'A1', 'object'])
+
+ """
+ )
+ self.assertEqualMro(astroid["D"], ["D", "dict", "C", "object"])
+ self.assertEqualMro(astroid["D1"], ["D1", "B1", "C1", "A1", "object"])
+ self.assertEqualMro(astroid["E1"], ["E1", "C1", "B1", "A1", "object"])
with self.assertRaises(InconsistentMroError) as cm:
- astroid['F1'].mro()
- A1 = astroid.getattr('A1')[0]
- B1 = astroid.getattr('B1')[0]
- C1 = astroid.getattr('C1')[0]
- object_ = builder.MANAGER.astroid_cache[BUILTINS].getattr('object')[0]
- self.assertEqual(cm.exception.mros, [[B1, C1, A1, object_],
- [C1, B1, A1, object_]])
+ astroid["F1"].mro()
+ A1 = astroid.getattr("A1")[0]
+ B1 = astroid.getattr("B1")[0]
+ C1 = astroid.getattr("C1")[0]
+ object_ = builder.MANAGER.astroid_cache[BUILTINS].getattr("object")[0]
+ self.assertEqual(
+ cm.exception.mros, [[B1, C1, A1, object_], [C1, B1, A1, object_]]
+ )
with self.assertRaises(InconsistentMroError) as cm:
- astroid['G1'].mro()
- self.assertEqual(cm.exception.mros, [[C1, B1, A1, object_],
- [B1, C1, A1, object_]])
+ astroid["G1"].mro()
+ self.assertEqual(
+ cm.exception.mros, [[C1, B1, A1, object_], [B1, C1, A1, object_]]
+ )
self.assertEqualMro(
- astroid['PedalWheelBoat'],
- ["PedalWheelBoat", "EngineLess",
- "DayBoat", "WheelBoat", "Boat", "object"])
+ astroid["PedalWheelBoat"],
+ ["PedalWheelBoat", "EngineLess", "DayBoat", "WheelBoat", "Boat", "object"],
+ )
self.assertEqualMro(
astroid["SmallCatamaran"],
- ["SmallCatamaran", "SmallMultihull", "DayBoat", "Boat", "object"])
+ ["SmallCatamaran", "SmallMultihull", "DayBoat", "Boat", "object"],
+ )
self.assertEqualMro(
astroid["Pedalo"],
- ["Pedalo", "PedalWheelBoat", "EngineLess", "SmallCatamaran",
- "SmallMultihull", "DayBoat", "WheelBoat", "Boat", "object"])
+ [
+ "Pedalo",
+ "PedalWheelBoat",
+ "EngineLess",
+ "SmallCatamaran",
+ "SmallMultihull",
+ "DayBoat",
+ "WheelBoat",
+ "Boat",
+ "object",
+ ],
+ )
self.assertEqualMro(
- astroid['OuterD']['Inner'],
- ['Inner', 'Inner', 'Inner', 'Inner', 'object'])
+ astroid["OuterD"]["Inner"], ["Inner", "Inner", "Inner", "Inner", "object"]
+ )
with self.assertRaises(DuplicateBasesError) as cm:
- astroid['Duplicates'].mro()
- Duplicates = astroid.getattr('Duplicates')[0]
+ astroid["Duplicates"].mro()
+ Duplicates = astroid.getattr("Duplicates")[0]
self.assertEqual(cm.exception.cls, Duplicates)
self.assertIsInstance(cm.exception, MroError)
self.assertIsInstance(cm.exception, ResolveError)
def test_mro_with_factories(self):
- cls = builder.extract_node('''
+ cls = builder.extract_node(
+ """
def MixinFactory(cls):
mixin_name = '{}Mixin'.format(cls.__name__)
mixin_bases = (object,)
@@ -1510,30 +1619,43 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
class FinalClass(ClassB):
def __init__(self):
self.name = 'x'
- ''')
+ """
+ )
self.assertEqualMro(
cls,
[
- "FinalClass", "ClassB", "MixinB", "", "ClassA", "MixinA", "", "Base", "object"
- ]
+ "FinalClass",
+ "ClassB",
+ "MixinB",
+ "",
+ "ClassA",
+ "MixinA",
+ "",
+ "Base",
+ "object",
+ ],
)
def test_generator_from_infer_call_result_parent(self):
- func = builder.extract_node("""
+ func = builder.extract_node(
+ """
import contextlib
@contextlib.contextmanager
def test(): #@
yield
- """)
+ """
+ )
result = next(func.infer_call_result())
self.assertIsInstance(result, Generator)
self.assertEqual(result.parent, func)
def test_type_three_arguments(self):
- classes = builder.extract_node("""
+ classes = builder.extract_node(
+ """
type('A', (object, ), {"a": 1, "b": 2, missing: 3}) #@
- """)
+ """
+ )
first = next(classes.infer())
self.assertIsInstance(first, nodes.ClassDef)
self.assertEqual(first.name, "A")
@@ -1546,47 +1668,56 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
first.getattr("missing")
def test_implicit_metaclass(self):
- cls = builder.extract_node("""
+ cls = builder.extract_node(
+ """
class A(object):
pass
- """)
+ """
+ )
type_cls = scoped_nodes.builtin_lookup("type")[1][0]
self.assertEqual(cls.implicit_metaclass(), type_cls)
def test_implicit_metaclass_lookup(self):
- cls = builder.extract_node('''
+ cls = builder.extract_node(
+ """
class A(object):
pass
- ''')
+ """
+ )
instance = cls.instantiate_class()
- func = cls.getattr('mro')
+ func = cls.getattr("mro")
self.assertEqual(len(func), 1)
- self.assertRaises(AttributeInferenceError, instance.getattr, 'mro')
+ self.assertRaises(AttributeInferenceError, instance.getattr, "mro")
def test_metaclass_lookup_using_same_class(self):
# Check that we don't have recursive attribute access for metaclass
- cls = builder.extract_node('''
- class A(object): pass
- ''')
- self.assertEqual(len(cls.getattr('mro')), 1)
+ cls = builder.extract_node(
+ """
+ class A(object): pass
+ """
+ )
+ self.assertEqual(len(cls.getattr("mro")), 1)
def test_metaclass_lookup_inference_errors(self):
- module = builder.parse('''
+ module = builder.parse(
+ """
import six
class Metaclass(type):
foo = lala
@six.add_metaclass(Metaclass)
- class B(object): pass
- ''')
- cls = module['B']
- self.assertEqual(util.Uninferable, next(cls.igetattr('foo')))
+ class B(object): pass
+ """
+ )
+ cls = module["B"]
+ self.assertEqual(util.Uninferable, next(cls.igetattr("foo")))
def test_metaclass_lookup(self):
- module = builder.parse('''
+ module = builder.parse(
+ """
import six
-
+
class Metaclass(type):
foo = 42
@classmethod
@@ -1604,59 +1735,65 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
@six.add_metaclass(Metaclass)
class A(object):
pass
- ''')
- acls = module['A']
- normal_attr = next(acls.igetattr('foo'))
+ """
+ )
+ acls = module["A"]
+ normal_attr = next(acls.igetattr("foo"))
self.assertIsInstance(normal_attr, nodes.Const)
self.assertEqual(normal_attr.value, 42)
- class_method = next(acls.igetattr('class_method'))
+ class_method = next(acls.igetattr("class_method"))
self.assertIsInstance(class_method, BoundMethod)
- self.assertEqual(class_method.bound, module['Metaclass'])
+ self.assertEqual(class_method.bound, module["Metaclass"])
- normal_method = next(acls.igetattr('normal_method'))
+ normal_method = next(acls.igetattr("normal_method"))
self.assertIsInstance(normal_method, BoundMethod)
- self.assertEqual(normal_method.bound, module['A'])
+ self.assertEqual(normal_method.bound, module["A"])
# Attribute access for properties:
# from the metaclass is a property object
# from the class that uses the metaclass, the value
# of the property
- property_meta = next(module['Metaclass'].igetattr('meta_property'))
+ property_meta = next(module["Metaclass"].igetattr("meta_property"))
self.assertIsInstance(property_meta, UnboundMethod)
wrapping = scoped_nodes.get_wrapping_class(property_meta)
- self.assertEqual(wrapping, module['Metaclass'])
+ self.assertEqual(wrapping, module["Metaclass"])
- property_class = next(acls.igetattr('meta_property'))
+ property_class = next(acls.igetattr("meta_property"))
self.assertIsInstance(property_class, nodes.Const)
self.assertEqual(property_class.value, 42)
- static = next(acls.igetattr('static'))
+ static = next(acls.igetattr("static"))
self.assertIsInstance(static, scoped_nodes.FunctionDef)
- @test_utils.require_version(maxver='3.0')
+ @test_utils.require_version(maxver="3.0")
def test_implicit_metaclass_is_none(self):
- cls = builder.extract_node("""
+ cls = builder.extract_node(
+ """
class A: pass
- """)
+ """
+ )
self.assertIsNone(cls.implicit_metaclass())
def test_local_attr_invalid_mro(self):
- cls = builder.extract_node("""
+ cls = builder.extract_node(
+ """
# A has an invalid MRO, local_attr should fallback
# to using .ancestors.
class A(object, object):
test = 42
class B(A): #@
pass
- """)
- local = cls.local_attr('test')[0]
+ """
+ )
+ local = cls.local_attr("test")[0]
inferred = next(local.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, 42)
def test_has_dynamic_getattr(self):
- module = builder.parse("""
+ module = builder.parse(
+ """
class Getattr(object):
def __getattr__(self, attrname):
pass
@@ -1667,104 +1804,121 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
class ParentGetattr(Getattr):
pass
- """)
- self.assertTrue(module['Getattr'].has_dynamic_getattr())
- self.assertTrue(module['Getattribute'].has_dynamic_getattr())
- self.assertTrue(module['ParentGetattr'].has_dynamic_getattr())
+ """
+ )
+ self.assertTrue(module["Getattr"].has_dynamic_getattr())
+ self.assertTrue(module["Getattribute"].has_dynamic_getattr())
+ self.assertTrue(module["ParentGetattr"].has_dynamic_getattr())
# Test that objects analyzed through the live introspection
# aren't considered to have dynamic getattr implemented.
import datetime
+
astroid_builder = builder.AstroidBuilder()
module = astroid_builder.module_build(datetime)
- self.assertFalse(module['timedelta'].has_dynamic_getattr())
+ self.assertFalse(module["timedelta"].has_dynamic_getattr())
def test_duplicate_bases_namedtuple(self):
- module = builder.parse("""
+ module = builder.parse(
+ """
import collections
_A = collections.namedtuple('A', 'a')
class A(_A): pass
class B(A): pass
- """)
- names = ['B', 'A', 'A', 'tuple', 'object']
- mro = module['B'].mro()
+ """
+ )
+ names = ["B", "A", "A", "tuple", "object"]
+ mro = module["B"].mro()
class_names = [i.name for i in mro]
self.assertEqual(names, class_names)
def test_instance_bound_method_lambdas(self):
- ast_nodes = builder.extract_node('''
+ ast_nodes = builder.extract_node(
+ """
class Test(object): #@
lam = lambda self: self
not_method = lambda xargs: xargs
Test() #@
- ''')
+ """
+ )
cls = next(ast_nodes[0].infer())
- self.assertIsInstance(next(cls.igetattr('lam')), scoped_nodes.Lambda)
- self.assertIsInstance(next(cls.igetattr('not_method')), scoped_nodes.Lambda)
+ self.assertIsInstance(next(cls.igetattr("lam")), scoped_nodes.Lambda)
+ self.assertIsInstance(next(cls.igetattr("not_method")), scoped_nodes.Lambda)
instance = next(ast_nodes[1].infer())
- lam = next(instance.igetattr('lam'))
+ lam = next(instance.igetattr("lam"))
self.assertIsInstance(lam, BoundMethod)
- not_method = next(instance.igetattr('not_method'))
+ not_method = next(instance.igetattr("not_method"))
self.assertIsInstance(not_method, scoped_nodes.Lambda)
def test_class_extra_decorators_frame_is_not_class(self):
- ast_node = builder.extract_node('''
+ ast_node = builder.extract_node(
+ """
def ala():
def bala(): #@
func = 42
- ''')
+ """
+ )
self.assertEqual(ast_node.extra_decorators, [])
def test_class_extra_decorators_only_callfunc_are_considered(self):
- ast_node = builder.extract_node('''
+ ast_node = builder.extract_node(
+ """
class Ala(object):
def func(self): #@
pass
func = 42
- ''')
+ """
+ )
self.assertEqual(ast_node.extra_decorators, [])
def test_class_extra_decorators_only_assignment_names_are_considered(self):
- ast_node = builder.extract_node('''
+ ast_node = builder.extract_node(
+ """
class Ala(object):
def func(self): #@
pass
def __init__(self):
self.func = staticmethod(func)
- ''')
+ """
+ )
self.assertEqual(ast_node.extra_decorators, [])
def test_class_extra_decorators_only_same_name_considered(self):
- ast_node = builder.extract_node('''
+ ast_node = builder.extract_node(
+ """
class Ala(object):
def func(self): #@
pass
bala = staticmethod(func)
- ''')
+ """
+ )
self.assertEqual(ast_node.extra_decorators, [])
- self.assertEqual(ast_node.type, 'method')
+ self.assertEqual(ast_node.type, "method")
def test_class_extra_decorators(self):
- static_method, clsmethod = builder.extract_node('''
+ static_method, clsmethod = builder.extract_node(
+ """
class Ala(object):
def static(self): #@
pass
def class_method(self): #@
pass
class_method = classmethod(class_method)
- static = staticmethod(static)
- ''')
+ static = staticmethod(static)
+ """
+ )
self.assertEqual(len(clsmethod.extra_decorators), 1)
- self.assertEqual(clsmethod.type, 'classmethod')
+ self.assertEqual(clsmethod.type, "classmethod")
self.assertEqual(len(static_method.extra_decorators), 1)
- self.assertEqual(static_method.type, 'staticmethod')
+ self.assertEqual(static_method.type, "staticmethod")
def test_extra_decorators_only_class_level_assignments(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
def _bind(arg):
return arg.bind
@@ -1776,41 +1930,44 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
# This is important, because it used to trigger
# a maximum recursion error.
bind = _bind(self)
- return bind
+ return bind
A() #@
- ''')
+ """
+ )
inferred = next(node.infer())
- bind = next(inferred.igetattr('bind'))
+ bind = next(inferred.igetattr("bind"))
self.assertIsInstance(bind, nodes.Const)
self.assertEqual(bind.value, 42)
parent = bind.scope()
self.assertEqual(len(parent.extra_decorators), 0)
- @test_utils.require_version(minver='3.0')
+ @test_utils.require_version(minver="3.0")
def test_class_keywords(self):
- data = '''
+ data = """
class TestKlass(object, metaclass=TestMetaKlass,
foo=42, bar='baz'):
pass
- '''
+ """
astroid = builder.parse(data, __name__)
- cls = astroid['TestKlass']
+ cls = astroid["TestKlass"]
self.assertEqual(len(cls.keywords), 2)
- self.assertEqual([x.arg for x in cls.keywords], ['foo', 'bar'])
+ self.assertEqual([x.arg for x in cls.keywords], ["foo", "bar"])
def test_metaclass_cannot_infer_call_yields_an_instance():
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
from undefined import Undefined
class Meta(type):
__call__ = Undefined
class A(metaclass=Meta):
pass
A()
- ''')
+ """
+ )
inferred = next(node.infer())
assert isinstance(inferred, Instance)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/tests/unittest_transforms.py b/astroid/tests/unittest_transforms.py
index 946c603d..5df7ffad 100644
--- a/astroid/tests/unittest_transforms.py
+++ b/astroid/tests/unittest_transforms.py
@@ -29,7 +29,6 @@ def add_transform(manager, node, transform, predicate=None):
class TestTransforms(unittest.TestCase):
-
def setUp(self):
self.transformer = transforms.TransformVisitor()
@@ -43,13 +42,14 @@ class TestTransforms(unittest.TestCase):
inferred = next(node.infer())
return inferred
- self.transformer.register_transform(nodes.Call,
- transform_call)
+ self.transformer.register_transform(nodes.Call, transform_call)
- module = self.parse_transform('''
+ module = self.parse_transform(
+ """
def test(): return 42
test() #@
- ''')
+ """
+ )
self.assertIsInstance(module.body[1], nodes.Expr)
self.assertIsInstance(module.body[1].value, nodes.Const)
@@ -72,11 +72,13 @@ class TestTransforms(unittest.TestCase):
self.transformer.register_transform(nodes.Compare, transform_compare)
self.transformer.register_transform(nodes.Name, transform_name)
- module = self.parse_transform('''
+ module = self.parse_transform(
+ """
a = 42
b = 24
a < b
- ''')
+ """
+ )
self.assertIsInstance(module.body[2], nodes.Expr)
self.assertIsInstance(module.body[2].value, nodes.Const)
@@ -86,23 +88,24 @@ class TestTransforms(unittest.TestCase):
def transform_function(node):
assign = nodes.Assign()
name = nodes.AssignName()
- name.name = 'value'
+ name.name = "value"
assign.targets = [name]
assign.value = nodes.const_factory(42)
node.body.append(assign)
- self.transformer.register_transform(nodes.FunctionDef,
- transform_function)
+ self.transformer.register_transform(nodes.FunctionDef, transform_function)
- module = self.parse_transform('''
+ module = self.parse_transform(
+ """
def test():
pass
- ''')
+ """
+ )
func = module.body[0]
self.assertEqual(len(func.body), 2)
self.assertIsInstance(func.body[1], nodes.Assign)
- self.assertEqual(func.body[1].as_string(), 'value = 42')
+ self.assertEqual(func.body[1].as_string(), "value = 42")
def test_predicates(self):
def transform_call(node):
@@ -110,13 +113,12 @@ class TestTransforms(unittest.TestCase):
return inferred
def should_inline(node):
- return node.func.name.startswith('inlineme')
+ return node.func.name.startswith("inlineme")
- self.transformer.register_transform(nodes.Call,
- transform_call,
- should_inline)
+ self.transformer.register_transform(nodes.Call, transform_call, should_inline)
- module = self.parse_transform('''
+ module = self.parse_transform(
+ """
def inlineme_1():
return 24
def dont_inline_me():
@@ -126,7 +128,8 @@ class TestTransforms(unittest.TestCase):
inlineme_1()
dont_inline_me()
inlineme_2()
- ''')
+ """
+ )
values = module.body[-3:]
self.assertIsInstance(values[0], nodes.Expr)
self.assertIsInstance(values[0].value, nodes.Const)
@@ -147,13 +150,14 @@ class TestTransforms(unittest.TestCase):
if node.decorators:
for decorator in node.decorators.nodes:
inferred = next(decorator.infer())
- if inferred.qname() == 'abc.abstractmethod':
+ if inferred.qname() == "abc.abstractmethod":
return next(node.infer_call_result())
return None
manager = builder.MANAGER
with add_transform(manager, nodes.FunctionDef, transform_function):
- module = builder.parse('''
+ module = builder.parse(
+ """
import abc
from abc import abstractmethod
@@ -165,9 +169,10 @@ class TestTransforms(unittest.TestCase):
@abstractmethod
def bala(self):
return 42
- ''')
+ """
+ )
- cls = module['A']
+ cls = module["A"]
ala = cls.body[0]
bala = cls.body[1]
self.assertIsInstance(ala, nodes.Const)
@@ -179,21 +184,20 @@ class TestTransforms(unittest.TestCase):
# Test that transforms are called for builtin modules.
def transform_function(node):
name = nodes.AssignName()
- name.name = 'value'
+ name.name = "value"
node.args.args = [name]
return node
manager = builder.MANAGER
- predicate = lambda node: node.root().name == 'time'
- with add_transform(manager, nodes.FunctionDef,
- transform_function, predicate):
+ predicate = lambda node: node.root().name == "time"
+ with add_transform(manager, nodes.FunctionDef, transform_function, predicate):
builder_instance = builder.AstroidBuilder()
module = builder_instance.module_build(time)
- asctime = module['asctime']
+ asctime = module["asctime"]
self.assertEqual(len(asctime.args.args), 1)
self.assertIsInstance(asctime.args.args[0], nodes.AssignName)
- self.assertEqual(asctime.args.args[0].name, 'value')
+ self.assertEqual(asctime.args.args[0].name, "value")
def test_builder_apply_transforms(self):
def transform_function(node):
@@ -202,7 +206,7 @@ class TestTransforms(unittest.TestCase):
manager = builder.MANAGER
with add_transform(manager, nodes.FunctionDef, transform_function):
astroid_builder = builder.AstroidBuilder(apply_transforms=False)
- module = astroid_builder.string_build('''def test(): pass''')
+ module = astroid_builder.string_build("""def test(): pass""")
# The transform wasn't applied.
self.assertIsInstance(module.body[0], nodes.FunctionDef)
@@ -212,14 +216,14 @@ class TestTransforms(unittest.TestCase):
# in a transform, as per issue #188. This happened
# before, when the transforms weren't in their own step.
def transform_class(cls):
- if cls.is_subtype_of('django.db.models.base.Model'):
+ if cls.is_subtype_of("django.db.models.base.Model"):
return cls
return cls
- self.transformer.register_transform(nodes.ClassDef,
- transform_class)
+ self.transformer.register_transform(nodes.ClassDef, transform_class)
- self.parse_transform('''
+ self.parse_transform(
+ """
# Change environ to automatically call putenv() if it exists
import os
putenv = os.putenv
@@ -230,8 +234,9 @@ class TestTransforms(unittest.TestCase):
pass
else:
import UserDict
- ''')
+ """
+ )
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/tests/unittest_utils.py b/astroid/tests/unittest_utils.py
index 47eb56f4..3ae3d6b7 100644
--- a/astroid/tests/unittest_utils.py
+++ b/astroid/tests/unittest_utils.py
@@ -17,26 +17,30 @@ from astroid import util as astroid_util
class InferenceUtil(unittest.TestCase):
-
def test_not_exclusive(self):
- module = builder.parse("""
+ module = builder.parse(
+ """
x = 10
for x in range(5):
print (x)
if x > 0:
print ('#' * x)
- """, __name__, __file__)
- xass1 = module.locals['x'][0]
+ """,
+ __name__,
+ __file__,
+ )
+ xass1 = module.locals["x"][0]
assert xass1.lineno == 2
- xnames = [n for n in module.nodes_of_class(nodes.Name) if n.name == 'x']
+ xnames = [n for n in module.nodes_of_class(nodes.Name) if n.name == "x"]
assert len(xnames) == 3
assert xnames[1].lineno == 6
self.assertEqual(node_classes.are_exclusive(xass1, xnames[1]), False)
self.assertEqual(node_classes.are_exclusive(xass1, xnames[2]), False)
def test_if(self):
- module = builder.parse('''
+ module = builder.parse(
+ """
if 1:
a = 1
a = 2
@@ -46,13 +50,14 @@ class InferenceUtil(unittest.TestCase):
else:
a = 3
a = 4
- ''')
- a1 = module.locals['a'][0]
- a2 = module.locals['a'][1]
- a3 = module.locals['a'][2]
- a4 = module.locals['a'][3]
- a5 = module.locals['a'][4]
- a6 = module.locals['a'][5]
+ """
+ )
+ a1 = module.locals["a"][0]
+ a2 = module.locals["a"][1]
+ a3 = module.locals["a"][2]
+ a4 = module.locals["a"][3]
+ a5 = module.locals["a"][4]
+ a6 = module.locals["a"][5]
self.assertEqual(node_classes.are_exclusive(a1, a2), False)
self.assertEqual(node_classes.are_exclusive(a1, a3), True)
self.assertEqual(node_classes.are_exclusive(a1, a5), True)
@@ -61,7 +66,8 @@ class InferenceUtil(unittest.TestCase):
self.assertEqual(node_classes.are_exclusive(a5, a6), False)
def test_try_except(self):
- module = builder.parse('''
+ module = builder.parse(
+ """
try:
def exclusive_func2():
"docstring"
@@ -74,11 +80,12 @@ class InferenceUtil(unittest.TestCase):
else:
def exclusive_func2():
"this one redefine the one defined line 42"
- ''')
- f1 = module.locals['exclusive_func2'][0]
- f2 = module.locals['exclusive_func2'][1]
- f3 = module.locals['exclusive_func2'][2]
- f4 = module.locals['exclusive_func2'][3]
+ """
+ )
+ f1 = module.locals["exclusive_func2"][0]
+ f2 = module.locals["exclusive_func2"][1]
+ f3 = module.locals["exclusive_func2"][2]
+ f4 = module.locals["exclusive_func2"][3]
self.assertEqual(node_classes.are_exclusive(f1, f2), True)
self.assertEqual(node_classes.are_exclusive(f1, f3), True)
self.assertEqual(node_classes.are_exclusive(f1, f4), False)
@@ -91,25 +98,28 @@ class InferenceUtil(unittest.TestCase):
self.assertEqual(node_classes.are_exclusive(f4, f2), True)
def test_unpack_infer_uninferable_nodes(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
x = [A] * 1
f = [x, [A] * 2]
f
- ''')
+ """
+ )
inferred = next(node.infer())
unpacked = list(node_classes.unpack_infer(inferred))
self.assertEqual(len(unpacked), 3)
- self.assertTrue(all(elt is astroid_util.Uninferable
- for elt in unpacked))
+ self.assertTrue(all(elt is astroid_util.Uninferable for elt in unpacked))
def test_unpack_infer_empty_tuple(self):
- node = builder.extract_node('''
+ node = builder.extract_node(
+ """
()
- ''')
+ """
+ )
inferred = next(node.infer())
with self.assertRaises(InferenceError):
list(node_classes.unpack_infer(inferred))
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/astroid/transforms.py b/astroid/transforms.py
index 8ade6f64..80645935 100644
--- a/astroid/transforms.py
+++ b/astroid/transforms.py
@@ -44,7 +44,7 @@ class TransformVisitor:
return node
def _visit(self, node):
- if hasattr(node, '_astroid_fields'):
+ if hasattr(node, "_astroid_fields"):
for field in node._astroid_fields:
value = getattr(node, field)
visited = self._visit_generic(value)
diff --git a/astroid/util.py b/astroid/util.py
index 9fa4d358..cdd705fb 100644
--- a/astroid/util.py
+++ b/astroid/util.py
@@ -17,27 +17,31 @@ def lazy_descriptor(obj):
class DescriptorProxy(lazy_object_proxy.Proxy):
def __get__(self, instance, owner=None):
return self.__class__.__get__(self, instance)
+
return DescriptorProxy(obj)
def lazy_import(module_name):
return lazy_object_proxy.Proxy(
- lambda: importlib.import_module('.' + module_name, 'astroid'))
+ lambda: importlib.import_module("." + module_name, "astroid")
+ )
@object.__new__
class Uninferable:
"""Special inference object, which is returned when inference fails."""
+
def __repr__(self):
- return 'Uninferable'
+ return "Uninferable"
+
__str__ = __repr__
def __getattribute__(self, name):
- if name == 'next':
- raise AttributeError('next method should not be called')
- if name.startswith('__') and name.endswith('__'):
+ if name == "next":
+ raise AttributeError("next method should not be called")
+ if name.startswith("__") and name.endswith("__"):
return object.__getattribute__(self, name)
- if name == 'accept':
+ if name == "accept":
return object.__getattribute__(self, name)
return self
@@ -53,6 +57,7 @@ class Uninferable:
func = getattr(visitor, "visit_uninferable")
return func(self)
+
class BadOperationMessage:
"""Object which describes a TypeError occurred somewhere in the inference chain
@@ -71,7 +76,7 @@ class BadUnaryOperationMessage(BadOperationMessage):
@property
def _object_type_helper(self):
- helpers = lazy_import('helpers')
+ helpers = lazy_import("helpers")
return helpers.object_type
def _object_type(self, obj):
@@ -83,11 +88,11 @@ class BadUnaryOperationMessage(BadOperationMessage):
return objtype
def __str__(self):
- if hasattr(self.operand, 'name'):
+ if hasattr(self.operand, "name"):
operand_type = self.operand.name
else:
object_type = self._object_type(self.operand)
- if hasattr(object_type, 'name'):
+ if hasattr(object_type, "name"):
operand_type = object_type.name
else:
# Just fallback to as_string
@@ -114,18 +119,25 @@ def _instancecheck(cls, other):
wrapped = cls.__wrapped__
other_cls = other.__class__
is_instance_of = wrapped is other_cls or issubclass(other_cls, wrapped)
- warnings.warn("%r is deprecated and slated for removal in astroid "
- "2.0, use %r instead" % (cls.__class__.__name__,
- wrapped.__name__),
- PendingDeprecationWarning, stacklevel=2)
+ warnings.warn(
+ "%r is deprecated and slated for removal in astroid "
+ "2.0, use %r instead" % (cls.__class__.__name__, wrapped.__name__),
+ PendingDeprecationWarning,
+ stacklevel=2,
+ )
return is_instance_of
def proxy_alias(alias_name, node_type):
"""Get a Proxy from the given name to the given node type."""
- proxy = type(alias_name, (lazy_object_proxy.Proxy,),
- {'__class__': object.__dict__['__class__'],
- '__instancecheck__': _instancecheck})
+ proxy = type(
+ alias_name,
+ (lazy_object_proxy.Proxy,),
+ {
+ "__class__": object.__dict__["__class__"],
+ "__instancecheck__": _instancecheck,
+ },
+ )
return proxy(lambda: node_type)