diff options
| author | hippo91 <guillaume.peillex@gmail.com> | 2019-01-20 18:48:54 +0100 |
|---|---|---|
| committer | hippo91 <guillaume.peillex@gmail.com> | 2019-01-20 18:48:54 +0100 |
| commit | fd3cdad2940d3f36943d759ba346c3067ab6b2ed (patch) | |
| tree | 61b79d52d87ab3270d98337e1c5feab9589e1b95 | |
| parent | b1937b9f2cfc2878c7ddc22ec5a04bd0825e54eb (diff) | |
| parent | 94bb94f2af823489733af2428356df56c6cbb7c8 (diff) | |
| download | astroid-git-fd3cdad2940d3f36943d759ba346c3067ab6b2ed.tar.gz | |
Merge branch 'master' of https://github.com/PyCQA/astroid
| -rw-r--r-- | .github/PULL_REQUEST_TEMPLATE.md | 8 | ||||
| -rw-r--r-- | ChangeLog | 18 | ||||
| -rw-r--r-- | astroid/__pkginfo__.py | 2 | ||||
| -rw-r--r-- | astroid/brain/brain_attrs.py | 2 | ||||
| -rw-r--r-- | astroid/brain/brain_builtin_inference.py | 4 | ||||
| -rw-r--r-- | astroid/brain/brain_functools.py | 6 | ||||
| -rw-r--r-- | astroid/brain/brain_http.py | 81 | ||||
| -rw-r--r-- | astroid/brain/brain_namedtuple_enum.py | 2 | ||||
| -rw-r--r-- | astroid/context.py | 8 | ||||
| -rw-r--r-- | astroid/decorators.py | 38 | ||||
| -rw-r--r-- | astroid/helpers.py | 2 | ||||
| -rw-r--r-- | astroid/inference.py | 27 | ||||
| -rw-r--r-- | astroid/interpreter/objectmodel.py | 237 | ||||
| -rw-r--r-- | astroid/manager.py | 24 | ||||
| -rw-r--r-- | astroid/node_classes.py | 5 | ||||
| -rw-r--r-- | astroid/objects.py | 15 | ||||
| -rw-r--r-- | astroid/protocols.py | 29 | ||||
| -rw-r--r-- | astroid/raw_building.py | 97 | ||||
| -rw-r--r-- | astroid/scoped_nodes.py | 62 | ||||
| -rw-r--r-- | astroid/tests/unittest_brain.py | 38 | ||||
| -rw-r--r-- | astroid/tests/unittest_manager.py | 4 | ||||
| -rw-r--r-- | astroid/tests/unittest_modutils.py | 3 | ||||
| -rw-r--r-- | astroid/tests/unittest_object_model.py | 46 | ||||
| -rw-r--r-- | astroid/tests/unittest_regrtest.py | 4 | ||||
| -rw-r--r-- | pylintrc | 4 |
25 files changed, 487 insertions, 279 deletions
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 282c5f72..ff146662 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -8,8 +8,8 @@ To ease our work reviewing your PR, do make sure to mark the complete the follow ## Steps -- [ ] Add a ChangeLog entry describing what your PR does -- [ ] Write a good description on what the PR does +- [ ] For new features or bug fixes, add a ChangeLog entry describing what your PR does. +- [ ] Write a good description on what the PR does. ## Description @@ -25,9 +25,9 @@ To ease our work reviewing your PR, do make sure to mark the complete the follow ## Related Issue -<!-- +<!-- If this PR fixes a particular issue, use the following to automatically close that issue once this PR gets merged: -Closes #XXX +Closes #XXX --> @@ -7,6 +7,22 @@ What's New in astroid 2.2.0? Release Date: TBA +* Remove the restriction that "old style classes" cannot have a MRO. + + This does not make sense any longer given that we run against Python 3 + code. + Close PyCQA/pylint#2701 + +* Added more builtin exceptions attributes. Close #580 + +* Add a registry for builtin exception models. Close PyCQA/pylint#1432 + +* Add brain tips for `http.client`. Close PyCQA/pylint#2687 + +* Prevent crashing when processing ``enums`` with mixed single and double quotes. + + Close PyCQA/pylint#2676 + * ``typing`` types have the `__args__` property. Close PyCQA/pylint#2419 * Fix a bug where an Attribute used as a base class was triggering a crash @@ -21,6 +37,8 @@ Release Date: TBA Close #628 +* Fix typo in description for brain_attrs + What's New in astroid 2.1.0? ============================ diff --git a/astroid/__pkginfo__.py b/astroid/__pkginfo__.py index 621f178a..646e6575 100644 --- a/astroid/__pkginfo__.py +++ b/astroid/__pkginfo__.py @@ -21,7 +21,7 @@ distname = "astroid" modname = "astroid" -version = "2.2.0" +version = "2.2.0-dev" numversion = tuple(int(elem) for elem in version.split(".") if elem.isdigit()) extras_require = {} diff --git a/astroid/brain/brain_attrs.py b/astroid/brain/brain_attrs.py index 3bcfb852..a9241281 100644 --- a/astroid/brain/brain_attrs.py +++ b/astroid/brain/brain_attrs.py @@ -4,7 +4,7 @@ Astroid hook for the attrs library Without this hook pylint reports unsupported-assignment-operation -for atrrs classes +for attrs classes """ import astroid diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py index 2655095a..21dd6872 100644 --- a/astroid/brain/brain_builtin_inference.py +++ b/astroid/brain/brain_builtin_inference.py @@ -94,9 +94,7 @@ def _extend_str(class_node, rvalue): def _extend_builtins(class_transforms): - from astroid.bases import BUILTINS - - builtin_ast = MANAGER.astroid_cache[BUILTINS] + builtin_ast = MANAGER.builtins_module for class_name, transform in class_transforms.items(): transform(builtin_ast[class_name]) diff --git a/astroid/brain/brain_functools.py b/astroid/brain/brain_functools.py index 93bc9d3f..473b5bfe 100644 --- a/astroid/brain/brain_functools.py +++ b/astroid/brain/brain_functools.py @@ -25,11 +25,11 @@ class LruWrappedModel(objectmodel.FunctionModel): """ @property - def py__wrapped__(self): + def attr___wrapped__(self): return self._instance @property - def pycache_info(self): + def attr_cache_info(self): cache_info = extract_node( """ from functools import _CacheInfo @@ -44,7 +44,7 @@ class LruWrappedModel(objectmodel.FunctionModel): return CacheInfoBoundMethod(proxy=self._instance, bound=self._instance) @property - def pycache_clear(self): + def attr_cache_clear(self): node = extract_node("""def cache_clear(self): pass""") return BoundMethod(proxy=node, bound=self._instance.parent.scope()) diff --git a/astroid/brain/brain_http.py b/astroid/brain/brain_http.py new file mode 100644 index 00000000..45a9db20 --- /dev/null +++ b/astroid/brain/brain_http.py @@ -0,0 +1,81 @@ +# Copyright (c) 2018 Claudiu Popa <pcmanticore@gmail.com> + +# 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 `http` module.""" +import textwrap + +import astroid +from astroid.builder import AstroidBuilder + + +def _http_transform(): + return AstroidBuilder(astroid.MANAGER).string_build( + textwrap.dedent( + """ + from http import HTTPStatus + + CONTINUE = HTTPStatus.CONTINUE + SWITCHING_PROTOCOLS = HTTPStatus.SWITCHING_PROTOCOLS + PROCESSING = HTTPStatus.PROCESSING + OK = HTTPStatus.OK + CREATED = HTTPStatus.CREATED + ACCEPTED = HTTPStatus.ACCEPTED + NON_AUTHORITATIVE_INFORMATION = HTTPStatus.NON_AUTHORITATIVE_INFORMATION + NO_CONTENT = HTTPStatus.NO_CONTENT + RESET_CONTENT = HTTPStatus.RESET_CONTENT + PARTIAL_CONTENT = HTTPStatus.PARTIAL_CONTENT + MULTI_STATUS = HTTPStatus.MULTI_STATUS + ALREADY_REPORTED = HTTPStatus.ALREADY_REPORTED + IM_USED = HTTPStatus.IM_USED + MULTIPLE_CHOICES = HTTPStatus.MULTIPLE_CHOICES + MOVED_PERMANENTLY = HTTPStatus.MOVED_PERMANENTLY + FOUND = HTTPStatus.FOUND + SEE_OTHER = HTTPStatus.SEE_OTHER + NOT_MODIFIED = HTTPStatus.NOT_MODIFIED + USE_PROXY = HTTPStatus.USE_PROXY + TEMPORARY_REDIRECT = HTTPStatus.TEMPORARY_REDIRECT + PERMANENT_REDIRECT = HTTPStatus.PERMANENT_REDIRECT + BAD_REQUEST = HTTPStatus.BAD_REQUEST + UNAUTHORIZED = HTTPStatus.UNAUTHORIZED + PAYMENT_REQUIRED = HTTPStatus.PAYMENT_REQUIRED + FORBIDDEN = HTTPStatus.FORBIDDEN + NOT_FOUND = HTTPStatus.NOT_FOUND + METHOD_NOT_ALLOWED = HTTPStatus.METHOD_NOT_ALLOWED + NOT_ACCEPTABLE = HTTPStatus.NOT_ACCEPTABLE + PROXY_AUTHENTICATION_REQUIRED = HTTPStatus.PROXY_AUTHENTICATION_REQUIRED + REQUEST_TIMEOUT = HTTPStatus.REQUEST_TIMEOUT + CONFLICT = HTTPStatus.CONFLICT + GONE = HTTPStatus.GONE + LENGTH_REQUIRED = HTTPStatus.LENGTH_REQUIRED + PRECONDITION_FAILED = HTTPStatus.PRECONDITION_FAILED + REQUEST_ENTITY_TOO_LARGE = HTTPStatus.REQUEST_ENTITY_TOO_LARGE + REQUEST_URI_TOO_LONG = HTTPStatus.REQUEST_URI_TOO_LONG + UNSUPPORTED_MEDIA_TYPE = HTTPStatus.UNSUPPORTED_MEDIA_TYPE + REQUESTED_RANGE_NOT_SATISFIABLE = HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE + EXPECTATION_FAILED = HTTPStatus.EXPECTATION_FAILED + UNPROCESSABLE_ENTITY = HTTPStatus.UNPROCESSABLE_ENTITY + LOCKED = HTTPStatus.LOCKED + FAILED_DEPENDENCY = HTTPStatus.FAILED_DEPENDENCY + UPGRADE_REQUIRED = HTTPStatus.UPGRADE_REQUIRED + PRECONDITION_REQUIRED = HTTPStatus.PRECONDITION_REQUIRED + TOO_MANY_REQUESTS = HTTPStatus.TOO_MANY_REQUESTS + REQUEST_HEADER_FIELDS_TOO_LARGE = HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE + INTERNAL_SERVER_ERROR = HTTPStatus.INTERNAL_SERVER_ERROR + NOT_IMPLEMENTED = HTTPStatus.NOT_IMPLEMENTED + BAD_GATEWAY = HTTPStatus.BAD_GATEWAY + SERVICE_UNAVAILABLE = HTTPStatus.SERVICE_UNAVAILABLE + GATEWAY_TIMEOUT = HTTPStatus.GATEWAY_TIMEOUT + HTTP_VERSION_NOT_SUPPORTED = HTTPStatus.HTTP_VERSION_NOT_SUPPORTED + VARIANT_ALSO_NEGOTIATES = HTTPStatus.VARIANT_ALSO_NEGOTIATES + INSUFFICIENT_STORAGE = HTTPStatus.INSUFFICIENT_STORAGE + LOOP_DETECTED = HTTPStatus.LOOP_DETECTED + NOT_EXTENDED = HTTPStatus.NOT_EXTENDED + NETWORK_AUTHENTICATION_REQUIRED = HTTPStatus.NETWORK_AUTHENTICATION_REQUIRED + """ + ) + ) + + +astroid.register_module_extender(astroid.MANAGER, "http.client", _http_transform) diff --git a/astroid/brain/brain_namedtuple_enum.py b/astroid/brain/brain_namedtuple_enum.py index 6dc07f5e..58402f18 100644 --- a/astroid/brain/brain_namedtuple_enum.py +++ b/astroid/brain/brain_namedtuple_enum.py @@ -322,7 +322,7 @@ def infer_enum_class(node): inferred_return_value = None if isinstance(stmt.value, nodes.Const): if isinstance(stmt.value.value, str): - inferred_return_value = '"{}"'.format(stmt.value.value) + inferred_return_value = repr(stmt.value.value) else: inferred_return_value = stmt.value.value diff --git a/astroid/context.py b/astroid/context.py index 2cd724fd..70a92088 100644 --- a/astroid/context.py +++ b/astroid/context.py @@ -7,7 +7,7 @@ # For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER """Various context related utilities, including inference and call contexts.""" - +import contextlib import pprint from typing import Optional @@ -116,6 +116,12 @@ class InferenceContext: self.inferred[key] = tuple(results) + @contextlib.contextmanager + def restore_path(self): + path = set(self.path) + yield + self.path = path + def __str__(self): state = ( "%s=%s" diff --git a/astroid/decorators.py b/astroid/decorators.py index d24c588f..14487570 100644 --- a/astroid/decorators.py +++ b/astroid/decorators.py @@ -111,27 +111,31 @@ def path_wrapper(func): @wrapt.decorator def yes_if_nothing_inferred(func, instance, args, kwargs): - inferred = False - for node in func(*args, **kwargs): - inferred = True - yield node - if not inferred: + generator = func(*args, **kwargs) + + try: + yield next(generator) + except StopIteration: + # generator is empty yield util.Uninferable + return + + yield from generator @wrapt.decorator def raise_if_nothing_inferred(func, instance, args, kwargs): - inferred = False + generator = func(*args, **kwargs) + try: - generator = func(*args, **kwargs) - while True: - yield next(generator) - inferred = True + yield next(generator) except StopIteration as error: - if not inferred: - if error.args: - # pylint: disable=not-a-mapping - raise exceptions.InferenceError(**error.args[0]) - raise exceptions.InferenceError( - "StopIteration raised without any error information." - ) + # generator is empty + if error.args: + # pylint: disable=not-a-mapping + raise exceptions.InferenceError(**error.args[0]) + raise exceptions.InferenceError( + "StopIteration raised without any error information." + ) + + yield from generator diff --git a/astroid/helpers.py b/astroid/helpers.py index e58d1919..edbb205c 100644 --- a/astroid/helpers.py +++ b/astroid/helpers.py @@ -46,7 +46,7 @@ def _function_type(function, builtins): def _object_type(node, context=None): astroid_manager = manager.AstroidManager() - builtins = astroid_manager.astroid_cache[BUILTINS] + builtins = astroid_manager.builtins_module context = context or contextmod.InferenceContext() for inferred in node.infer(context=context): diff --git a/astroid/inference.py b/astroid/inference.py index 3836c090..16346a77 100644 --- a/astroid/inference.py +++ b/astroid/inference.py @@ -245,15 +245,6 @@ def infer_import(self, context=None, asname=True): nodes.Import._infer = infer_import -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 - - @decorators.raise_if_nothing_inferred @decorators.path_wrapper def infer_import_from(self, context=None, asname=True): @@ -283,7 +274,6 @@ def infer_import_from(self, context=None, asname=True): nodes.ImportFrom._infer = infer_import_from -@decorators.raise_if_nothing_inferred def infer_attribute(self, context=None): """infer an Attribute node by using getattr on the associated object""" for owner in self.expr.infer(context): @@ -320,8 +310,11 @@ def infer_attribute(self, context=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.Attribute._infer = decorators.raise_if_nothing_inferred( + decorators.path_wrapper(infer_attribute) +) +# won't work with a path wrapper +nodes.AssignAttr.infer_lhs = decorators.raise_if_nothing_inferred(infer_attribute) @decorators.raise_if_nothing_inferred @@ -883,15 +876,7 @@ def instance_getitem(self, index, context=None): "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.", - node=self, - index=index, - context=context, - ) from exc + return next(method.infer_call_result(self, new_context)) bases.Instance.getitem = instance_getitem diff --git a/astroid/interpreter/objectmodel.py b/astroid/interpreter/objectmodel.py index 65e9c641..f031022f 100644 --- a/astroid/interpreter/objectmodel.py +++ b/astroid/interpreter/objectmodel.py @@ -25,7 +25,6 @@ attribute. Thus the model can be viewed as a special part of the lookup mechanism. """ -import builtins import itertools import pprint import os @@ -38,6 +37,9 @@ from astroid import exceptions from astroid import node_classes +IMPL_PREFIX = "attr_" + + def _dunder_dict(instance, attributes): obj = node_classes.Dict(parent=instance) @@ -98,7 +100,9 @@ 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[len(IMPL_PREFIX) :] for obj in dir(self) if obj.startswith(IMPL_PREFIX) + ] def lookup(self, name): """Look up the given *name* in the current model @@ -108,26 +112,21 @@ class ObjectModel: """ if name in self.attributes(): - return getattr(self, "py" + name) + return getattr(self, IMPL_PREFIX + name) raise exceptions.AttributeInferenceError(target=self._instance, attribute=name) class ModuleModel(ObjectModel): def _builtins(self): - builtins_ast_module = astroid.MANAGER.astroid_cache[builtins.__name__] + builtins_ast_module = astroid.MANAGER.builtins_module return builtins_ast_module.special_attributes.lookup("__dict__") @property - def pybuiltins(self): + def attr_builtins(self): return self._builtins() - # __path__ is a standard attribute on *packages* not - # non-package modules. The only mention of it in the - # official 2.7 documentation I can find is in the - # tutorial. - @property - def py__path__(self): + def attr___path__(self): if not self._instance.package: raise exceptions.AttributeInferenceError( target=self._instance, attribute="__path__" @@ -149,25 +148,23 @@ class ModuleModel(ObjectModel): return container @property - def py__name__(self): + def attr___name__(self): return node_classes.Const(value=self._instance.name, parent=self._instance) @property - def py__doc__(self): + def attr___doc__(self): return node_classes.Const(value=self._instance.doc, parent=self._instance) @property - def py__file__(self): + def attr___file__(self): return node_classes.Const(value=self._instance.file, parent=self._instance) @property - def py__dict__(self): + def attr___dict__(self): return _dunder_dict(self._instance, self._instance.globals) - # __package__ isn't mentioned anywhere outside a PEP: - # https://www.python.org/dev/peps/pep-0366/ @property - def py__package__(self): + def attr___package__(self): if not self._instance.package: value = "" else: @@ -180,36 +177,36 @@ class ModuleModel(ObjectModel): # https://docs.python.org/3/reference/import.html#import-related-module-attributes @property - def py__spec__(self): + def attr___spec__(self): # No handling for now. return node_classes.Unknown() @property - def py__loader__(self): + def attr___loader__(self): # No handling for now. return node_classes.Unknown() @property - def py__cached__(self): + def attr___cached__(self): # No handling for now. return node_classes.Unknown() class FunctionModel(ObjectModel): @property - def py__name__(self): + def attr___name__(self): return node_classes.Const(value=self._instance.name, parent=self._instance) @property - def py__doc__(self): + def attr___doc__(self): return node_classes.Const(value=self._instance.doc, parent=self._instance) @property - def py__qualname__(self): + def attr___qualname__(self): return node_classes.Const(value=self._instance.qname(), parent=self._instance) @property - def py__defaults__(self): + def attr___defaults__(self): func = self._instance if not func.args.defaults: return node_classes.Const(value=None, parent=func) @@ -219,7 +216,7 @@ class FunctionModel(ObjectModel): return defaults_obj @property - def py__annotations__(self): + def attr___annotations__(self): obj = node_classes.Dict(parent=self._instance) if not self._instance.returns: @@ -252,13 +249,13 @@ class FunctionModel(ObjectModel): return obj @property - def py__dict__(self): + def attr___dict__(self): return node_classes.Dict(parent=self._instance) - py__globals__ = py__dict__ + attr___globals__ = attr___dict__ @property - def py__kwdefaults__(self): + def attr___kwdefaults__(self): def _default_args(args, parent): for arg in args.kwonlyargs: try: @@ -277,11 +274,11 @@ class FunctionModel(ObjectModel): return obj @property - def py__module__(self): + def attr___module__(self): return node_classes.Const(self._instance.root().qname()) @property - def py__get__(self): + def attr___get__(self): from astroid import bases func = self._instance @@ -361,51 +358,51 @@ class FunctionModel(ObjectModel): # These are here just for completion. @property - def py__ne__(self): + def attr___ne__(self): return node_classes.Unknown() - py__subclasshook__ = py__ne__ - py__str__ = py__ne__ - py__sizeof__ = py__ne__ - py__setattr__ = py__ne__ - py__repr__ = py__ne__ - py__reduce__ = py__ne__ - py__reduce_ex__ = py__ne__ - py__new__ = py__ne__ - py__lt__ = py__ne__ - py__eq__ = py__ne__ - py__gt__ = py__ne__ - py__format__ = py__ne__ - py__delattr__ = py__ne__ - py__getattribute__ = py__ne__ - py__hash__ = py__ne__ - py__init__ = py__ne__ - py__dir__ = py__ne__ - py__call__ = py__ne__ - py__class__ = py__ne__ - py__closure__ = py__ne__ - py__code__ = py__ne__ + attr___subclasshook__ = attr___ne__ + attr___str__ = attr___ne__ + attr___sizeof__ = attr___ne__ + attr___setattr___ = attr___ne__ + attr___repr__ = attr___ne__ + attr___reduce__ = attr___ne__ + attr___reduce_ex__ = attr___ne__ + attr___new__ = attr___ne__ + attr___lt__ = attr___ne__ + attr___eq__ = attr___ne__ + attr___gt__ = attr___ne__ + attr___format__ = attr___ne__ + attr___delattr___ = attr___ne__ + attr___getattribute__ = attr___ne__ + attr___hash__ = attr___ne__ + attr___init__ = attr___ne__ + attr___dir__ = attr___ne__ + attr___call__ = attr___ne__ + attr___class__ = attr___ne__ + attr___closure__ = attr___ne__ + attr___code__ = attr___ne__ class ClassModel(ObjectModel): @property - def py__module__(self): + def attr___module__(self): return node_classes.Const(self._instance.root().qname()) @property - def py__name__(self): + def attr___name__(self): return node_classes.Const(self._instance.name) @property - def py__qualname__(self): + def attr___qualname__(self): return node_classes.Const(self._instance.qname()) @property - def py__doc__(self): + def attr___doc__(self): return node_classes.Const(self._instance.doc) @property - def py__mro__(self): + def attr___mro__(self): if not self._instance.newstyle: raise exceptions.AttributeInferenceError( target=self._instance, attribute="__mro__" @@ -417,7 +414,7 @@ class ClassModel(ObjectModel): return obj @property - def pymro(self): + def attr_mro(self): if not self._instance.newstyle: raise exceptions.AttributeInferenceError( target=self._instance, attribute="mro" @@ -431,14 +428,14 @@ class ClassModel(ObjectModel): # The method we're returning is capable of inferring the underlying MRO though. class MroBoundMethod(bases.BoundMethod): def infer_call_result(self, caller, context=None): - yield other_self.py__mro__ + yield other_self.attr___mro__ implicit_metaclass = self._instance.implicit_metaclass() mro_method = implicit_metaclass.locals["mro"][0] return MroBoundMethod(proxy=mro_method, bound=implicit_metaclass) @property - def py__bases__(self): + def attr___bases__(self): obj = node_classes.Tuple() context = contextmod.InferenceContext() elts = list(self._instance._inferred_bases(context)) @@ -446,13 +443,13 @@ class ClassModel(ObjectModel): return obj @property - def py__class__(self): + def attr___class__(self): from astroid import helpers return helpers.object_type(self._instance) @property - def py__subclasses__(self): + def attr___subclasses__(self): """Get the subclasses of the underlying class This looks only in the current module for retrieving the subclasses, @@ -486,55 +483,55 @@ class ClassModel(ObjectModel): return SubclassesBoundMethod(proxy=subclasses_method, bound=implicit_metaclass) @property - def py__dict__(self): + def attr___dict__(self): return node_classes.Dict(parent=self._instance) class SuperModel(ObjectModel): @property - def py__thisclass__(self): + def attr___thisclass__(self): return self._instance.mro_pointer @property - def py__self_class__(self): + def attr___self_class__(self): return self._instance._self_class @property - def py__self__(self): + def attr___self__(self): return self._instance.type @property - def py__class__(self): + def attr___class__(self): return self._instance._proxied class UnboundMethodModel(ObjectModel): @property - def py__class__(self): + def attr___class__(self): from astroid import helpers return helpers.object_type(self._instance) @property - def py__func__(self): + def attr___func__(self): return self._instance._proxied @property - def py__self__(self): + def attr___self__(self): return node_classes.Const(value=None, parent=self._instance) - pyim_func = py__func__ - pyim_class = py__class__ - pyim_self = py__self__ + attr_im_func = attr___func__ + attr_im_class = attr___class__ + attr_im_self = attr___self__ class BoundMethodModel(FunctionModel): @property - def py__func__(self): + def attr___func__(self): return self._instance._proxied._proxied @property - def py__self__(self): + def attr___self__(self): return self._instance.bound @@ -542,23 +539,23 @@ 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.builtins_module["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), IMPL_PREFIX + name, property(patched)) return ret @property - def py__name__(self): + def attr___name__(self): return node_classes.Const( value=self._instance.parent.name, parent=self._instance ) @property - def py__doc__(self): + def attr___doc__(self): return node_classes.Const( value=self._instance.parent.doc, parent=self._instance ) @@ -568,7 +565,7 @@ 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__] + astroid_builtins = astroid.MANAGER.builtins_module generator = astroid_builtins.get("async_generator") if generator is None: # Make it backward compatible. @@ -578,47 +575,101 @@ class AsyncGeneratorModel(GeneratorModel): method = values[0] patched = lambda cls, meth=method: meth - setattr(type(ret), "py" + name, property(patched)) + setattr(type(ret), IMPL_PREFIX + name, property(patched)) return ret class InstanceModel(ObjectModel): @property - def py__class__(self): + def attr___class__(self): return self._instance._proxied @property - def py__module__(self): + def attr___module__(self): return node_classes.Const(self._instance.root().qname()) @property - def py__doc__(self): + def attr___doc__(self): return node_classes.Const(self._instance.doc) @property - def py__dict__(self): + def attr___dict__(self): return _dunder_dict(self._instance, self._instance.instance_attrs) +# Exception instances + + class ExceptionInstanceModel(InstanceModel): @property - def pyargs(self): + def attr_args(self): message = node_classes.Const("") args = node_classes.Tuple(parent=self._instance) args.postinit((message,)) return args @property - def py__traceback__(self): - builtins_ast_module = astroid.MANAGER.astroid_cache[builtins.__name__] + def attr___traceback__(self): + builtins_ast_module = astroid.MANAGER.builtins_module traceback_type = builtins_ast_module[types.TracebackType.__name__] return traceback_type.instantiate_class() +class SyntaxErrorInstanceModel(ExceptionInstanceModel): + @property + def attr_text(self): + return node_classes.Const("") + + +class OSErrorInstanceModel(ExceptionInstanceModel): + @property + def attr_filename(self): + return node_classes.Const("") + + @property + def attr_errno(self): + return node_classes.Const(0) + + attr_filename2 = attr_filename + + +class ImportErrorInstanceModel(ExceptionInstanceModel): + @property + def attr_name(self): + return node_classes.Const("") + + @property + def attr_path(self): + return node_classes.Const("") + + +BUILTIN_EXCEPTIONS = { + "builtins.SyntaxError": SyntaxErrorInstanceModel, + "builtins.ImportError": ImportErrorInstanceModel, + # These are all similar to OSError in terms of attributes + "builtins.OSError": OSErrorInstanceModel, + "builtins.BlockingIOError": OSErrorInstanceModel, + "builtins.BrokenPipeError": OSErrorInstanceModel, + "builtins.ChildProcessError": OSErrorInstanceModel, + "builtins.ConnectionAbortedError": OSErrorInstanceModel, + "builtins.ConnectionError": OSErrorInstanceModel, + "builtins.ConnectionRefusedError": OSErrorInstanceModel, + "builtins.ConnectionResetError": OSErrorInstanceModel, + "builtins.FileExistsError": OSErrorInstanceModel, + "builtins.FileNotFoundError": OSErrorInstanceModel, + "builtins.InterruptedError": OSErrorInstanceModel, + "builtins.IsADirectoryError": OSErrorInstanceModel, + "builtins.NotADirectoryError": OSErrorInstanceModel, + "builtins.PermissionError": OSErrorInstanceModel, + "builtins.ProcessLookupError": OSErrorInstanceModel, + "builtins.TimeoutError": OSErrorInstanceModel, +} + + class DictModel(ObjectModel): @property - def py__class__(self): + def attr___class__(self): return self._instance._proxied def _generic_dict_attribute(self, obj, name): @@ -632,7 +683,7 @@ class DictModel(ObjectModel): return DictMethodBoundMethod(proxy=meth, bound=self._instance) @property - def pyitems(self): + def attr_items(self): elems = [] obj = node_classes.List(parent=self._instance) for key, value in self._instance.items: @@ -648,7 +699,7 @@ class DictModel(ObjectModel): return self._generic_dict_attribute(obj, "items") @property - def pykeys(self): + def attr_keys(self): keys = [key for (key, _) in self._instance.items] obj = node_classes.List(parent=self._instance) obj.postinit(elts=keys) @@ -660,7 +711,7 @@ class DictModel(ObjectModel): return self._generic_dict_attribute(obj, "keys") @property - def pyvalues(self): + def attr_values(self): values = [value for (_, value) in self._instance.items] obj = node_classes.List(parent=self._instance) diff --git a/astroid/manager.py b/astroid/manager.py index f05588ae..4388514a 100644 --- a/astroid/manager.py +++ b/astroid/manager.py @@ -60,6 +60,10 @@ class AstroidManager: self.unregister_transform = self._transform.unregister_transform self.max_inferable_values = 100 + @property + def builtins_module(self): + return self.astroid_cache["builtins"] + def visit_transforms(self, node): """Visit the transforms and apply them to the given *node*.""" return self._transform.visit(node) @@ -307,13 +311,17 @@ class AstroidManager: """Cache a module if no module with the same name is known yet.""" self.astroid_cache.setdefault(module.name, module) - def clear_cache(self, astroid_builtin=None): - # XXX clear transforms - self.astroid_cache.clear() - # force bootstrap again, else we may ends up with cache inconsistency - # between the manager and CONST_PROXY, making - # unittest_lookup.LookupTC.test_builtin_lookup fail depending on the - # test order + def bootstrap(self): + """Bootstrap the required AST modules needed for the manager to work + + The bootstrap usually involves building the AST for the builtins + module, which is required by the rest of astroid to work correctly. + """ import astroid.raw_building - astroid.raw_building._astroid_bootstrapping(astroid_builtin=astroid_builtin) + astroid.raw_building._astroid_bootstrapping() + + def clear_cache(self): + """Clear the underlying cache. Also bootstraps the builtins module.""" + self.astroid_cache.clear() + self.bootstrap() diff --git a/astroid/node_classes.py b/astroid/node_classes.py index 7ef6b0a7..4e5f5612 100644 --- a/astroid/node_classes.py +++ b/astroid/node_classes.py @@ -3874,7 +3874,7 @@ class Slice(NodeNG): @decorators.cachedproperty def _proxied(self): - builtins = MANAGER.astroid_cache[BUILTINS] + builtins = MANAGER.builtins_module return builtins.getattr("slice")[0] def pytype(self): @@ -4166,8 +4166,7 @@ class TryFinally(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement): if ( isinstance(child, TryExcept) and child.fromlineno == self.fromlineno - and lineno > self.fromlineno - and lineno <= child.tolineno + and child.tolineno >= lineno > self.fromlineno ): return child.block_range(lineno) return self._elsed_block_range(lineno, self.finalbody) diff --git a/astroid/objects.py b/astroid/objects.py index 367f650e..b68d3596 100644 --- a/astroid/objects.py +++ b/astroid/objects.py @@ -43,7 +43,7 @@ class FrozenSet(node_classes._BaseContainer): @decorators.cachedproperty def _proxied(self): # pylint: disable=method-hidden - ast_builtins = MANAGER.astroid_cache[BUILTINS] + ast_builtins = MANAGER.builtins_module return ast_builtins.getattr("frozenset")[0] @@ -114,7 +114,7 @@ class Super(node_classes.NodeNG): @decorators.cachedproperty def _proxied(self): - ast_builtins = MANAGER.astroid_cache[BUILTINS] + ast_builtins = MANAGER.builtins_module return ast_builtins.getattr("super")[0] def pytype(self): @@ -210,10 +210,13 @@ class ExceptionInstance(bases.Instance): the case of .args. """ - # pylint: disable=unnecessary-lambda - special_attributes = util.lazy_descriptor( - lambda: objectmodel.ExceptionInstanceModel() - ) + @decorators.cachedproperty + def special_attributes(self): + qname = self.qname() + instance = objectmodel.BUILTIN_EXCEPTIONS.get( + qname, objectmodel.ExceptionInstanceModel + ) + return instance() class DictInstance(bases.Instance): diff --git a/astroid/protocols.py b/astroid/protocols.py index 86889b43..db0f5d9d 100644 --- a/astroid/protocols.py +++ b/astroid/protocols.py @@ -453,26 +453,23 @@ nodes.ExceptHandler.assigned_stmts = excepthandler_assigned_stmts def _infer_context_manager(self, mgr, context): - try: - inferred = next(mgr.infer(context=context)) - except (StopIteration, exceptions.InferenceError): - return + inferred = next(mgr.infer(context=context)) if isinstance(inferred, bases.Generator): # Check if it is decorated with contextlib.contextmanager. func = inferred.parent if not func.decorators: - return + raise exceptions.InferenceError( + "No decorators found on inferred generator %s", node=func + ) + for decorator_node in func.decorators.nodes: - try: - decorator = next(decorator_node.infer(context)) - except StopIteration: - return + decorator = next(decorator_node.infer(context)) if isinstance(decorator, nodes.FunctionDef): if decorator.qname() == _CONTEXTLIB_MGR: break else: # It doesn't interest us. - return + raise exceptions.InferenceError(node=func) # Get the first yield point. If it has multiple yields, # then a RuntimeError will be raised. @@ -493,17 +490,15 @@ def _infer_context_manager(self, mgr, context): elif isinstance(inferred, bases.Instance): try: enter = next(inferred.igetattr("__enter__", context=context)) - except ( - StopIteration, - exceptions.InferenceError, - exceptions.AttributeInferenceError, - ): - return + except (exceptions.InferenceError, exceptions.AttributeInferenceError): + raise exceptions.InferenceError(node=inferred) if not isinstance(enter, bases.BoundMethod): - return + raise exceptions.InferenceError(node=enter) if not context.callcontext: context.callcontext = contextmod.CallContext(args=[inferred]) yield from enter.infer_call_result(self, context) + else: + raise exceptions.InferenceError(node=mgr) @decorators.raise_if_nothing_inferred diff --git a/astroid/raw_building.py b/astroid/raw_building.py index 1cd6c81f..7707ea19 100644 --- a/astroid/raw_building.py +++ b/astroid/raw_building.py @@ -261,8 +261,6 @@ class InspectBuilder: FunctionDef and ClassDef nodes and some others as guessed. """ - # astroid from living objects ############################################### - def __init__(self): self._done = {} self._module = None @@ -380,17 +378,20 @@ class InspectBuilder: ### astroid bootstrapping ###################################################### -Astroid_BUILDER = InspectBuilder() _CONST_PROXY = {} +# TODO : find a nicer way to handle this situation; +def _set_proxied(const): + return _CONST_PROXY[const.value.__class__] + -def _astroid_bootstrapping(astroid_builtin=None): - """astroid boot strapping the builtins module""" +def _astroid_bootstrapping(): + """astroid bootstrapping the builtins module""" # this boot strapping is necessary since we need the Const nodes to # inspect_build builtins, and then we can proxy Const - if astroid_builtin is None: - astroid_builtin = Astroid_BUILDER.inspect_build(builtins) + builder = InspectBuilder() + astroid_builtin = builder.inspect_build(builtins) # pylint: disable=redefined-outer-name for cls, node_cls in node_classes.CONST_CLS.items(): @@ -407,52 +408,42 @@ def _astroid_bootstrapping(astroid_builtin=None): else: _CONST_PROXY[cls] = proxy + # Set the builtin module as parent for some builtins. + nodes.Const._proxied = property(_set_proxied) -_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.parent = MANAGER.astroid_cache[builtins.__name__] -bases.Generator._proxied = _GeneratorType -Astroid_BUILDER.object_build(bases.Generator._proxied, types.GeneratorType) - -if hasattr(types, "AsyncGeneratorType"): - # pylint: disable=no-member; AsyncGeneratorType - _AsyncGeneratorType = nodes.ClassDef( - types.AsyncGeneratorType.__name__, types.AsyncGeneratorType.__doc__ + _GeneratorType = nodes.ClassDef( + types.GeneratorType.__name__, types.GeneratorType.__doc__ ) - _AsyncGeneratorType.parent = MANAGER.astroid_cache[builtins.__name__] - bases.AsyncGenerator._proxied = _AsyncGeneratorType - Astroid_BUILDER.object_build( - bases.AsyncGenerator._proxied, types.AsyncGeneratorType + _GeneratorType.parent = astroid_builtin + bases.Generator._proxied = _GeneratorType + builder.object_build(bases.Generator._proxied, types.GeneratorType) + + if hasattr(types, "AsyncGeneratorType"): + # pylint: disable=no-member; AsyncGeneratorType + _AsyncGeneratorType = nodes.ClassDef( + types.AsyncGeneratorType.__name__, types.AsyncGeneratorType.__doc__ + ) + _AsyncGeneratorType.parent = astroid_builtin + bases.AsyncGenerator._proxied = _AsyncGeneratorType + builder.object_build(bases.AsyncGenerator._proxied, types.AsyncGeneratorType) + builtin_types = ( + types.GetSetDescriptorType, + types.GeneratorType, + types.MemberDescriptorType, + type(None), + type(NotImplemented), + types.FunctionType, + types.MethodType, + types.BuiltinFunctionType, + types.ModuleType, + types.TracebackType, ) -# 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, -) -for _type in BUILTIN_TYPES: - if _type.__name__ not in _builtins: - cls = nodes.ClassDef(_type.__name__, _type.__doc__) - cls.parent = MANAGER.astroid_cache[builtins.__name__] - Astroid_BUILDER.object_build(cls, _type) - _builtins[_type.__name__] = cls + for _type in builtin_types: + if _type.__name__ not in astroid_builtin: + cls = nodes.ClassDef(_type.__name__, _type.__doc__) + cls.parent = astroid_builtin + builder.object_build(cls, _type) + astroid_builtin[_type.__name__] = cls + + +_astroid_bootstrapping() diff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py index 6e580d54..b94fbe49 100644 --- a/astroid/scoped_nodes.py +++ b/astroid/scoped_nodes.py @@ -1920,10 +1920,10 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement :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.attr___module__),) if sys.version_info >= (3, 3): # __qualname__ is defined in PEP3155 - locals_ += (("__qualname__", self.special_attributes.py__qualname__),) + locals_ += (("__qualname__", self.special_attributes.attr___qualname__),) return locals_ # pylint: disable=redefined-outer-name @@ -2134,7 +2134,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement # inside this class. lookup_upper_frame = ( isinstance(node.parent, node_classes.Decorators) - and name in MANAGER.astroid_cache[builtins.__name__] + and name in MANAGER.builtins_module ) if ( any(node == base or base.parent_of(node) for base in self.bases) @@ -2190,30 +2190,31 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement return for stmt in self.bases: - try: - for baseobj in stmt.infer(context): - if not isinstance(baseobj, ClassDef): - if isinstance(baseobj, bases.Instance): - baseobj = baseobj._proxied - else: - continue - if not baseobj.hide: - if baseobj in yielded: - continue - yielded.add(baseobj) - yield baseobj - if not recurs: - continue - for grandpa in baseobj.ancestors(recurs=True, context=context): - if grandpa is self: - # This class is the ancestor of itself. - break - if grandpa in yielded: + with context.restore_path(): + try: + for baseobj in stmt.infer(context): + if not isinstance(baseobj, ClassDef): + if isinstance(baseobj, bases.Instance): + baseobj = baseobj._proxied + else: + continue + if not baseobj.hide: + if baseobj in yielded: + continue + yielded.add(baseobj) + yield baseobj + if not recurs: continue - yielded.add(grandpa) - yield grandpa - except exceptions.InferenceError: - continue + for grandpa in baseobj.ancestors(recurs=True, context=context): + if grandpa is self: + # This class is the ancestor of itself. + break + if grandpa in yielded: + continue + yielded.add(grandpa) + yield grandpa + except exceptions.InferenceError: + continue def local_attr_ancestors(self, name, context=None): """Iterate over the parents that define the given name. @@ -2763,21 +2764,14 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement _verify_duplicates_mro(unmerged_mro, self, context) return _c3_merge(unmerged_mro, self, context) - def mro(self, context=None): + def mro(self, context=None) -> List["ClassDef"]: """Get the method resolution order, using C3 linearization. :returns: The list of ancestors, sorted by the mro. :rtype: list(NodeNG) - - :raises NotImplementedError: If this is an old style class, - since they don't have the concept of an MRO. :raises DuplicateBasesError: Duplicate bases in the same class base :raises InconsistentMroError: A class' MRO is inconsistent """ - - if not self.newstyle: - raise NotImplementedError("Could not obtain mro for old-style classes.") - return self._compute_mro(context=context) def bool_value(self): diff --git a/astroid/tests/unittest_brain.py b/astroid/tests/unittest_brain.py index 55936009..031bce7a 100644 --- a/astroid/tests/unittest_brain.py +++ b/astroid/tests/unittest_brain.py @@ -740,6 +740,30 @@ class EnumBrainTest(unittest.TestCase): isinstance(elem, astroid.Const) and elem.value == 1 for elem in inferred_int ) + def test_mingled_single_and_double_quotes_does_not_crash(self): + node = builder.extract_node( + """ + from enum import Enum + class A(Enum): + a = 'x"y"' + A.a.value #@ + """ + ) + inferred_string = next(node.infer()) + assert inferred_string.value == 'x"y"' + + def test_special_characters_does_not_crash(self): + node = builder.extract_node( + """ + import enum + class Example(enum.Enum): + NULL = '\\N{NULL}' + Example.NULL.value + """ + ) + inferred_string = next(node.infer()) + assert inferred_string.value == "\N{NULL}" + @unittest.skipUnless(HAS_DATEUTIL, "This test requires the dateutil library.") class DateutilBrainTest(unittest.TestCase): @@ -1761,5 +1785,19 @@ class TestFunctoolsPartial: assert inferred.value == expected_value +@pytest.mark.skipif( + sys.version_info[:2] == (3, 4), reason="Not a problem on Python 3.4" +) +def test_http_client_brain(): + node = astroid.extract_node( + """ + from http.client import OK + OK + """ + ) + inferred = next(node.infer()) + assert isinstance(inferred, astroid.Instance) + + if __name__ == "__main__": unittest.main() diff --git a/astroid/tests/unittest_manager.py b/astroid/tests/unittest_manager.py index 505bdf56..5629b4ff 100644 --- a/astroid/tests/unittest_manager.py +++ b/astroid/tests/unittest_manager.py @@ -19,6 +19,7 @@ import unittest import pkg_resources import six +import time import astroid from astroid import exceptions @@ -45,7 +46,6 @@ class AstroidManagerTest( def setUp(self): super(AstroidManagerTest, self).setUp() self.manager = manager.AstroidManager() - self.manager.clear_cache(self._builtins) # take care of borg def test_ast_from_file(self): filepath = unittest.__file__ @@ -235,8 +235,6 @@ class AstroidManagerTest( 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) diff --git a/astroid/tests/unittest_modutils.py b/astroid/tests/unittest_modutils.py index ae4ac245..6f1bae14 100644 --- a/astroid/tests/unittest_modutils.py +++ b/astroid/tests/unittest_modutils.py @@ -300,9 +300,6 @@ class IsRelativeTest(unittest.TestCase): def test_knownValues_is_relative_1(self): 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__)) - def test_knownValues_is_relative_3(self): self.assertFalse(modutils.is_relative("astroid", astroid.__path__[0])) diff --git a/astroid/tests/unittest_object_model.py b/astroid/tests/unittest_object_model.py index 496cd479..81e2b3a6 100644 --- a/astroid/tests/unittest_object_model.py +++ b/astroid/tests/unittest_object_model.py @@ -564,7 +564,7 @@ class GeneratorModelTest(unittest.TestCase): class ExceptionModelTest(unittest.TestCase): - def test_model_py3(self): + def test_valueerror_py3(self): ast_nodes = builder.extract_node( """ try: @@ -585,6 +585,50 @@ class ExceptionModelTest(unittest.TestCase): with self.assertRaises(exceptions.InferenceError): next(ast_nodes[2].infer()) + def test_syntax_error(self): + ast_node = builder.extract_node( + """ + try: + x[42] + except SyntaxError as err: + err.text #@ + """ + ) + inferred = next(ast_node.infer()) + assert isinstance(inferred, astroid.Const) + + def test_oserror(self): + ast_nodes = builder.extract_node( + """ + try: + raise OSError("a") + except OSError as err: + err.filename #@ + err.filename2 #@ + err.errno #@ + """ + ) + expected_values = ["", "", 0] + for node, value in zip(ast_nodes, expected_values): + inferred = next(node.infer()) + assert isinstance(inferred, astroid.Const) + assert inferred.value == value + + def test_import_error(self): + ast_nodes = builder.extract_node( + """ + try: + raise ImportError("a") + except ImportError as err: + err.name #@ + err.path #@ + """ + ) + for node in ast_nodes: + inferred = next(node.infer()) + assert isinstance(inferred, astroid.Const) + assert inferred.value == "" + class DictObjectModelTest(unittest.TestCase): def test__class__(self): diff --git a/astroid/tests/unittest_regrtest.py b/astroid/tests/unittest_regrtest.py index b83fa69f..50e9aa6c 100644 --- a/astroid/tests/unittest_regrtest.py +++ b/astroid/tests/unittest_regrtest.py @@ -33,10 +33,6 @@ class NonRegressionTests(resources.AstroidCacheSetupMixin, unittest.TestCase): MANAGER.astroid_cache[BUILTINS] = self._builtins def tearDown(self): - # Since we may have created a brainless manager, leading - # to a new cache builtin module and proxy classes in the constants, - # clear out the global manager cache. - MANAGER.clear_cache(self._builtins) MANAGER.always_load_extensions = False sys.path.pop(0) sys.path_importer_cache.pop(resources.find("data"), None) @@ -129,7 +129,9 @@ disable=fixme,invalid-name, missing-docstring, too-few-public-methods, # We'll have to disable this until we drop support for Python 2 stop-iteration-return, # black handles these - format + format, + # temporary until we fix the problems with InferenceContexts + no-member [BASIC] |
