From 16f69882f14a2946c6bb14fd82be27d377e1ac3e Mon Sep 17 00:00:00 2001 From: hippo91 Date: Sun, 13 Jan 2019 14:39:58 +0100 Subject: Refactoring chained comparison (#636) Reformat a chained comparison so that no more 'chained-comparison' warning is emitted from node_classe.py --- astroid/node_classes.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/astroid/node_classes.py b/astroid/node_classes.py index 7ef6b0a7..fe6f6bbb 100644 --- a/astroid/node_classes.py +++ b/astroid/node_classes.py @@ -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) -- cgit v1.2.1 From fd41070d76f323f089a120c72fb9b0d87e7f4a20 Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Sun, 13 Jan 2019 15:07:31 +0100 Subject: Prevent crashing when processing ``enums`` with mixed single and double quotes. Close PyCQA/pylint#2676 --- ChangeLog | 4 ++++ astroid/brain/brain_namedtuple_enum.py | 2 +- astroid/tests/unittest_brain.py | 24 ++++++++++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/ChangeLog b/ChangeLog index d81b58de..fc50430e 100644 --- a/ChangeLog +++ b/ChangeLog @@ -7,6 +7,10 @@ What's New in astroid 2.2.0? Release Date: TBA +* 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 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/tests/unittest_brain.py b/astroid/tests/unittest_brain.py index 55936009..5b9c68b8 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): -- cgit v1.2.1 From 51891dc8179a709bf18c7f2869ca32f2ec8a2e92 Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Sun, 13 Jan 2019 16:06:53 +0100 Subject: Move infer_name_module() in pylint and remove it from here --- astroid/inference.py | 9 --------- 1 file changed, 9 deletions(-) diff --git a/astroid/inference.py b/astroid/inference.py index 3836c090..09c6eb60 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): -- cgit v1.2.1 From 4ae06d58e9f6fd94d0b0f1497b665b027777a1a7 Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Mon, 14 Jan 2019 15:14:21 +0100 Subject: Remove test that does not work actually work consistently on all Python versions --- astroid/tests/unittest_modutils.py | 3 --- 1 file changed, 3 deletions(-) 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])) -- cgit v1.2.1 From 7197fb7287505388bbf7af1c73adaf09bf3b04f5 Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Tue, 15 Jan 2019 14:05:14 +0100 Subject: Disable the pylint job until we fix the clone inference bugs --- .travis.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 1d8e90d7..e77bc82a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,10 +6,11 @@ stages: jobs: include: + #- stage: prechecks + # python: 3.6 + # env: TOXENV=pylint - stage: prechecks python: 3.6 - env: TOXENV=pylint - - python: 3.6 env: TOXENV=formatting - stage: tests python: 3.4 -- cgit v1.2.1 From e2f3dbd62e7e090c95bba1d9bc487c56c25b954a Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Tue, 15 Jan 2019 14:05:57 +0100 Subject: Revert "Disable the pylint job until we fix the clone inference bugs" This reverts commit 7197fb7287505388bbf7af1c73adaf09bf3b04f5. Disable just no-member instead of disabling everything. --- .travis.yml | 5 ++--- pylintrc | 4 +++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index e77bc82a..1d8e90d7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,11 +6,10 @@ stages: jobs: include: - #- stage: prechecks - # python: 3.6 - # env: TOXENV=pylint - stage: prechecks python: 3.6 + env: TOXENV=pylint + - python: 3.6 env: TOXENV=formatting - stage: tests python: 3.4 diff --git a/pylintrc b/pylintrc index 2228e1c4..b752ee50 100644 --- a/pylintrc +++ b/pylintrc @@ -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] -- cgit v1.2.1 From 04856ecc2af19486689a9965c0075d4ce119b2cd Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Wed, 16 Jan 2019 15:10:21 +0100 Subject: Add brain tips for `http.client`. Close PyCQA/pylint#2687 --- ChangeLog | 2 + astroid/brain/brain_http.py | 81 +++++++++++++++++++++++++++++++++++++++++ astroid/tests/unittest_brain.py | 11 ++++++ 3 files changed, 94 insertions(+) create mode 100644 astroid/brain/brain_http.py diff --git a/ChangeLog b/ChangeLog index fc50430e..bf964afe 100644 --- a/ChangeLog +++ b/ChangeLog @@ -7,6 +7,8 @@ What's New in astroid 2.2.0? Release Date: TBA +* 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 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 + +# 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/tests/unittest_brain.py b/astroid/tests/unittest_brain.py index 5b9c68b8..b7a750e5 100644 --- a/astroid/tests/unittest_brain.py +++ b/astroid/tests/unittest_brain.py @@ -1785,5 +1785,16 @@ class TestFunctoolsPartial: assert inferred.value == expected_value +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() -- cgit v1.2.1 From 7fa547be48d6192e2572b9ade25f490bbd6ec0b4 Mon Sep 17 00:00:00 2001 From: Nick Drozd Date: Tue, 6 Nov 2018 09:18:21 -0600 Subject: Cut generator flags This simplifies the code, and may slightly improve performance. --- astroid/decorators.py | 38 +++++++++++++++++++++----------------- 1 file changed, 21 insertions(+), 17 deletions(-) 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 -- cgit v1.2.1 From 0d4f73d02943b77739e4d0053f20d9aac855b1f0 Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Thu, 17 Jan 2019 14:59:20 +0100 Subject: Revert "Remove the restore_path() method" This reverts commit 8151853e9525252b75ae560273a709cbed47ddc5 which was added while investigating the slowdown caused by context's path copying. Turns out this change doesn't have a negative impact on the performance but it has a positive one on the inference. --- astroid/context.py | 8 +++++++- astroid/scoped_nodes.py | 47 ++++++++++++++++++++++++----------------------- 2 files changed, 31 insertions(+), 24 deletions(-) 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/scoped_nodes.py b/astroid/scoped_nodes.py index 6e580d54..4f552910 100644 --- a/astroid/scoped_nodes.py +++ b/astroid/scoped_nodes.py @@ -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. -- cgit v1.2.1 From 041366cc7a0fecaccbb17421571f996cc645fe26 Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Thu, 17 Jan 2019 15:24:04 +0100 Subject: Add a registry for builtin exception models. Close PyCQA/pylint#1432 --- ChangeLog | 2 ++ astroid/interpreter/objectmodel.py | 12 ++++++++++++ astroid/objects.py | 11 +++++++---- astroid/tests/unittest_object_model.py | 12 ++++++++++++ 4 files changed, 33 insertions(+), 4 deletions(-) diff --git a/ChangeLog b/ChangeLog index bf964afe..a6646b3f 100644 --- a/ChangeLog +++ b/ChangeLog @@ -7,6 +7,8 @@ What's New in astroid 2.2.0? Release Date: TBA +* 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. diff --git a/astroid/interpreter/objectmodel.py b/astroid/interpreter/objectmodel.py index 65e9c641..746f6ba6 100644 --- a/astroid/interpreter/objectmodel.py +++ b/astroid/interpreter/objectmodel.py @@ -601,6 +601,9 @@ class InstanceModel(ObjectModel): return _dunder_dict(self._instance, self._instance.instance_attrs) +# Exception instances + + class ExceptionInstanceModel(InstanceModel): @property def pyargs(self): @@ -616,6 +619,15 @@ class ExceptionInstanceModel(InstanceModel): return traceback_type.instantiate_class() +class SyntaxErrorInstanceModel(ExceptionInstanceModel): + @property + def pytext(self): + return node_classes.Const("") + + +BUILTIN_EXCEPTIONS = {"builtins.SyntaxError": SyntaxErrorInstanceModel} + + class DictModel(ObjectModel): @property def py__class__(self): diff --git a/astroid/objects.py b/astroid/objects.py index 367f650e..1a071b2c 100644 --- a/astroid/objects.py +++ b/astroid/objects.py @@ -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/tests/unittest_object_model.py b/astroid/tests/unittest_object_model.py index 496cd479..0923389b 100644 --- a/astroid/tests/unittest_object_model.py +++ b/astroid/tests/unittest_object_model.py @@ -585,6 +585,18 @@ 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) + class DictObjectModelTest(unittest.TestCase): def test__class__(self): -- cgit v1.2.1 From 964cbb76a3e3af32af297b717a613a0c7df94d07 Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Thu, 17 Jan 2019 15:28:05 +0100 Subject: Disable test on Python 3.4 --- astroid/tests/unittest_brain.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/astroid/tests/unittest_brain.py b/astroid/tests/unittest_brain.py index b7a750e5..c5bad5fe 100644 --- a/astroid/tests/unittest_brain.py +++ b/astroid/tests/unittest_brain.py @@ -1785,6 +1785,9 @@ class TestFunctoolsPartial: assert inferred.value == expected_value +@pytest.mark.skipunless( + sys.version_info[:2] > (3, 4), reason="Not a problem on Python 3.4" +) def test_http_client_brain(): node = astroid.extract_node( """ -- cgit v1.2.1 From 7eaf1bee72d9181b32a198085b41e8317d33b9eb Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Thu, 17 Jan 2019 22:20:00 +0100 Subject: Change the filter to use equal --- astroid/tests/unittest_brain.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/astroid/tests/unittest_brain.py b/astroid/tests/unittest_brain.py index c5bad5fe..031bce7a 100644 --- a/astroid/tests/unittest_brain.py +++ b/astroid/tests/unittest_brain.py @@ -1785,8 +1785,8 @@ class TestFunctoolsPartial: assert inferred.value == expected_value -@pytest.mark.skipunless( - sys.version_info[:2] > (3, 4), reason="Not a problem on Python 3.4" +@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( -- cgit v1.2.1 From f6dc0f45045b70b1487f94c5cc8beba22e31695f Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Fri, 18 Jan 2019 18:30:53 +0100 Subject: Use a different prefix for the object model methods `py` is a bit confusing, instead a new constant is used. --- astroid/brain/brain_functools.py | 6 +- astroid/interpreter/objectmodel.py | 176 ++++++++++++++++++------------------- astroid/scoped_nodes.py | 4 +- 3 files changed, 92 insertions(+), 94 deletions(-) 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/interpreter/objectmodel.py b/astroid/interpreter/objectmodel.py index 746f6ba6..918cb06d 100644 --- a/astroid/interpreter/objectmodel.py +++ b/astroid/interpreter/objectmodel.py @@ -38,6 +38,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 +101,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,7 +113,7 @@ 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) @@ -118,16 +123,11 @@ class ModuleModel(ObjectModel): 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 +149,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 +178,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 +217,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 +250,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 +275,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 +359,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 +415,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 +429,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 +444,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 +484,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 @@ -547,18 +545,18 @@ class GeneratorModel(FunctionModel): 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 ) @@ -578,26 +576,26 @@ 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) @@ -606,14 +604,14 @@ class InstanceModel(ObjectModel): 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): + def attr___traceback__(self): builtins_ast_module = astroid.MANAGER.astroid_cache[builtins.__name__] traceback_type = builtins_ast_module[types.TracebackType.__name__] return traceback_type.instantiate_class() @@ -621,7 +619,7 @@ class ExceptionInstanceModel(InstanceModel): class SyntaxErrorInstanceModel(ExceptionInstanceModel): @property - def pytext(self): + def attr_text(self): return node_classes.Const("") @@ -630,7 +628,7 @@ BUILTIN_EXCEPTIONS = {"builtins.SyntaxError": SyntaxErrorInstanceModel} class DictModel(ObjectModel): @property - def py__class__(self): + def attr___class__(self): return self._instance._proxied def _generic_dict_attribute(self, obj, name): @@ -644,7 +642,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: @@ -660,7 +658,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) @@ -672,7 +670,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/scoped_nodes.py b/astroid/scoped_nodes.py index 4f552910..13721adc 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 -- cgit v1.2.1 From 0e1ab4ac02b1946851496585459930f0d7b6f03e Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Fri, 18 Jan 2019 18:48:13 +0100 Subject: Added more builtin exceptions attributes. Close #580 --- ChangeLog | 2 ++ astroid/interpreter/objectmodel.py | 44 +++++++++++++++++++++++++++++++++- astroid/tests/unittest_object_model.py | 34 +++++++++++++++++++++++++- 3 files changed, 78 insertions(+), 2 deletions(-) diff --git a/ChangeLog b/ChangeLog index a6646b3f..f12a3534 100644 --- a/ChangeLog +++ b/ChangeLog @@ -7,6 +7,8 @@ What's New in astroid 2.2.0? Release Date: TBA +* 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 diff --git a/astroid/interpreter/objectmodel.py b/astroid/interpreter/objectmodel.py index 918cb06d..c9da8023 100644 --- a/astroid/interpreter/objectmodel.py +++ b/astroid/interpreter/objectmodel.py @@ -623,7 +623,49 @@ class SyntaxErrorInstanceModel(ExceptionInstanceModel): return node_classes.Const("") -BUILTIN_EXCEPTIONS = {"builtins.SyntaxError": SyntaxErrorInstanceModel} +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): diff --git a/astroid/tests/unittest_object_model.py b/astroid/tests/unittest_object_model.py index 0923389b..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: @@ -597,6 +597,38 @@ class ExceptionModelTest(unittest.TestCase): 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): -- cgit v1.2.1 From 02699bad102678273dcd6bbeb7d3f6100f4547fb Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Fri, 18 Jan 2019 18:54:30 +0100 Subject: Remove StopIteration handling which should not leak at all from inference --- astroid/inference.py | 10 +--------- astroid/protocols.py | 13 +++---------- 2 files changed, 4 insertions(+), 19 deletions(-) diff --git a/astroid/inference.py b/astroid/inference.py index 09c6eb60..dbcf8a62 100644 --- a/astroid/inference.py +++ b/astroid/inference.py @@ -874,15 +874,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/protocols.py b/astroid/protocols.py index 86889b43..f3032caf 100644 --- a/astroid/protocols.py +++ b/astroid/protocols.py @@ -455,7 +455,7 @@ 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): + except exceptions.InferenceError: return if isinstance(inferred, bases.Generator): # Check if it is decorated with contextlib.contextmanager. @@ -463,10 +463,7 @@ def _infer_context_manager(self, mgr, context): if not func.decorators: return 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 @@ -493,11 +490,7 @@ 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, - ): + except (exceptions.InferenceError, exceptions.AttributeInferenceError): return if not isinstance(enter, bases.BoundMethod): return -- cgit v1.2.1 From b96f9f1e40845dd192877672040eedefea8a28f2 Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Sat, 19 Jan 2019 00:01:39 +0100 Subject: Replace a couple of returns with explicit InferenceError exceptions --- astroid/protocols.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/astroid/protocols.py b/astroid/protocols.py index f3032caf..db0f5d9d 100644 --- a/astroid/protocols.py +++ b/astroid/protocols.py @@ -453,15 +453,15 @@ nodes.ExceptHandler.assigned_stmts = excepthandler_assigned_stmts def _infer_context_manager(self, mgr, context): - try: - inferred = next(mgr.infer(context=context)) - except 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: decorator = next(decorator_node.infer(context)) if isinstance(decorator, nodes.FunctionDef): @@ -469,7 +469,7 @@ def _infer_context_manager(self, mgr, context): 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. @@ -491,12 +491,14 @@ def _infer_context_manager(self, mgr, context): try: enter = next(inferred.igetattr("__enter__", context=context)) except (exceptions.InferenceError, exceptions.AttributeInferenceError): - return + 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 -- cgit v1.2.1 From 931415b9a98ee5c9ed5bfef89c8e0901dd6a3c60 Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Sat, 19 Jan 2019 00:02:11 +0100 Subject: Make sure that Attribute.infer has a protection against StopIterations --- astroid/inference.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/astroid/inference.py b/astroid/inference.py index dbcf8a62..16346a77 100644 --- a/astroid/inference.py +++ b/astroid/inference.py @@ -274,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): @@ -311,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 -- cgit v1.2.1 From 41a6d4d127d285dc4bcbff875a6990afa0035e96 Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Sat, 19 Jan 2019 04:08:33 +0100 Subject: Add a method to the manager to retrieve the builtins module --- astroid/brain/brain_builtin_inference.py | 4 +--- astroid/helpers.py | 2 +- astroid/interpreter/objectmodel.py | 9 ++++----- astroid/manager.py | 4 ++++ astroid/node_classes.py | 2 +- astroid/objects.py | 4 ++-- astroid/scoped_nodes.py | 2 +- astroid/tests/unittest_inference.py | 22 ++++++++++++++++++++-- 8 files changed, 34 insertions(+), 15 deletions(-) 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/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/interpreter/objectmodel.py b/astroid/interpreter/objectmodel.py index c9da8023..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 @@ -119,7 +118,7 @@ class ObjectModel: 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 @@ -540,7 +539,7 @@ 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 @@ -566,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. @@ -612,7 +611,7 @@ class ExceptionInstanceModel(InstanceModel): @property def attr___traceback__(self): - builtins_ast_module = astroid.MANAGER.astroid_cache[builtins.__name__] + builtins_ast_module = astroid.MANAGER.builtins_module traceback_type = builtins_ast_module[types.TracebackType.__name__] return traceback_type.instantiate_class() diff --git a/astroid/manager.py b/astroid/manager.py index f05588ae..c7295b57 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) diff --git a/astroid/node_classes.py b/astroid/node_classes.py index fe6f6bbb..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): diff --git a/astroid/objects.py b/astroid/objects.py index 1a071b2c..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): diff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py index 13721adc..5457e1ff 100644 --- a/astroid/scoped_nodes.py +++ b/astroid/scoped_nodes.py @@ -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) diff --git a/astroid/tests/unittest_inference.py b/astroid/tests/unittest_inference.py index 420e528c..9592b437 100644 --- a/astroid/tests/unittest_inference.py +++ b/astroid/tests/unittest_inference.py @@ -31,10 +31,10 @@ from unittest.mock import patch import pytest -from astroid import InferenceError, builder, nodes +from astroid import InferenceError, builder, nodes, MANAGER 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, Generator from astroid import arguments from astroid import decorators as decoratorsmod from astroid import exceptions @@ -5072,5 +5072,23 @@ def test_inferred_sequence_unpacking_works(): assert [value.value for value in inferred.elts] == [1, 2] +def test_separate_cache_object(): + code = extract_node( + """ + def loop_gen(): + for y in test_gen(): + yield y + + def test_gen(): + yield "yield" + return + test_gen() + """ + ) + MANAGER.clear_cache() + inferred = next(code.infer()) + assert isinstance(inferred, Generator) + + if __name__ == "__main__": unittest.main() -- cgit v1.2.1 From 92cc7637f5a89bf348c4d3fb2e4a1edc7c696ded Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Sat, 19 Jan 2019 17:41:54 +0100 Subject: 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 --- ChangeLog | 6 ++++++ astroid/scoped_nodes.py | 9 +-------- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/ChangeLog b/ChangeLog index f12a3534..a13247f2 100644 --- a/ChangeLog +++ b/ChangeLog @@ -7,6 +7,12 @@ 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 diff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py index 5457e1ff..b94fbe49 100644 --- a/astroid/scoped_nodes.py +++ b/astroid/scoped_nodes.py @@ -2764,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): -- cgit v1.2.1 From 7eba7bf6bc3dbcff35fa429b3fb80459f9453056 Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Sun, 20 Jan 2019 01:59:42 +0100 Subject: Remove inadvertent test which still does not have a fix --- astroid/tests/unittest_inference.py | 22 ++-------------------- 1 file changed, 2 insertions(+), 20 deletions(-) diff --git a/astroid/tests/unittest_inference.py b/astroid/tests/unittest_inference.py index 9592b437..420e528c 100644 --- a/astroid/tests/unittest_inference.py +++ b/astroid/tests/unittest_inference.py @@ -31,10 +31,10 @@ from unittest.mock import patch import pytest -from astroid import InferenceError, builder, nodes, MANAGER +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, Generator +from astroid.bases import Instance, BoundMethod, UnboundMethod, BUILTINS from astroid import arguments from astroid import decorators as decoratorsmod from astroid import exceptions @@ -5072,23 +5072,5 @@ def test_inferred_sequence_unpacking_works(): assert [value.value for value in inferred.elts] == [1, 2] -def test_separate_cache_object(): - code = extract_node( - """ - def loop_gen(): - for y in test_gen(): - yield y - - def test_gen(): - yield "yield" - return - test_gen() - """ - ) - MANAGER.clear_cache() - inferred = next(code.infer()) - assert isinstance(inferred, Generator) - - if __name__ == "__main__": unittest.main() -- cgit v1.2.1 From e2df6d80b973853405456dd16551faa48c8d8905 Mon Sep 17 00:00:00 2001 From: Bianca Power <30207144+biancapower@users.noreply.github.com> Date: Mon, 21 Jan 2019 02:14:11 +1100 Subject: Fix typo in description for brain_attrs (#638) --- ChangeLog | 2 ++ astroid/brain/brain_attrs.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/ChangeLog b/ChangeLog index a13247f2..0b2740fb 100644 --- a/ChangeLog +++ b/ChangeLog @@ -37,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/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 -- cgit v1.2.1 From d7509faaae24ab6bb64435c8bcb3ad9652b949a8 Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Sun, 20 Jan 2019 16:15:54 +0100 Subject: Adjust the pull request template a little bit --- .github/PULL_REQUEST_TEMPLATE.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 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 - -- cgit v1.2.1 From 6f3149a643c04c47b308688af4fe99ed129f0e61 Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Sun, 20 Jan 2019 17:42:57 +0100 Subject: Make the astroid bootstrapping take care of builtins such as Generator Currently the astroid bootstrapping function, which builds the builtins module and relevant builtin objects, does not rebuild objects such as generators. This is causing a problem when the cache is cleared, e.g. from pylint's side, given that objects such as generator will not be present any longer in the builtins module created *after* the cache was cleared with MANAGER.cache_clear(). This behaviour was making that function useless from this point of view. The new change instead makes sure to build everything in the same function. Close #446 --- astroid/manager.py | 20 ++++---- astroid/raw_building.py | 97 +++++++++++++++++--------------------- astroid/tests/unittest_manager.py | 4 +- astroid/tests/unittest_regrtest.py | 4 -- 4 files changed, 57 insertions(+), 68 deletions(-) diff --git a/astroid/manager.py b/astroid/manager.py index c7295b57..4388514a 100644 --- a/astroid/manager.py +++ b/astroid/manager.py @@ -311,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/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/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_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) -- cgit v1.2.1 From 94bb94f2af823489733af2428356df56c6cbb7c8 Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Sun, 20 Jan 2019 17:51:53 +0100 Subject: Prepare a dev release --- astroid/__pkginfo__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 = {} -- cgit v1.2.1