all_hints_text string | base_commit string | commit_urls list | created_at timestamp[s] | hints_text string | instance_id string | issue_numbers list | language string | patch string | problem_statement string | pull_number string | repo string | test_patch string | version string | FAIL_TO_PASS list | PASS_TO_PASS list | test_cmds list | log_parser string | difficulty dict |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Makes sense.
This happens because the inference for functions looks through each return value here (https://github.com/PyCQA/astroid/blob/629c92db2dc1b016f4bf47645c95c42e65fd3bd6/astroid/scoped_nodes.py#L1558) and tries to infer the result from there. But since functions like this don't have an explicit return value, the inference gets into `raise_if_nothing_inferred` over here (https://github.com/PyCQA/astroid/blob/ac3e82e9bd8678086325a71a927a06bbc43d415e/astroid/decorators.py#L140), resulting in the exception you see.
What should we infer for a function that always raises an exception? I don't think it should be `None`. Uninferable I guess?
---
I tried to add this, but It caused a cascade of errors where we are looking for Uninferable instead of const.None
@brycepg I would say it should return `Uninferable`, as raising exceptions is not necessarily returning a value from the function. Although we'd want some mechanism to get what exceptions a function could raise.
Regarding your last statement, you mean you added `Uninferable` for functions that raise exceptions or for functions that return `None`? Which of these failed with the cascade of errors?
@PCManticore I made functions that do not have any return/yield nodes infer to `None` instead of `Uninferable`, and it broke a lot of tests.
| 53a20335357bbd734d74c3bfe22e3518f74f4d11 | [
"https://github.com/pylint-dev/astroid/commit/4a53ef4b151ace595608b5b5e6008b7b17914a80",
"https://github.com/pylint-dev/astroid/commit/38297611b6ebf32cd7722cce3074ce8fccccb490",
"https://github.com/pylint-dev/astroid/commit/826d0e95fd6800fff5f32f66e911b0a30dbfa982",
"https://github.com/pylint-dev/astroid/comm... | 2021-05-01T03:28:27 | Makes sense.
This happens because the inference for functions looks through each return value here (https://github.com/PyCQA/astroid/blob/629c92db2dc1b016f4bf47645c95c42e65fd3bd6/astroid/scoped_nodes.py#L1558) and tries to infer the result from there. But since functions like this don't have an explicit return value, the inference gets into `raise_if_nothing_inferred` over here (https://github.com/PyCQA/astroid/blob/ac3e82e9bd8678086325a71a927a06bbc43d415e/astroid/decorators.py#L140), resulting in the exception you see.
What should we infer for a function that always raises an exception? I don't think it should be `None`. Uninferable I guess?
---
I tried to add this, but It caused a cascade of errors where we are looking for Uninferable instead of const.None
@brycepg I would say it should return `Uninferable`, as raising exceptions is not necessarily returning a value from the function. Although we'd want some mechanism to get what exceptions a function could raise.
Regarding your last statement, you mean you added `Uninferable` for functions that raise exceptions or for functions that return `None`? Which of these failed with the cascade of errors?
@PCManticore I made functions that do not have any return/yield nodes infer to `None` instead of `Uninferable`, and it broke a lot of tests.
| pylint-dev__astroid-983 | [
"485"
] | python | diff --git a/ChangeLog b/ChangeLog
index c606b76106..8ba9ea37bb 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -45,6 +45,11 @@ Release Date: TBA
Closes #904
+* Allow inferring a return value of None for non-abstract empty functions and
+ functions with no return statements (implicitly returning None)
+
+ Closes #485
+
What's New in astroid 2.5.6?
============================
diff --git a/astroid/bases.py b/astroid/bases.py
index 02da1a8876..97b10366bf 100644
--- a/astroid/bases.py
+++ b/astroid/bases.py
@@ -329,6 +329,12 @@ def getitem(self, index, context=None):
raise exceptions.InferenceError(
"Could not find __getitem__ for {node!r}.", node=self, context=context
)
+ if len(method.args.arguments) != 2: # (self, index)
+ raise exceptions.AstroidTypeError(
+ "__getitem__ for {node!r} does not have correct signature",
+ node=self,
+ context=context,
+ )
return next(method.infer_call_result(self, new_context))
diff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py
index 27237e8296..cfc64392a0 100644
--- a/astroid/scoped_nodes.py
+++ b/astroid/scoped_nodes.py
@@ -1661,11 +1661,12 @@ def is_bound(self):
"""
return self.type == "classmethod"
- def is_abstract(self, pass_is_abstract=True):
+ def is_abstract(self, pass_is_abstract=True, any_raise_is_abstract=False):
"""Check if the method is abstract.
A method is considered abstract if any of the following is true:
* The only statement is 'raise NotImplementedError'
+ * The only statement is 'raise <SomeException>' and any_raise_is_abstract is True
* The only statement is 'pass' and pass_is_abstract is True
* The method is annotated with abc.astractproperty/abc.abstractmethod
@@ -1686,6 +1687,8 @@ def is_abstract(self, pass_is_abstract=True):
for child_node in self.body:
if isinstance(child_node, node_classes.Raise):
+ if any_raise_is_abstract:
+ return True
if child_node.raises_not_implemented():
return True
return pass_is_abstract and isinstance(child_node, node_classes.Pass)
@@ -1744,8 +1747,11 @@ def infer_call_result(self, caller=None, context=None):
first_return = next(returns, None)
if not first_return:
- if self.body and isinstance(self.body[-1], node_classes.Assert):
- yield node_classes.Const(None)
+ if self.body:
+ if self.is_abstract(pass_is_abstract=True, any_raise_is_abstract=True):
+ yield util.Uninferable
+ else:
+ yield node_classes.Const(None)
return
raise exceptions.InferenceError(
| Cannot infer empty functions
### Steps to reproduce
```python
import astroid
astroid.extract_node("""
def f():
pass
f()
""").inferred()
```
### Current behavior
raises `StopIteration`
### Expected behavior
Returns `[const.NoneType]`
### ``python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"`` output
2.0.0
This also applies to procedural functions which don't explicitly return any values.
| 983 | pylint-dev/astroid | diff --git a/tests/unittest_inference.py b/tests/unittest_inference.py
index 6b9f4c0609..2e88891637 100644
--- a/tests/unittest_inference.py
+++ b/tests/unittest_inference.py
@@ -706,14 +706,6 @@ class InvalidGetitem2(object):
NoGetitem()[4] #@
InvalidGetitem()[5] #@
InvalidGetitem2()[10] #@
- """
- )
- for node in ast_nodes[:3]:
- self.assertRaises(InferenceError, next, node.infer())
- for node in ast_nodes[3:]:
- self.assertEqual(next(node.infer()), util.Uninferable)
- ast_nodes = extract_node(
- """
[1, 2, 3][None] #@
'lala'['bala'] #@
"""
@@ -5404,26 +5396,25 @@ class Cls:
def test_prevent_recursion_error_in_igetattr_and_context_manager_inference():
code = """
class DummyContext(object):
- def method(self, msg): # pylint: disable=C0103
- pass
def __enter__(self):
- pass
+ return self
def __exit__(self, ex_type, ex_value, ex_tb):
return True
- class CallMeMaybe(object):
- def __call__(self):
- while False:
- with DummyContext() as con:
- f_method = con.method
- break
+ if False:
+ with DummyContext() as con:
+ pass
- with DummyContext() as con:
- con #@
- f_method = con.method
+ with DummyContext() as con:
+ con.__enter__ #@
"""
node = extract_node(code)
- assert next(node.infer()) is util.Uninferable
+ # According to the original issue raised that introduced this test
+ # (https://github.com/PyCQA/astroid/663, see 55076ca), this test was a
+ # non-regression check for StopIteration leaking out of inference and
+ # causing a RuntimeError. Hence, here just consume the inferred value
+ # without checking it and rely on pytest to fail on raise
+ next(node.infer())
def test_infer_context_manager_with_unknown_args():
diff --git a/tests/unittest_scoped_nodes.py b/tests/unittest_scoped_nodes.py
index fc766941b8..a298803c91 100644
--- a/tests/unittest_scoped_nodes.py
+++ b/tests/unittest_scoped_nodes.py
@@ -466,6 +466,55 @@ def func():
self.assertIsInstance(func_vals[0], nodes.Const)
self.assertIsNone(func_vals[0].value)
+ def test_no_returns_is_implicitly_none(self):
+ code = """
+ def f():
+ print('non-empty, non-pass, no return statements')
+ value = f()
+ value
+ """
+ node = builder.extract_node(code)
+ inferred = next(node.infer())
+ assert isinstance(inferred, nodes.Const)
+ assert inferred.value is None
+
+ def test_only_raises_is_not_implicitly_none(self):
+ code = """
+ def f():
+ raise SystemExit()
+ f()
+ """
+ node = builder.extract_node(code) # type: nodes.Call
+ inferred = next(node.infer())
+ assert inferred is util.Uninferable
+
+ def test_abstract_methods_are_not_implicitly_none(self):
+ code = """
+ from abc import ABCMeta, abstractmethod
+
+ class Abstract(metaclass=ABCMeta):
+ @abstractmethod
+ def foo(self):
+ pass
+ def bar(self):
+ print('non-empty, non-pass, no return statements')
+ Abstract().foo() #@
+ Abstract().bar() #@
+
+ class Concrete(Abstract):
+ def foo(self):
+ return 123
+ Concrete().foo() #@
+ Concrete().bar() #@
+ """
+ afoo, abar, cfoo, cbar = builder.extract_node(code)
+
+ assert next(afoo.infer()) is util.Uninferable
+ for node, value in [(abar, None), (cfoo, 123), (cbar, None)]:
+ inferred = next(node.infer())
+ assert isinstance(inferred, nodes.Const)
+ assert inferred.value == value
+
def test_func_instance_attr(self):
"""test instance attributes for functions"""
data = """
| none | [
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_abstract_methods_are_not_implicitly_none",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_no_returns_is_implicitly_none",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_only_raises_is_not_implicitly_none"
] | [
"tests/unittest_inference.py::InferenceUtilsTest::test_path_wrapper",
"tests/unittest_inference.py::InferenceTest::test__new__",
"tests/unittest_inference.py::InferenceTest::test__new__bound_methods",
"tests/unittest_inference.py::InferenceTest::test_advanced_tupleassign_name_inference1",
"tests/unittest_in... | [
"pytest -rA tests/"
] | pytest | {
"files": 3,
"hunks": 5,
"lines": 23
} |
Some notes:
- The `ModuleNotFoundError` exception is thrown by `importlib.util.find_spec`. Before python 3.7 this was an `AttributeError`
- `modutils.is_relative()` is the call-site for the `find_spec` call
- It seems that `is_ralative()` is trying to find a parent mod-spec for the anchor `from_file` parameter so that it can check to see if the `modname` is contained by it
- Neither `is_relative` nor its tests, explicitly handle on-disk paths (that is, paths for which `os.path.exists()` returns `True`) vs virtual-paths (`exists() == False`). The seems to be important to `find_spec` which raises if the package's `__path__` attribute isn't found (which it won't be for virtual paths).
- The existing unit tests for `is_realtive()` use a range of modules to check against a set of module paths via `__path__[0]`. Somehow these pass and it is not clear why/how
One workaround fix, that feels like a hack until I understand the problem better, is for `is_relative()` to handle the `ModuleNotFoundError`/`AttributeError` exceptions and them as signifying that the `parent_spec` is being not-yet found. However, that requires that the loop-logic is fixed for linux-like systems, otherwise you end up in an infinite loop with `len(file_path)>0` always being true for `/` and `file_path = os.path.dirname('/')` always returning `/`.
I have written some new unit tests for this issue and extended the existing ones, but there is some fundamental logic underpinning the use of `importlib.util.find_spec` that I am not smart enough to understand. For example, why do the existing unit-tests not all use the same `modname` parameter? Is it to work around the import caching in `sys.modules`? Should we take that into account?
My unit tests look at both virtual and ondisk paths (because of the `if not os.path.isdir(from_file):` line in `is_realtive()`, and the docs for `find_spec`). They also look at both absolute and relative paths explicitly. Finally, they also use system modules and assert that they are already in the import cache.
.. and I thought this fix was going to be easy.
@doublethefish thanks for your report and investigation.
I can reproduce it and i confirm that #857 is the origin of the issue.
It seems like this happens if an import inside a package which is at least two levels deep is processed.
For example, trying to run ``pyreverse`` on ``pylint`` itself will crash as soon as the import statements in checker modules in ``pylint.checkers.refactoring`` are processed.
``importlib.util.find_spec(name, from_file)`` is called with ``name`` = ``checkers.refactoring``.
``find_spec`` will then split this up and try to import ``checkers``, which fails because the path to _inside_ the ``pylint`` package (i.e. ``pylint/pylint`` from the repo root) is normally not in the Pythonpath.
| d2394a3e24236106355418e102b1bb0f1bef879c | [
"https://github.com/pylint-dev/astroid/commit/86edd7d157592d84853dece3122507cb303b326d",
"https://github.com/pylint-dev/astroid/commit/6b4b4a1f7349062782999342b8ca43f95fe37f59",
"https://github.com/pylint-dev/astroid/commit/d2a72366b4cd6699a8a5828dbc75f6694b07e058",
"https://github.com/pylint-dev/astroid/comm... | 2021-05-01T16:13:04 | Some notes:
- The `ModuleNotFoundError` exception is thrown by `importlib.util.find_spec`. Before python 3.7 this was an `AttributeError`
- `modutils.is_relative()` is the call-site for the `find_spec` call
- It seems that `is_ralative()` is trying to find a parent mod-spec for the anchor `from_file` parameter so that it can check to see if the `modname` is contained by it
- Neither `is_relative` nor its tests, explicitly handle on-disk paths (that is, paths for which `os.path.exists()` returns `True`) vs virtual-paths (`exists() == False`). The seems to be important to `find_spec` which raises if the package's `__path__` attribute isn't found (which it won't be for virtual paths).
- The existing unit tests for `is_realtive()` use a range of modules to check against a set of module paths via `__path__[0]`. Somehow these pass and it is not clear why/how
One workaround fix, that feels like a hack until I understand the problem better, is for `is_relative()` to handle the `ModuleNotFoundError`/`AttributeError` exceptions and them as signifying that the `parent_spec` is being not-yet found. However, that requires that the loop-logic is fixed for linux-like systems, otherwise you end up in an infinite loop with `len(file_path)>0` always being true for `/` and `file_path = os.path.dirname('/')` always returning `/`.
I have written some new unit tests for this issue and extended the existing ones, but there is some fundamental logic underpinning the use of `importlib.util.find_spec` that I am not smart enough to understand. For example, why do the existing unit-tests not all use the same `modname` parameter? Is it to work around the import caching in `sys.modules`? Should we take that into account?
My unit tests look at both virtual and ondisk paths (because of the `if not os.path.isdir(from_file):` line in `is_realtive()`, and the docs for `find_spec`). They also look at both absolute and relative paths explicitly. Finally, they also use system modules and assert that they are already in the import cache.
.. and I thought this fix was going to be easy.
@doublethefish thanks for your report and investigation.
I can reproduce it and i confirm that #857 is the origin of the issue.
It seems like this happens if an import inside a package which is at least two levels deep is processed.
For example, trying to run ``pyreverse`` on ``pylint`` itself will crash as soon as the import statements in checker modules in ``pylint.checkers.refactoring`` are processed.
``importlib.util.find_spec(name, from_file)`` is called with ``name`` = ``checkers.refactoring``.
``find_spec`` will then split this up and try to import ``checkers``, which fails because the path to _inside_ the ``pylint`` package (i.e. ``pylint/pylint`` from the repo root) is normally not in the Pythonpath.
| pylint-dev__astroid-984 | [
"930"
] | python | diff --git a/ChangeLog b/ChangeLog
index 8ba9ea37bb..3252b48719 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -6,6 +6,10 @@ What's New in astroid 2.6.0?
============================
Release Date: TBA
+* Fix detection of relative imports.
+ Closes #930
+ Closes PyCQA/pylint#4186
+
* Fix inference of instance attributes defined in base classes
Closes #932
diff --git a/astroid/interpreter/_import/spec.py b/astroid/interpreter/_import/spec.py
index 7800af8765..0a3db54964 100644
--- a/astroid/interpreter/_import/spec.py
+++ b/astroid/interpreter/_import/spec.py
@@ -292,15 +292,13 @@ def _precache_zipimporters(path=None):
new_paths = _cached_set_diff(req_paths, cached_paths)
for entry_path in new_paths:
try:
- pic[entry_path] = zipimport.zipimporter( # pylint: disable=no-member
- entry_path
- )
- except zipimport.ZipImportError: # pylint: disable=no-member
+ pic[entry_path] = zipimport.zipimporter(entry_path)
+ except zipimport.ZipImportError:
continue
return {
key: value
for key, value in pic.items()
- if isinstance(value, zipimport.zipimporter) # pylint: disable=no-member
+ if isinstance(value, zipimport.zipimporter)
}
diff --git a/astroid/manager.py b/astroid/manager.py
index 06ab8d3263..6525d1badd 100644
--- a/astroid/manager.py
+++ b/astroid/manager.py
@@ -213,9 +213,7 @@ def zip_import_data(self, filepath):
except ValueError:
continue
try:
- importer = zipimport.zipimporter( # pylint: disable=no-member
- eggpath + ext
- )
+ importer = zipimport.zipimporter(eggpath + ext)
zmodname = resource.replace(os.path.sep, ".")
if importer.is_package(resource):
zmodname = zmodname + ".__init__"
diff --git a/astroid/modutils.py b/astroid/modutils.py
index 4a4798ada2..a71f2745e7 100644
--- a/astroid/modutils.py
+++ b/astroid/modutils.py
@@ -18,6 +18,7 @@
# Copyright (c) 2020 hippo91 <guillaume.peillex@gmail.com>
# Copyright (c) 2020 Peter Kolbus <peter.kolbus@gmail.com>
# Copyright (c) 2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
+# Copyright (c) 2021 Andreas Finkler <andi.finkler@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/LICENSE
@@ -37,6 +38,8 @@
# We disable the import-error so pylint can work without distutils installed.
# pylint: disable=no-name-in-module,useless-suppression
+import importlib
+import importlib.machinery
import importlib.util
import itertools
import os
@@ -574,21 +577,11 @@ def is_relative(modname, from_file):
from_file = os.path.dirname(from_file)
if from_file in sys.path:
return False
- name = os.path.basename(from_file)
- file_path = os.path.dirname(from_file)
- parent_spec = importlib.util.find_spec(name, from_file)
- while parent_spec is None and len(file_path) > 0:
- name = os.path.basename(file_path) + "." + name
- file_path = os.path.dirname(file_path)
- parent_spec = importlib.util.find_spec(name, from_file)
-
- if parent_spec is None:
- return False
-
- submodule_spec = importlib.util.find_spec(
- name + "." + modname.split(".")[0], parent_spec.submodule_search_locations
+ return bool(
+ importlib.machinery.PathFinder.find_spec(
+ modname.split(".", maxsplit=1)[0], [from_file]
+ )
)
- return submodule_spec is not None
# internal only functions #####################################################
| Pyreverse regression after #857 (astroid 2.5)
### Steps to reproduce
1. Checkout pylint's source (which contains pyreverse)
1. cd `<pylint checkout>`
2. Run `source .tox/py39/bin/activate` or similar (you may need to run a tox session first)
3. Ensure you have `astroid` ac2b173bc8acd2d08f6b6ffe29dd8cda0b2c8814 or later
4. Ensure you have installed `astroid` (`python3 -m pip install -e <path-to-astroid>`) as dependencies may be different
4. Run `pyreverse --output png --project test tests/data`
### Current behaviour
A `ModuleNotFoundError` exception is raised.
```
$ pyreverse --output png --project test tests/data
parsing tests/data/__init__.py...
parsing /opt/contrib/pylint/pylint/tests/data/suppliermodule_test.py...
parsing /opt/contrib/pylint/pylint/tests/data/__init__.py...
parsing /opt/contrib/pylint/pylint/tests/data/clientmodule_test.py...
Traceback (most recent call last):
File "/opt/contrib/pylint/pylint/.tox/py39/bin/pyreverse", line 8, in <module>
sys.exit(run_pyreverse())
File "/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/__init__.py", line 39, in run_pyreverse
PyreverseRun(sys.argv[1:])
File "/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/main.py", line 201, in __init__
sys.exit(self.run(args))
File "/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/main.py", line 219, in run
diadefs = handler.get_diadefs(project, linker)
File "/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/diadefslib.py", line 236, in get_diadefs
diagrams = DefaultDiadefGenerator(linker, self).visit(project)
File "/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/utils.py", line 210, in visit
self.visit(local_node)
File "/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/utils.py", line 207, in visit
methods[0](node)
File "/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/diadefslib.py", line 162, in visit_module
self.linker.visit(node)
File "/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/utils.py", line 210, in visit
self.visit(local_node)
File "/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/utils.py", line 207, in visit
methods[0](node)
File "/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/inspector.py", line 257, in visit_importfrom
relative = astroid.modutils.is_relative(basename, context_file)
File "/opt/contrib/pylint/astroid/astroid/modutils.py", line 581, in is_relative
parent_spec = importlib.util.find_spec(name, from_file)
File "/usr/local/Cellar/python@3.9/3.9.2_4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/util.py", line 94, in find_spec
parent = __import__(parent_name, fromlist=['__path__'])
ModuleNotFoundError: No module named 'pylint.tests'
```
### Expected behaviour
No exception should be raised. Prior to #857 no exception was raised.
```
$ pyreverse --output png --project test tests/data
parsing tests/data/__init__.py...
parsing /opt/contributing/pylint/tests/data/suppliermodule_test.py...
parsing /opt/contributing/pylint/tests/data/__init__.py...
parsing /opt/contributing/pylint/tests/data/clientmodule_test.py...
```
### ``python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"`` output
`2.6.0-dev0` (cab9b08737ed7aad2a08ce90718c67155fa5c4a0)
| 984 | pylint-dev/astroid | diff --git a/tests/unittest_modutils.py b/tests/unittest_modutils.py
index 958659f542..248a88cdb9 100644
--- a/tests/unittest_modutils.py
+++ b/tests/unittest_modutils.py
@@ -301,6 +301,18 @@ def test_knownValues_is_relative_1(self):
def test_knownValues_is_relative_3(self):
self.assertFalse(modutils.is_relative("astroid", astroid.__path__[0]))
+ def test_knownValues_is_relative_4(self):
+ self.assertTrue(
+ modutils.is_relative("util", astroid.interpreter._import.spec.__file__)
+ )
+
+ def test_knownValues_is_relative_5(self):
+ self.assertFalse(
+ modutils.is_relative(
+ "objectmodel", astroid.interpreter._import.spec.__file__
+ )
+ )
+
def test_deep_relative(self):
self.assertTrue(modutils.is_relative("ElementTree", xml.etree.__path__[0]))
| none | [
"tests/unittest_modutils.py::IsRelativeTest::test_knownValues_is_relative_4",
"tests/unittest_modutils.py::IsRelativeTest::test_knownValues_is_relative_5"
] | [
"tests/unittest_modutils.py::ModuleFileTest::test_find_egg_module",
"tests/unittest_modutils.py::ModuleFileTest::test_find_zipped_module",
"tests/unittest_modutils.py::LoadModuleFromNameTest::test_knownValues_load_module_from_name_1",
"tests/unittest_modutils.py::LoadModuleFromNameTest::test_knownValues_load_... | [
"pytest -rA"
] | pytest | {
"files": 4,
"hunks": 6,
"lines": 37
} |
Minimal case:
```python
class Example:
def func(self):
pass
whatthe = object()
whatthe.func = None
ex = Example()
ex.func() # false-positive: not-callable
```
Not caused by 78d5537, just revealed by it. `typing` imported `collections`, `collections.OrderedDict` had an ambiguously inferred case that was previously broken by failure with positional-only arguments which was fixed in 78d5537.
| 2c109eec6fe3f972c6e8c637fe956431a0d7685c | [
"https://github.com/pylint-dev/astroid/commit/957c832d049708d5e3a8e47c13231afe38914b39",
"https://github.com/pylint-dev/astroid/commit/09558a0743c6130b472f6b4ea1c2a44fdb5a3e77",
"https://github.com/pylint-dev/astroid/commit/5b9916b67c4d75b3ed4d33c1eb93f4197da0d16c",
"https://github.com/pylint-dev/astroid/comm... | 2021-04-13T12:30:06 | Minimal case:
```python
class Example:
def func(self):
pass
whatthe = object()
whatthe.func = None
ex = Example()
ex.func() # false-positive: not-callable
```
Not caused by 78d5537, just revealed by it. `typing` imported `collections`, `collections.OrderedDict` had an ambiguously inferred case that was previously broken by failure with positional-only arguments which was fixed in 78d5537.
| pylint-dev__astroid-946 | [
"945"
] | python | diff --git a/ChangeLog b/ChangeLog
index b4af947daa..12fae5ceab 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -6,6 +6,15 @@ What's New in astroid 2.6.0?
============================
Release Date: TBA
+* Do not set instance attributes on builtin object()
+
+ Closes #945
+ Closes PyCQA/pylint#4232
+ Closes PyCQA/pylint#4221
+ Closes PyCQA/pylint#3970
+ Closes PyCQA/pylint#3595
+
+
What's New in astroid 2.5.6?
============================
Release Date: 2021-04-25
diff --git a/astroid/builder.py b/astroid/builder.py
index 6a7f79ced0..4a066ee836 100644
--- a/astroid/builder.py
+++ b/astroid/builder.py
@@ -67,7 +67,7 @@ def _can_assign_attr(node, attrname):
else:
if slots and attrname not in {slot.value for slot in slots}:
return False
- return True
+ return node.qname() != "builtins.object"
class AstroidBuilder(raw_building.InspectBuilder):
| Delayed attribute assignment to object() may cause incorrect inference of instance attributes
@cdce8p: `aiohttp` and `VLCTelnet` turned out to be red herrings. This case fails on current stable versions:
```python
class Example:
def prev(self):
pass
def next(self):
pass
def other(self):
pass
ex = Example()
ex.other() # no warning
ex.prev() # no warning
ex.next() # no warning
import typing
ex.other() # no warning
ex.prev() # false-positive: not-callable
ex.next() # false-positive: not-callable
```
_Originally posted by @nelfin in https://github.com/PyCQA/astroid/issues/927#issuecomment-818626368_
I've bisected this down to 78d5537. Pylint 2.3.1 passes this case with 20a7ae5 and fails with 78d5537
| 946 | pylint-dev/astroid | diff --git a/tests/unittest_builder.py b/tests/unittest_builder.py
index a48d341999..ce9abf9af0 100644
--- a/tests/unittest_builder.py
+++ b/tests/unittest_builder.py
@@ -28,7 +28,7 @@
import pytest
-from astroid import builder, exceptions, manager, nodes, test_utils, util
+from astroid import Instance, builder, exceptions, manager, nodes, test_utils, util
from . import resources
@@ -476,6 +476,53 @@ def A_assign_type(self):
self.assertIn("assign_type", lclass.locals)
self.assertIn("type", lclass.locals)
+ def test_infer_can_assign_regular_object(self):
+ mod = builder.parse(
+ """
+ class A:
+ pass
+ a = A()
+ a.value = "is set"
+ a.other = "is set"
+ """
+ )
+ obj = list(mod.igetattr("a"))
+ self.assertEqual(len(obj), 1)
+ obj = obj[0]
+ self.assertIsInstance(obj, Instance)
+ self.assertIn("value", obj.instance_attrs)
+ self.assertIn("other", obj.instance_attrs)
+
+ def test_infer_can_assign_has_slots(self):
+ mod = builder.parse(
+ """
+ class A:
+ __slots__ = ('value',)
+ a = A()
+ a.value = "is set"
+ a.other = "not set"
+ """
+ )
+ obj = list(mod.igetattr("a"))
+ self.assertEqual(len(obj), 1)
+ obj = obj[0]
+ self.assertIsInstance(obj, Instance)
+ self.assertIn("value", obj.instance_attrs)
+ self.assertNotIn("other", obj.instance_attrs)
+
+ def test_infer_can_assign_no_classdict(self):
+ mod = builder.parse(
+ """
+ a = object()
+ a.value = "not set"
+ """
+ )
+ obj = list(mod.igetattr("a"))
+ self.assertEqual(len(obj), 1)
+ obj = obj[0]
+ self.assertIsInstance(obj, Instance)
+ self.assertNotIn("value", obj.instance_attrs)
+
def test_augassign_attr(self):
builder.parse(
"""
diff --git a/tests/unittest_scoped_nodes.py b/tests/unittest_scoped_nodes.py
index dd6102c6ff..9303f1c7eb 100644
--- a/tests/unittest_scoped_nodes.py
+++ b/tests/unittest_scoped_nodes.py
@@ -1430,7 +1430,9 @@ class A:
pass
class B:
pass
- scope = object()
+ class Scope:
+ pass
+ scope = Scope()
scope.A = A
scope.B = B
class C(scope.A, scope.B):
| none | [
"tests/unittest_builder.py::BuilderTest::test_infer_can_assign_no_classdict"
] | [
"tests/unittest_builder.py::FromToLineNoTest::test_callfunc_lineno",
"tests/unittest_builder.py::FromToLineNoTest::test_class_lineno",
"tests/unittest_builder.py::FromToLineNoTest::test_decorated_function_lineno",
"tests/unittest_builder.py::FromToLineNoTest::test_for_while_lineno",
"tests/unittest_builder.... | [
"pytest -rA tests"
] | pytest | {
"files": 2,
"hunks": 2,
"lines": 11
} |
Looks like this is caused by https://github.com/PyCQA/astroid/blob/f2b197a4f8af0ceeddf435747a5c937c8632872a/astroid/scoped_nodes.py#L2590-L2603. When we are inferring an attribute on a derived class then `class_context` is `True` but `metaclass` is `False` so the property itself is returned.
| 962becc0ae86c16f7b33140f43cd6ed8f1e8a045 | [
"https://github.com/pylint-dev/astroid/commit/dbc9c0c0a01744bf9b654e750b2dbd03d80f3ed5",
"https://github.com/pylint-dev/astroid/commit/857f15448fbfbecd488f8bdfdeb315b2950b37d0",
"https://github.com/pylint-dev/astroid/commit/8030d6ab76a8696294d5d8f297ad7193b953e9d5",
"https://github.com/pylint-dev/astroid/comm... | 2021-04-11T11:57:22 | Looks like this is caused by https://github.com/PyCQA/astroid/blob/f2b197a4f8af0ceeddf435747a5c937c8632872a/astroid/scoped_nodes.py#L2590-L2603. When we are inferring an attribute on a derived class then `class_context` is `True` but `metaclass` is `False` so the property itself is returned.
| pylint-dev__astroid-941 | [
"940"
] | python | diff --git a/ChangeLog b/ChangeLog
index 4343be3fee..9d7b945fde 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -28,6 +28,15 @@ Release Date: TBA
Closes #898
+* Fix property inference in class contexts for properties defined on the metaclass
+
+ Closes #940
+
+* Update enum brain to fix definition of __members__ for subclass-defined Enums
+
+ Closes PyCQA/pylint#3535
+ Closes PyCQA/pylint#4358
+
What's New in astroid 2.5.6?
============================
diff --git a/astroid/brain/brain_namedtuple_enum.py b/astroid/brain/brain_namedtuple_enum.py
index 1af5ba2bb4..9a9cc98981 100644
--- a/astroid/brain/brain_namedtuple_enum.py
+++ b/astroid/brain/brain_namedtuple_enum.py
@@ -315,6 +315,7 @@ def infer_enum_class(node):
if node.root().name == "enum":
# Skip if the class is directly from enum module.
break
+ dunder_members = {}
for local, values in node.locals.items():
if any(not isinstance(value, nodes.AssignName) for value in values):
continue
@@ -372,7 +373,16 @@ def name(self):
for method in node.mymethods():
fake.locals[method.name] = [method]
new_targets.append(fake.instantiate_class())
+ dunder_members[local] = fake
node.locals[local] = new_targets
+ members = nodes.Dict(parent=node)
+ members.postinit(
+ [
+ (nodes.Const(k, parent=members), nodes.Name(v.name, parent=members))
+ for k, v in dunder_members.items()
+ ]
+ )
+ node.locals["__members__"] = [members]
break
return node
diff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py
index 333f42fe55..27237e8296 100644
--- a/astroid/scoped_nodes.py
+++ b/astroid/scoped_nodes.py
@@ -2554,7 +2554,7 @@ def igetattr(self, name, context=None, class_context=True):
context = contextmod.copy_context(context)
context.lookupname = name
- metaclass = self.declared_metaclass(context=context)
+ metaclass = self.metaclass(context=context)
try:
attributes = self.getattr(name, context, class_context=class_context)
# If we have more than one attribute, make sure that those starting from
@@ -2587,9 +2587,12 @@ def igetattr(self, name, context=None, class_context=True):
yield from function.infer_call_result(
caller=self, context=context
)
- # If we have a metaclass, we're accessing this attribute through
- # the class itself, which means we can solve the property
- elif metaclass:
+ # If we're in a class context, we need to determine if the property
+ # was defined in the metaclass (a derived class must be a subclass of
+ # the metaclass of all its bases), in which case we can resolve the
+ # property. If not, i.e. the property is defined in some base class
+ # instead, then we return the property object
+ elif metaclass and function.parent.scope() is metaclass:
# Resolve a property as long as it is not accessed through
# the class itself.
yield from function.infer_call_result(
| @property members defined in metaclasses of a base class are not correctly inferred
Ref https://github.com/PyCQA/astroid/issues/927#issuecomment-817244963
Inference works on the parent class but not the child in the following example:
```python
class BaseMeta(type):
@property
def __members__(cls):
return ['a', 'property']
class Parent(metaclass=BaseMeta):
pass
class Derived(Parent):
pass
Parent.__members__ # [<Set.set l.10 at 0x...>]
Derived.__members__ # [<Property.__members__ l.8 at 0x...>]
```
| 941 | pylint-dev/astroid | diff --git a/tests/unittest_scoped_nodes.py b/tests/unittest_scoped_nodes.py
index 9303f1c7eb..7fe537b2fb 100644
--- a/tests/unittest_scoped_nodes.py
+++ b/tests/unittest_scoped_nodes.py
@@ -1923,6 +1923,153 @@ def update(self):
builder.parse(data)
+def test_issue940_metaclass_subclass_property():
+ node = builder.extract_node(
+ """
+ class BaseMeta(type):
+ @property
+ def __members__(cls):
+ return ['a', 'property']
+ class Parent(metaclass=BaseMeta):
+ pass
+ class Derived(Parent):
+ pass
+ Derived.__members__
+ """
+ )
+ inferred = next(node.infer())
+ assert isinstance(inferred, nodes.List)
+ assert [c.value for c in inferred.elts] == ["a", "property"]
+
+
+def test_issue940_property_grandchild():
+ node = builder.extract_node(
+ """
+ class Grandparent:
+ @property
+ def __members__(self):
+ return ['a', 'property']
+ class Parent(Grandparent):
+ pass
+ class Child(Parent):
+ pass
+ Child().__members__
+ """
+ )
+ inferred = next(node.infer())
+ assert isinstance(inferred, nodes.List)
+ assert [c.value for c in inferred.elts] == ["a", "property"]
+
+
+def test_issue940_metaclass_property():
+ node = builder.extract_node(
+ """
+ class BaseMeta(type):
+ @property
+ def __members__(cls):
+ return ['a', 'property']
+ class Parent(metaclass=BaseMeta):
+ pass
+ Parent.__members__
+ """
+ )
+ inferred = next(node.infer())
+ assert isinstance(inferred, nodes.List)
+ assert [c.value for c in inferred.elts] == ["a", "property"]
+
+
+def test_issue940_with_metaclass_class_context_property():
+ node = builder.extract_node(
+ """
+ class BaseMeta(type):
+ pass
+ class Parent(metaclass=BaseMeta):
+ @property
+ def __members__(self):
+ return ['a', 'property']
+ class Derived(Parent):
+ pass
+ Derived.__members__
+ """
+ )
+ inferred = next(node.infer())
+ assert not isinstance(inferred, nodes.List)
+ assert isinstance(inferred, objects.Property)
+
+
+def test_issue940_metaclass_values_funcdef():
+ node = builder.extract_node(
+ """
+ class BaseMeta(type):
+ def __members__(cls):
+ return ['a', 'func']
+ class Parent(metaclass=BaseMeta):
+ pass
+ Parent.__members__()
+ """
+ )
+ inferred = next(node.infer())
+ assert isinstance(inferred, nodes.List)
+ assert [c.value for c in inferred.elts] == ["a", "func"]
+
+
+def test_issue940_metaclass_derived_funcdef():
+ node = builder.extract_node(
+ """
+ class BaseMeta(type):
+ def __members__(cls):
+ return ['a', 'func']
+ class Parent(metaclass=BaseMeta):
+ pass
+ class Derived(Parent):
+ pass
+ Derived.__members__()
+ """
+ )
+ inferred_result = next(node.infer())
+ assert isinstance(inferred_result, nodes.List)
+ assert [c.value for c in inferred_result.elts] == ["a", "func"]
+
+
+def test_issue940_metaclass_funcdef_is_not_datadescriptor():
+ node = builder.extract_node(
+ """
+ class BaseMeta(type):
+ def __members__(cls):
+ return ['a', 'property']
+ class Parent(metaclass=BaseMeta):
+ @property
+ def __members__(cls):
+ return BaseMeta.__members__()
+ class Derived(Parent):
+ pass
+ Derived.__members__
+ """
+ )
+ # Here the function is defined on the metaclass, but the property
+ # is defined on the base class. When loading the attribute in a
+ # class context, this should return the property object instead of
+ # resolving the data descriptor
+ inferred = next(node.infer())
+ assert isinstance(inferred, objects.Property)
+
+
+def test_issue940_enums_as_a_real_world_usecase():
+ node = builder.extract_node(
+ """
+ from enum import Enum
+ class Sounds(Enum):
+ bee = "buzz"
+ cat = "meow"
+ Sounds.__members__
+ """
+ )
+ inferred_result = next(node.infer())
+ assert isinstance(inferred_result, nodes.Dict)
+ actual = [k.value for k, _ in inferred_result.items]
+ assert sorted(actual) == ["bee", "cat"]
+
+
def test_metaclass_cannot_infer_call_yields_an_instance():
node = builder.extract_node(
"""
| none | [
"tests/unittest_scoped_nodes.py::test_issue940_metaclass_subclass_property",
"tests/unittest_scoped_nodes.py::test_issue940_enums_as_a_real_world_usecase"
] | [
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_dict_interface",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_api",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_in_memory",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_physical",
"tests/uni... | [
"pytest -rA tests/"
] | pytest | {
"files": 3,
"hunks": 5,
"lines": 30
} |
The first issue is caused by the fact that the `str` relies on `postinit` being called I think.
I ran into this while debugging `astroid` many times..
I made a quick unit test on #2198. Am I going in the right direction? Also, I guess fixing the errors themselves will be part of this issue right?
I'd prefer using `pytest` semantics instead of `unittests` but that's more a review comment.
I think the bigger issue is that the reliance on `__postinit__` makes this very hard to solve. We would need to revisit either 1) what we put in the `__str__` or 2) how we instantiate nodes. Both are not optimal I think.
I labeled this as a good first issue because I was hoping it wasn't requiring knowledge of any of that, just placing a good blank placeholder in the str/repr when the info is not available.
That would require a fix here:
https://github.com/pylint-dev/astroid/blob/a6eb2b87c5bfa39929b8047010788afce48461bf/astroid/nodes/node_ng.py#L213
I guess that would work? We don't really need a regression test for it though (I think).
LGTM. There are bunch of overridden `__str__` methods that might have similar problems, so I was thinking the unit tests would be nice. But if we find no other problems in the other methods, then such a test could be overly paranoid. EDIT: but writing the test would be the fastest way to find out!
| 61ca2e832dd1f99ed7de5c7c403031292993d6fd | [
"https://github.com/pylint-dev/astroid/commit/f5028e230d4d0320e31af5f7014f08ba0b0666aa"
] | 2023-06-06T20:17:57 | The first issue is caused by the fact that the `str` relies on `postinit` being called I think.
I ran into this while debugging `astroid` many times..
| pylint-dev__astroid-2198 | [
"1881"
] | python | diff --git a/astroid/nodes/node_ng.py b/astroid/nodes/node_ng.py
index 977469df90..af2d270e1b 100644
--- a/astroid/nodes/node_ng.py
+++ b/astroid/nodes/node_ng.py
@@ -210,7 +210,7 @@ def __str__(self) -> str:
alignment = len(cname) + 1
result = []
for field in self._other_fields + self._astroid_fields:
- value = getattr(self, field)
+ value = getattr(self, field, "Unknown")
width = 80 - len(field) - alignment
lines = pprint.pformat(value, indent=2, width=width).splitlines(True)
@@ -227,6 +227,11 @@ def __str__(self) -> str:
def __repr__(self) -> str:
rname = self.repr_name()
+ # The dependencies used to calculate fromlineno (if not cached) may not exist at the time
+ try:
+ lineno = self.fromlineno
+ except AttributeError:
+ lineno = 0
if rname:
string = "<%(cname)s.%(rname)s l.%(lineno)s at 0x%(id)x>"
else:
@@ -234,7 +239,7 @@ def __repr__(self) -> str:
return string % {
"cname": type(self).__name__,
"rname": rname,
- "lineno": self.fromlineno,
+ "lineno": lineno,
"id": id(self),
}
| Some `__str__` methods of nodes raise errors and warnings
### Steps to reproduce
```python
>>> fd = astroid.nodes.FunctionDef()
>>> str(fd)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/jacobwalls/astroid/astroid/nodes/node_ng.py", line 219, in __str__
value = getattr(self, field)
^^^^^^^^^^^^^^^^^^^^
AttributeError: 'FunctionDef' object has no attribute 'args'
```
Less severely, but still not great, launching python with warnings e.g. `python -Wall`:
```python
>>> cd = astroid.nodes.ClassDef()
>>> str(cd)
/Users/.../astroid/astroid/nodes/scoped_nodes/scoped_nodes.py:2041: DeprecationWarning: The 'ClassDef.doc' attribute is deprecated, use 'ClassDef.doc_node' instead.
```
***
We should add a unittest that generates the `str()` and `repr()` of all node types.
### `python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"` output
2.12.13
| 2198 | pylint-dev/astroid | diff --git a/tests/test_nodes.py b/tests/test_nodes.py
index 6303bbef28..d5c017dfc4 100644
--- a/tests/test_nodes.py
+++ b/tests/test_nodes.py
@@ -7,7 +7,9 @@
from __future__ import annotations
import copy
+import inspect
import os
+import random
import sys
import textwrap
import unittest
@@ -1880,3 +1882,35 @@ def return_from_match(x):
inferred = node.inferred()
assert len(inferred) == 2
assert [inf.value for inf in inferred] == [10, -1]
+
+
+@pytest.mark.parametrize(
+ "node",
+ [
+ node
+ for node in astroid.nodes.ALL_NODE_CLASSES
+ if node.__name__
+ not in ["_BaseContainer", "BaseContainer", "NodeNG", "const_factory"]
+ ],
+)
+@pytest.mark.filterwarnings("error")
+def test_str_repr_no_warnings(node):
+ parameters = inspect.signature(node.__init__).parameters
+
+ args = {}
+ for name, param_type in parameters.items():
+ if name == "self":
+ continue
+
+ if "int" in param_type.annotation:
+ args[name] = random.randint(0, 50)
+ elif "NodeNG" in param_type.annotation:
+ args[name] = nodes.Unknown()
+ elif "str" in param_type.annotation:
+ args[name] = ""
+ else:
+ args[name] = None
+
+ test_node = node(**args)
+ str(test_node)
+ repr(test_node)
| none | [
"tests/test_nodes.py::test_str_repr_no_warnings[AnnAssign]",
"tests/test_nodes.py::test_str_repr_no_warnings[Arguments]",
"tests/test_nodes.py::test_str_repr_no_warnings[Assert]",
"tests/test_nodes.py::test_str_repr_no_warnings[Assign]",
"tests/test_nodes.py::test_str_repr_no_warnings[AssignAttr]",
"tests... | [
"tests/test_nodes.py::AsStringTest::test_3k_annotations_and_metaclass",
"tests/test_nodes.py::AsStringTest::test_3k_as_string",
"tests/test_nodes.py::AsStringTest::test_as_string",
"tests/test_nodes.py::AsStringTest::test_as_string_for_list_containing_uninferable",
"tests/test_nodes.py::AsStringTest::test_a... | [
"pytest -rA"
] | pytest | {
"files": 1,
"hunks": 3,
"lines": 9
} |
I can work around it by replacing `...` with `yield`, but it doesn't seem that this should be necessary (and it wasn't in prior versions of Astroid). And it is hard to satisfy mypy with this workaround, because it expects `yield [value]` etc.
@belm0 thanks for the report.
The issue seems to have started with #934, the previous commit is fine: https://github.com/PyCQA/astroid/commit/2e8417ffc2285e798ccdef86f743abb75958e2c6. (Tested with pylint `2.8.3`.)
@nelfin Would you like to take a look at this?
Sure, happy to take this one
This doesn't seem to have anything to do with `@overload`. Here's a minimum reproducing example:
```python
class A:
def foo(self): ...
def foo(self):
yield
for _ in A().foo():
pass
```
I think this has to do with the name resolution order, `Attribute.foo` is inferred as the `foo(): ...` instead of `foo(): yield` and the lack of a function body means `infer_call_result` infers `None` (arguably correct, just given incorrect inputs). If you switch the order of the functions in the class body then there's no pylint warning (which is a false-negative). I'm chasing down the root cause and a fix.
https://github.com/PyCQA/pylint/issues/7624 have a use case related to this in pylint
Getting a similar problem with `pylint` on [`torch.nn.Module.to()`](https://github.com/pytorch/pytorch/blob/8dc60010573fd8249657d7711f39cc1e339a6b11/torch/nn/modules/module.py#L1030-L1043):
```python
from __future__ import annotations
from typing import Any, Union, overload
class device:
...
class Tensor:
...
class dtype:
...
class Module:
def __call__(self, *args: Any, **kwargs: Any) -> Any:
...
@overload
def to(self, dtype: Union[dtype, str]) -> Module:
...
@overload
def to(self, tensor: Tensor) -> Module:
...
def to(self, *args, **kwargs):
return self
tensor = Tensor()
module = Module()
_ = module(tensor) # OK
module = module.to("cpu")
_ = module(tensor) # a.py:46:4: E1102: module is not callable (not-callable)
```
```
astroid==2.15.4
pylint==2.17.4
```
THANKS @jacobtylerwalls -- this was a major bug for pre-typing code that returned different things depending on settings (would not write new code for that today) and needed `@overload` to specify the proper return values.
| 12ed435a97be78ce2d00f9ef818ec65d54f5ca82 | [
"https://github.com/pylint-dev/astroid/commit/4113a8f61ee3e9a8d5ff021f1bc02f96f2f532c7",
"https://github.com/pylint-dev/astroid/commit/5a86f413705fcb9ccb20d4a7d8716e003420f24b",
"https://github.com/pylint-dev/astroid/commit/38bb9c0b18b3a5f3038ef633ce250c411e7d6552",
"https://github.com/pylint-dev/astroid/comm... | 2021-09-15T08:41:50 | I can work around it by replacing `...` with `yield`, but it doesn't seem that this should be necessary (and it wasn't in prior versions of Astroid). And it is hard to satisfy mypy with this workaround, because it expects `yield [value]` etc.
@belm0 thanks for the report.
The issue seems to have started with #934, the previous commit is fine: https://github.com/PyCQA/astroid/commit/2e8417ffc2285e798ccdef86f743abb75958e2c6. (Tested with pylint `2.8.3`.)
@nelfin Would you like to take a look at this?
Sure, happy to take this one
| pylint-dev__astroid-1173 | [
"1015"
] | python | diff --git a/ChangeLog b/ChangeLog
index 86b614c1f6..ac5df56f4f 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -7,6 +7,11 @@ What's New in astroid 3.2.0?
============================
Release date: TBA
+* ``igetattr()`` returns the last same-named function in a class (instead of
+ the first). This avoids false positives in pylint with ``@overload``.
+
+ Closes #1015
+ Refs pylint-dev/pylint#4696
What's New in astroid 3.1.1?
diff --git a/astroid/nodes/scoped_nodes/scoped_nodes.py b/astroid/nodes/scoped_nodes/scoped_nodes.py
index 9cda4f1be0..79b7643e55 100644
--- a/astroid/nodes/scoped_nodes/scoped_nodes.py
+++ b/astroid/nodes/scoped_nodes/scoped_nodes.py
@@ -2508,12 +2508,21 @@ def igetattr(
# to the attribute happening *after* the attribute's definition (e.g. AugAssigns on lists)
if len(attributes) > 1:
first_attr, attributes = attributes[0], attributes[1:]
- first_scope = first_attr.scope()
+ first_scope = first_attr.parent.scope()
attributes = [first_attr] + [
attr
for attr in attributes
if attr.parent and attr.parent.scope() == first_scope
]
+ functions = [attr for attr in attributes if isinstance(attr, FunctionDef)]
+ if functions:
+ # Prefer only the last function, unless a property is involved.
+ last_function = functions[-1]
+ attributes = [
+ a
+ for a in attributes
+ if a not in functions or a is last_function or bases._is_property(a)
+ ]
for inferred in bases._infer_stmts(attributes, context, frame=self):
# yield Uninferable object instead of descriptors when necessary
| false not-an-iterable for class method with @overload (2.5.7 regression)
### Steps to reproduce
Starting from astroid 2.5.7, I'm seeing false not-an-iterable when generator class methods are annotated with `@overload`.
```python
from typing import overload, Iterator
class MyClass:
@overload
def transitions(self, foo: int, bar: int) -> Iterator[int]: ...
@overload
def transitions(self, baz: str) -> Iterator[str]: ...
def transitions(self, foo_or_baz, bar=None):
yield
for _ in MyClass().transitions('hello'):
pass
```
If `@overload` is removed, or the function is moved to the module level, or I switch to astroid 2.5.6, the problem goes away.
It happens with pylint-2.8.3 or pylint-3.0.0a3.
### Current behavior
E1133: Non-iterable value MyClass().transitions('hello') is used in an iterating context (not-an-iterable)
### Expected behavior
no error
| 1173 | pylint-dev/astroid | diff --git a/tests/test_inference.py b/tests/test_inference.py
index ffd78fe035..10fceb7b56 100644
--- a/tests/test_inference.py
+++ b/tests/test_inference.py
@@ -30,7 +30,7 @@
)
from astroid import decorators as decoratorsmod
from astroid.arguments import CallSite
-from astroid.bases import BoundMethod, Instance, UnboundMethod, UnionType
+from astroid.bases import BoundMethod, Generator, Instance, UnboundMethod, UnionType
from astroid.builder import AstroidBuilder, _extract_single_node, extract_node, parse
from astroid.const import IS_PYPY, PY39_PLUS, PY310_PLUS, PY312_PLUS
from astroid.context import CallContext, InferenceContext
@@ -4321,6 +4321,53 @@ class Test(Outer.Inner):
assert isinstance(inferred, nodes.Const)
assert inferred.value == 123
+ def test_infer_method_empty_body(self) -> None:
+ # https://github.com/PyCQA/astroid/issues/1015
+ node = extract_node(
+ """
+ class A:
+ def foo(self): ...
+
+ A().foo() #@
+ """
+ )
+ inferred = next(node.infer())
+ assert isinstance(inferred, nodes.Const)
+ assert inferred.value is None
+
+ def test_infer_method_overload(self) -> None:
+ # https://github.com/PyCQA/astroid/issues/1015
+ node = extract_node(
+ """
+ class A:
+ def foo(self): ...
+
+ def foo(self):
+ yield
+
+ A().foo() #@
+ """
+ )
+ inferred = list(node.infer())
+ assert len(inferred) == 1
+ assert isinstance(inferred[0], Generator)
+
+ def test_infer_function_under_if(self) -> None:
+ node = extract_node(
+ """
+ if 1 in [1]:
+ def func():
+ return 42
+ else:
+ def func():
+ return False
+
+ func() #@
+ """
+ )
+ inferred = list(node.inferred())
+ assert [const.value for const in inferred] == [42, False]
+
def test_delayed_attributes_without_slots(self) -> None:
ast_node = extract_node(
"""
| none | [
"tests/test_inference.py::InferenceTest::test_infer_method_overload"
] | [
"tests/test_inference.py::InferenceUtilsTest::test_path_wrapper",
"tests/test_inference.py::InferenceTest::test__new__",
"tests/test_inference.py::InferenceTest::test__new__bound_methods",
"tests/test_inference.py::InferenceTest::test_advanced_tupleassign_name_inference1",
"tests/test_inference.py::Inferenc... | [
"pytest -rA"
] | pytest | {
"files": 2,
"hunks": 2,
"lines": 16
} |
Hi @eugene57
Can I work on this issue?
Sure, I assigned you to the issue @pavan-msys :)
| 34fbf2ed10fdd3ce244c12584683f40ac3af984a | [
"https://github.com/pylint-dev/astroid/commit/05f0aa9594a069ffdd8c58776796bf6edb9161ff",
"https://github.com/pylint-dev/astroid/commit/d0da3a29bfeff4b2a18969d4eaa3996156698967"
] | 2025-05-26T16:30:17 | Hi @eugene57
Can I work on this issue?
Sure, I assigned you to the issue @pavan-msys :)
| pylint-dev__astroid-2756 | [
"2608"
] | python | diff --git a/ChangeLog b/ChangeLog
index 22ed00a05..d8fdfd63e 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -38,6 +38,10 @@ Release date: TBA
* Modify ``astroid.bases`` and ``tests.test_nodes`` to reflect that `enum.property` was added in Python 3.11, not 3.10
+* Fix incorrect result in `_get_relative_base_path` when the target directory name starts with the base path
+
+ Closes #2608
+
What's New in astroid 3.3.11?
=============================
Release date: TBA
diff --git a/astroid/modutils.py b/astroid/modutils.py
index 6029e33c1..6b84fe761 100644
--- a/astroid/modutils.py
+++ b/astroid/modutils.py
@@ -236,6 +236,14 @@ def check_modpath_has_init(path: str, mod_path: list[str]) -> bool:
return True
+def _is_subpath(path: str, base: str) -> bool:
+ path = os.path.normcase(os.path.normpath(path))
+ base = os.path.normcase(os.path.normpath(base))
+ if not path.startswith(base):
+ return False
+ return (len(path) == len(base)) or (path[len(base)] == os.path.sep)
+
+
def _get_relative_base_path(filename: str, path_to_check: str) -> list[str] | None:
"""Extracts the relative mod path of the file to import from.
@@ -252,19 +260,18 @@ def _get_relative_base_path(filename: str, path_to_check: str) -> list[str] | No
_get_relative_base_path("/a/b/c/d.py", "/a/b") -> ["c","d"]
_get_relative_base_path("/a/b/c/d.py", "/dev") -> None
"""
- importable_path = None
- path_to_check = os.path.normcase(path_to_check)
+ path_to_check = os.path.normcase(os.path.normpath(path_to_check))
+
abs_filename = os.path.abspath(filename)
- if os.path.normcase(abs_filename).startswith(path_to_check):
- importable_path = abs_filename
+ if _is_subpath(abs_filename, path_to_check):
+ base_path = os.path.splitext(abs_filename)[0]
+ relative_base_path = base_path[len(path_to_check) :].lstrip(os.path.sep)
+ return [pkg for pkg in relative_base_path.split(os.sep) if pkg]
real_filename = os.path.realpath(filename)
- if os.path.normcase(real_filename).startswith(path_to_check):
- importable_path = real_filename
-
- if importable_path:
- base_path = os.path.splitext(importable_path)[0]
- relative_base_path = base_path[len(path_to_check) :]
+ if _is_subpath(real_filename, path_to_check):
+ base_path = os.path.splitext(real_filename)[0]
+ relative_base_path = base_path[len(path_to_check) :].lstrip(os.path.sep)
return [pkg for pkg in relative_base_path.split(os.sep) if pkg]
return None
| modutils._get_relative_base_path returns incorrect result when directory name starts with directory name in path_to_check
Consider following call: `astroid.modutils._get_relative_base_path('something', os.path.join(os.getcwd(), 'some'))`.
I would expect this to return `None` by design. However, this returns `'thing'` instead.
This results in issues with running pylint on a project with following directory structure:
```
some
\- __init__.py
something
\- __init__.py
thing
\- __init__.py
```
I have observed this in astroid version 3.1.0, but it seems to me that the code in master is still the same.
| 2756 | pylint-dev/astroid | diff --git a/tests/test_get_relative_base_path.py b/tests/test_get_relative_base_path.py
new file mode 100644
index 000000000..ddf35588a
--- /dev/null
+++ b/tests/test_get_relative_base_path.py
@@ -0,0 +1,119 @@
+# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
+# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
+# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
+import os
+import tempfile
+import unittest
+
+from astroid import modutils
+
+
+class TestModUtilsRelativePath(unittest.TestCase):
+
+ def setUp(self):
+ self.cwd = os.getcwd()
+
+ def _run_relative_path_test(self, target, base, expected):
+ if not target or not base:
+ result = None
+ else:
+ base_dir = os.path.join(self.cwd, base)
+ target_path = os.path.join(self.cwd, target)
+ result = modutils._get_relative_base_path(target_path, base_dir)
+ self.assertEqual(result, expected)
+
+ def test_similar_prefixes_no_match(self):
+
+ cases = [
+ ("something", "some", None),
+ ("some-thing", "some", None),
+ ("some2", "some", None),
+ ("somedir", "some", None),
+ ("some_thing", "some", None),
+ ("some.dir", "some", None),
+ ]
+ for target, base, expected in cases:
+ with self.subTest(target=target, base=base):
+ self._run_relative_path_test(target, base, expected)
+
+ def test_valid_subdirectories(self):
+
+ cases = [
+ ("some/sub", "some", ["sub"]),
+ ("some/foo/bar", "some", ["foo", "bar"]),
+ ("some/foo-bar", "some", ["foo-bar"]),
+ ("some/foo/bar-ext", "some/foo", ["bar-ext"]),
+ ("something/sub", "something", ["sub"]),
+ ]
+ for target, base, expected in cases:
+ with self.subTest(target=target, base=base):
+ self._run_relative_path_test(target, base, expected)
+
+ def test_path_format_variations(self):
+
+ cases = [
+ ("some", "some", []),
+ ("some/", "some", []),
+ ("../some", "some", None),
+ ]
+
+ if os.path.isabs("/abs/path"):
+ cases.append(("/abs/path/some", "/abs/path", ["some"]))
+
+ for target, base, expected in cases:
+ with self.subTest(target=target, base=base):
+ self._run_relative_path_test(target, base, expected)
+
+ def test_case_sensitivity(self):
+
+ cases = [
+ ("Some/sub", "some", None if os.path.sep == "/" else ["sub"]),
+ ("some/Sub", "some", ["Sub"]),
+ ]
+ for target, base, expected in cases:
+ with self.subTest(target=target, base=base):
+ self._run_relative_path_test(target, base, expected)
+
+ def test_special_path_components(self):
+
+ cases = [
+ ("some/.hidden", "some", [".hidden"]),
+ ("some/with space", "some", ["with space"]),
+ ("some/unicode_ø", "some", ["unicode_ø"]),
+ ]
+ for target, base, expected in cases:
+ with self.subTest(target=target, base=base):
+ self._run_relative_path_test(target, base, expected)
+
+ def test_nonexistent_paths(self):
+
+ cases = [("nonexistent", "some", None), ("some/sub", "nonexistent", None)]
+ for target, base, expected in cases:
+ with self.subTest(target=target, base=base):
+ self._run_relative_path_test(target, base, expected)
+
+ def test_empty_paths(self):
+
+ cases = [("", "some", None), ("some", "", None), ("", "", None)]
+ for target, base, expected in cases:
+ with self.subTest(target=target, base=base):
+ self._run_relative_path_test(target, base, expected)
+
+ def test_symlink_resolution(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ base_dir = os.path.join(tmpdir, "some")
+ os.makedirs(base_dir, exist_ok=True)
+
+ real_file = os.path.join(base_dir, "real.py")
+ with open(real_file, "w", encoding="utf-8") as f:
+ f.write("# dummy content")
+
+ symlink_path = os.path.join(tmpdir, "symlink.py")
+ os.symlink(real_file, symlink_path)
+
+ result = modutils._get_relative_base_path(symlink_path, base_dir)
+ self.assertEqual(result, ["real"])
+
+
+if __name__ == "__main__":
+ unittest.main()
| none | [
"tests/test_get_relative_base_path.py::TestModUtilsRelativePath::test_similar_prefixes_no_match"
] | [
"tests/test_get_relative_base_path.py::TestModUtilsRelativePath::test_case_sensitivity",
"tests/test_get_relative_base_path.py::TestModUtilsRelativePath::test_empty_paths",
"tests/test_get_relative_base_path.py::TestModUtilsRelativePath::test_nonexistent_paths",
"tests/test_get_relative_base_path.py::TestModU... | [
"pytest -rA"
] | pytest | {
"files": 2,
"hunks": 3,
"lines": 31
} |
OSS-Fuzz discovered another `IndexError` when there's only one argument to `_alias` ([OSS-Fuzz bug report](https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=64639)):
```python
a = _alias(int)
```
```
Traceback (most recent call last):
File "pylint/pylint/checkers/utils.py", line 1365, in safe_infer
value = next(infer_gen)
^^^^^^^^^^^^^^^
File "astroid/astroid/nodes/node_ng.py", line 147, in infer
for result in self._explicit_inference(
^^^^^^^^^^^^^^^^^^^^^^^^^
File "astroid/astroid/inference_tip.py", line 70, in inner
raise e from None
File "astroid/astroid/inference_tip.py", line 66, in inner
func(node, context, **kwargs)
File "astroid/astroid/brain/brain_typing.py", line 330, in infer_typing_alias
maybe_type_var = node.args[1]
~~~~~~~~~^^^
IndexError: list index out of range
```
It seems like a comprehensive fix can handle both crashes. If not, I will file this issue separately.
| a8439ff4f822cde57151f083d987a7b7ed593fbf | [
"https://github.com/pylint-dev/astroid/commit/58a3c28feac91b84dba9fe1a9aed54478616d709"
] | 2024-10-23T17:48:15 | OSS-Fuzz discovered another `IndexError` when there's only one argument to `_alias` ([OSS-Fuzz bug report](https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=64639)):
```python
a = _alias(int)
```
```
Traceback (most recent call last):
File "pylint/pylint/checkers/utils.py", line 1365, in safe_infer
value = next(infer_gen)
^^^^^^^^^^^^^^^
File "astroid/astroid/nodes/node_ng.py", line 147, in infer
for result in self._explicit_inference(
^^^^^^^^^^^^^^^^^^^^^^^^^
File "astroid/astroid/inference_tip.py", line 70, in inner
raise e from None
File "astroid/astroid/inference_tip.py", line 66, in inner
func(node, context, **kwargs)
File "astroid/astroid/brain/brain_typing.py", line 330, in infer_typing_alias
maybe_type_var = node.args[1]
~~~~~~~~~^^^
IndexError: list index out of range
```
It seems like a comprehensive fix can handle both crashes. If not, I will file this issue separately.
| pylint-dev__astroid-2623 | [
"2513"
] | python | diff --git a/ChangeLog b/ChangeLog
index 036f888e08..8ab5375b4f 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -17,6 +17,10 @@ Release date: TBA
Closes #2521
Closes #2523
+* Fix crash when typing._alias() call is missing arguments.
+
+ Closes #2513
+
What's New in astroid 3.3.6?
============================
diff --git a/astroid/brain/brain_typing.py b/astroid/brain/brain_typing.py
index 239e63af24..c44687bf89 100644
--- a/astroid/brain/brain_typing.py
+++ b/astroid/brain/brain_typing.py
@@ -258,6 +258,7 @@ def _looks_like_typing_alias(node: Call) -> bool:
isinstance(node.func, Name)
# TODO: remove _DeprecatedGenericAlias when Py3.14 min
and node.func.name in {"_alias", "_DeprecatedGenericAlias"}
+ and len(node.args) == 2
and (
# _alias function works also for builtins object such as list and dict
isinstance(node.args[0], (Attribute, Name))
| IndexError when _alias() has no arguments
### Bug description
```python
_alias()
```
This bug was discovered by OSS-Fuzz:
https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=57984 (report not public yet)
### Configuration
```ini
N/A
```
### Command used
```shell
pylint a.py
```
### Pylint output
<details open>
<summary>Stacktrace</summary>
```
Traceback (most recent call last):
File "/home/s/code/pylint/pylint/lint/pylinter.py", line 974, in get_ast
return MANAGER.ast_from_file(filepath, modname, source=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/s/code/astroid/astroid/manager.py", line 167, in ast_from_file
return AstroidBuilder(self).file_build(filepath, modname)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/s/code/astroid/astroid/builder.py", line 145, in file_build
return self._post_build(module, builder, encoding)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/s/code/astroid/astroid/builder.py", line 173, in _post_build
module = self._manager.visit_transforms(module)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/s/code/astroid/astroid/manager.py", line 128, in visit_transforms
return self._transform.visit(node)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/s/code/astroid/astroid/transforms.py", line 162, in visit
return self._visit(node)
^^^^^^^^^^^^^^^^^
File "/home/s/code/astroid/astroid/transforms.py", line 84, in _visit
visited = self._visit_generic(value)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/s/code/astroid/astroid/transforms.py", line 112, in _visit_generic
return [self._visit_generic(child) for child in node]
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/s/code/astroid/astroid/transforms.py", line 119, in _visit_generic
return self._visit(node)
^^^^^^^^^^^^^^^^^
File "/home/s/code/astroid/astroid/transforms.py", line 84, in _visit
visited = self._visit_generic(value)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/s/code/astroid/astroid/transforms.py", line 119, in _visit_generic
return self._visit(node)
^^^^^^^^^^^^^^^^^
File "/home/s/code/astroid/astroid/transforms.py", line 87, in _visit
return self._transform(node)
^^^^^^^^^^^^^^^^^^^^^
File "/home/s/code/astroid/astroid/transforms.py", line 66, in _transform
if predicate is None or predicate(node):
^^^^^^^^^^^^^^^
File "/home/s/code/astroid/astroid/brain/brain_typing.py", line 262, in _looks_like_typing_alias
isinstance(node.args[0], (Attribute, Name))
~~~~~~~~~^^^
IndexError: list index out of range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/s/code/pylint/pylint/lint/pylinter.py", line 714, in _get_asts
ast_per_fileitem[fileitem] = self.get_ast(
^^^^^^^^^^^^^
File "/home/s/code/pylint/pylint/lint/pylinter.py", line 996, in get_ast
raise astroid.AstroidBuildingError(
astroid.exceptions.AstroidBuildingError: Building error when trying to create ast representation of module 'input'
```
</details>
### Expected behavior
No crash
### Pylint version
pylint 6bb335f5ca2c52a994d5836eee63dc2c140fc5f3
pylint-dev/astroid@f924ba2299328dc4d138ac9117edbfd0581f880b
### OS / Environment
Arch Linux
### Additional dependencies
_No response_
| 2623 | pylint-dev/astroid | diff --git a/tests/brain/test_typing.py b/tests/brain/test_typing.py
index 1e8e3eaf88..11b77b7f9e 100644
--- a/tests/brain/test_typing.py
+++ b/tests/brain/test_typing.py
@@ -4,7 +4,7 @@
import pytest
-from astroid import builder
+from astroid import bases, builder, nodes
from astroid.exceptions import InferenceError
@@ -23,3 +23,50 @@ def test_infer_typevar() -> None:
)
with pytest.raises(InferenceError):
call_node.inferred()
+
+
+class TestTypingAlias:
+ def test_infer_typing_alias(self) -> None:
+ """
+ Test that _alias() calls can be inferred.
+ """
+ node = builder.extract_node(
+ """
+ from typing import _alias
+ x = _alias(int, float)
+ """
+ )
+ assert isinstance(node, nodes.Assign)
+ assert isinstance(node.value, nodes.Call)
+ inferred = next(node.value.infer())
+ assert isinstance(inferred, nodes.ClassDef)
+ assert len(inferred.bases) == 1
+ assert inferred.bases[0].name == "int"
+
+ @pytest.mark.parametrize(
+ "alias_args",
+ [
+ "", # two missing arguments
+ "int", # one missing argument
+ "int, float, tuple", # one additional argument
+ ],
+ )
+ def test_infer_typing_alias_incorrect_number_of_arguments(
+ self, alias_args: str
+ ) -> None:
+ """
+ Regression test for: https://github.com/pylint-dev/astroid/issues/2513
+
+ Test that _alias() calls with the incorrect number of arguments can be inferred.
+ """
+ node = builder.extract_node(
+ f"""
+ from typing import _alias
+ x = _alias({alias_args})
+ """
+ )
+ assert isinstance(node, nodes.Assign)
+ assert isinstance(node.value, nodes.Call)
+ inferred = next(node.value.infer())
+ assert isinstance(inferred, bases.Instance)
+ assert inferred.name == "_SpecialGenericAlias"
| none | [
"tests/brain/test_typing.py::TestTypingAlias::test_infer_typing_alias_incorrect_number_of_arguments[]",
"tests/brain/test_typing.py::TestTypingAlias::test_infer_typing_alias_incorrect_number_of_arguments[int]",
"tests/brain/test_typing.py::TestTypingAlias::test_infer_typing_alias_incorrect_number_of_arguments[i... | [
"tests/brain/test_typing.py::test_infer_typevar",
"tests/brain/test_typing.py::TestTypingAlias::test_infer_typing_alias"
] | [
"pytest -rA"
] | pytest | {
"files": 2,
"hunks": 2,
"lines": 5
} |
Thank you for opening the issue.
I don't believe `Unknown().as_string()` is ever called regularly. AFAIK it's only used during inference. What should the string representation of an `Unknown` node be? So not sure this needs to be addressed.
Probably just `'Unknown'`.
It's mostly only a problem when we do something like this:
```python
inferred = infer(node)
if inferred is not Uninferable:
if inferred.as_string().contains(some_value):
...
```
So for the most part, as long as it doesn't crash we're good.
| ce5cbce5ba11cdc2f8139ade66feea1e181a7944 | [
"https://github.com/pylint-dev/astroid/commit/eb3b3a21ff08ca50fb3abbaf4b5229f923596caf",
"https://github.com/pylint-dev/astroid/commit/81fbae69befe04663f433ba471662aee90951aa1",
"https://github.com/pylint-dev/astroid/commit/9b6ebb18f75f49da85fd3543b71ed532911b1ede"
] | 2021-11-21T16:15:23 | Thank you for opening the issue.
I don't believe `Unknown().as_string()` is ever called regularly. AFAIK it's only used during inference. What should the string representation of an `Unknown` node be? So not sure this needs to be addressed.
Probably just `'Unknown'`.
It's mostly only a problem when we do something like this:
```python
inferred = infer(node)
if inferred is not Uninferable:
if inferred.as_string().contains(some_value):
...
```
So for the most part, as long as it doesn't crash we're good.
| pylint-dev__astroid-1268 | [
"1264"
] | python | diff --git a/ChangeLog b/ChangeLog
index 0f047d393c..944b76f91c 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -8,6 +8,10 @@ Release date: TBA
* Always treat ``__class_getitem__`` as a classmethod.
+* Add missing ``as_string`` visitor method for ``Unknown`` node.
+
+ Closes #1264
+
What's New in astroid 2.8.6?
============================
diff --git a/astroid/nodes/as_string.py b/astroid/nodes/as_string.py
index 427ccc151e..bc8dab1c16 100644
--- a/astroid/nodes/as_string.py
+++ b/astroid/nodes/as_string.py
@@ -36,6 +36,7 @@
MatchSingleton,
MatchStar,
MatchValue,
+ Unknown,
)
# pylint: disable=unused-argument
@@ -643,6 +644,9 @@ def visit_property(self, node):
def visit_evaluatedobject(self, node):
return node.original.accept(self)
+ def visit_unknown(self, node: "Unknown") -> str:
+ return str(node)
+
def _import_string(names):
"""return a list of (name, asname) formatted as a string"""
| 'AsStringVisitor' object has no attribute 'visit_unknown'
```python
>>> import astroid
>>> astroid.nodes.Unknown().as_string()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/node_ng.py", line 609, in as_string
return AsStringVisitor()(self)
File "/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/as_string.py", line 56, in __call__
return node.accept(self).replace(DOC_NEWLINE, "\n")
File "/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/node_ng.py", line 220, in accept
func = getattr(visitor, "visit_" + self.__class__.__name__.lower())
AttributeError: 'AsStringVisitor' object has no attribute 'visit_unknown'
>>>
```
### `python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"` output
2.8.6-dev0
| 1268 | pylint-dev/astroid | diff --git a/tests/unittest_nodes.py b/tests/unittest_nodes.py
index 7c78cd23ed..8c860eac3a 100644
--- a/tests/unittest_nodes.py
+++ b/tests/unittest_nodes.py
@@ -306,6 +306,11 @@ def test_f_strings(self):
ast = abuilder.string_build(code)
self.assertEqual(ast.as_string().strip(), code.strip())
+ @staticmethod
+ def test_as_string_unknown() -> None:
+ assert nodes.Unknown().as_string() == "Unknown.Unknown()"
+ assert nodes.Unknown(lineno=1, col_offset=0).as_string() == "Unknown.Unknown()"
+
class _NodeTest(unittest.TestCase):
"""test transformation of If Node"""
| none | [
"tests/unittest_nodes.py::AsStringTest::test_as_string_unknown"
] | [
"tests/unittest_nodes.py::AsStringTest::test_3k_annotations_and_metaclass",
"tests/unittest_nodes.py::AsStringTest::test_3k_as_string",
"tests/unittest_nodes.py::AsStringTest::test_as_string",
"tests/unittest_nodes.py::AsStringTest::test_as_string_for_list_containing_uninferable",
"tests/unittest_nodes.py::... | [
"pytest -rA tests/"
] | pytest | {
"files": 2,
"hunks": 3,
"lines": 8
} |
0824812ed2999413f00d80fa58805b1b47c1ccc5 | ["https://github.com/pylint-dev/astroid/commit/ef7520df9bbd7e387e6e131ab17d250b5d5da692","https://gi(...TRUNCATED) | 2022-06-07T10:37:43 | pylint-dev__astroid-1602 | [
"104"
] | python | "diff --git a/ChangeLog b/ChangeLog\nindex 7db3e6c682..4cc346a478 100644\n--- a/ChangeLog\n+++ b/Cha(...TRUNCATED) | "String formatting is inferred as empty string\nOriginally reported by: **Florian Bruhin (BitBucket:(...TRUNCATED) | 1602 | pylint-dev/astroid | "diff --git a/tests/unittest_brain_builtin.py b/tests/unittest_brain_builtin.py\nindex 0d7493034a..a(...TRUNCATED) | none | ["tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[empty-indexes]","tests/unitte(...TRUNCATED) | ["tests/unittest_brain_builtin.py::BuiltinsTest::test_infer_property","tests/unittest_inference.py::(...TRUNCATED) | [
"pytest -rA tests/"
] | pytest | {
"files": 2,
"hunks": 3,
"lines": 50
} |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 9