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/commit/c801ca690609007dfdcff5d7fc0c7a9f9c924474",
"https://github.com/pylint-dev/astroid/commit/ce10268fad96ab2c46ef486a02b0f6c8fdc543cf"
] | 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_inference.py::InferenceTest::test_advanced_tupleassign_name_inference2",
"tests/unittest_inference.py::InferenceTest::test_ancestors_inference",
"tests/unittest_inference.py::InferenceTest::test_ancestors_inference2",
"tests/unittest_inference.py::InferenceTest::test_args_default_inference1",
"tests/unittest_inference.py::InferenceTest::test_args_default_inference2",
"tests/unittest_inference.py::InferenceTest::test_aug_different_types_aug_not_implemented",
"tests/unittest_inference.py::InferenceTest::test_aug_different_types_aug_not_implemented_rop_fallback",
"tests/unittest_inference.py::InferenceTest::test_aug_different_types_augop_implemented",
"tests/unittest_inference.py::InferenceTest::test_aug_different_types_no_method_implemented",
"tests/unittest_inference.py::InferenceTest::test_aug_op_same_type_aug_implemented",
"tests/unittest_inference.py::InferenceTest::test_aug_op_same_type_aug_not_implemented_normal_implemented",
"tests/unittest_inference.py::InferenceTest::test_aug_op_same_type_not_implemented",
"tests/unittest_inference.py::InferenceTest::test_aug_op_subtype_aug_op_is_implemented",
"tests/unittest_inference.py::InferenceTest::test_aug_op_subtype_both_not_implemented",
"tests/unittest_inference.py::InferenceTest::test_aug_op_subtype_normal_op_is_implemented",
"tests/unittest_inference.py::InferenceTest::test_augassign",
"tests/unittest_inference.py::InferenceTest::test_augop_supertypes_augop_implemented",
"tests/unittest_inference.py::InferenceTest::test_augop_supertypes_none_implemented",
"tests/unittest_inference.py::InferenceTest::test_augop_supertypes_normal_binop_implemented",
"tests/unittest_inference.py::InferenceTest::test_augop_supertypes_not_implemented_returned_for_all",
"tests/unittest_inference.py::InferenceTest::test_augop_supertypes_reflected_binop_implemented",
"tests/unittest_inference.py::InferenceTest::test_bin_op_classes",
"tests/unittest_inference.py::InferenceTest::test_bin_op_supertype_more_complicated_example",
"tests/unittest_inference.py::InferenceTest::test_binary_op_custom_class",
"tests/unittest_inference.py::InferenceTest::test_binary_op_float_div",
"tests/unittest_inference.py::InferenceTest::test_binary_op_int_add",
"tests/unittest_inference.py::InferenceTest::test_binary_op_int_bitand",
"tests/unittest_inference.py::InferenceTest::test_binary_op_int_bitor",
"tests/unittest_inference.py::InferenceTest::test_binary_op_int_bitxor",
"tests/unittest_inference.py::InferenceTest::test_binary_op_int_shiftleft",
"tests/unittest_inference.py::InferenceTest::test_binary_op_int_shiftright",
"tests/unittest_inference.py::InferenceTest::test_binary_op_int_sub",
"tests/unittest_inference.py::InferenceTest::test_binary_op_list_mul",
"tests/unittest_inference.py::InferenceTest::test_binary_op_list_mul_int",
"tests/unittest_inference.py::InferenceTest::test_binary_op_list_mul_none",
"tests/unittest_inference.py::InferenceTest::test_binary_op_on_self",
"tests/unittest_inference.py::InferenceTest::test_binary_op_other_type",
"tests/unittest_inference.py::InferenceTest::test_binary_op_other_type_using_reflected_operands",
"tests/unittest_inference.py::InferenceTest::test_binary_op_reflected_and_not_implemented_is_type_error",
"tests/unittest_inference.py::InferenceTest::test_binary_op_str_mul",
"tests/unittest_inference.py::InferenceTest::test_binary_op_tuple_add",
"tests/unittest_inference.py::InferenceTest::test_binary_op_type_errors",
"tests/unittest_inference.py::InferenceTest::test_binop_ambiguity",
"tests/unittest_inference.py::InferenceTest::test_binop_different_types_no_method_implemented",
"tests/unittest_inference.py::InferenceTest::test_binop_different_types_normal_not_implemented_and_reflected",
"tests/unittest_inference.py::InferenceTest::test_binop_different_types_reflected_and_normal_not_implemented",
"tests/unittest_inference.py::InferenceTest::test_binop_different_types_reflected_only",
"tests/unittest_inference.py::InferenceTest::test_binop_different_types_unknown_bases",
"tests/unittest_inference.py::InferenceTest::test_binop_inference_errors",
"tests/unittest_inference.py::InferenceTest::test_binop_list_with_elts",
"tests/unittest_inference.py::InferenceTest::test_binop_same_types",
"tests/unittest_inference.py::InferenceTest::test_binop_subtype",
"tests/unittest_inference.py::InferenceTest::test_binop_subtype_implemented_in_parent",
"tests/unittest_inference.py::InferenceTest::test_binop_subtype_not_implemented",
"tests/unittest_inference.py::InferenceTest::test_binop_supertype",
"tests/unittest_inference.py::InferenceTest::test_binop_supertype_both_not_implemented",
"tests/unittest_inference.py::InferenceTest::test_binop_supertype_rop_not_implemented",
"tests/unittest_inference.py::InferenceTest::test_bool_value",
"tests/unittest_inference.py::InferenceTest::test_bool_value_instances",
"tests/unittest_inference.py::InferenceTest::test_bool_value_recursive",
"tests/unittest_inference.py::InferenceTest::test_bool_value_variable",
"tests/unittest_inference.py::InferenceTest::test_bound_method_inference",
"tests/unittest_inference.py::InferenceTest::test_bt_ancestor_crash",
"tests/unittest_inference.py::InferenceTest::test_builtin_help",
"tests/unittest_inference.py::InferenceTest::test_builtin_inference_py3k",
"tests/unittest_inference.py::InferenceTest::test_builtin_name_inference",
"tests/unittest_inference.py::InferenceTest::test_builtin_open",
"tests/unittest_inference.py::InferenceTest::test_builtin_types",
"tests/unittest_inference.py::InferenceTest::test_bytes_subscript",
"tests/unittest_inference.py::InferenceTest::test_callfunc_context_func",
"tests/unittest_inference.py::InferenceTest::test_callfunc_context_lambda",
"tests/unittest_inference.py::InferenceTest::test_callfunc_inference",
"tests/unittest_inference.py::InferenceTest::test_class_inference",
"tests/unittest_inference.py::InferenceTest::test_classmethod_inferred_by_context",
"tests/unittest_inference.py::InferenceTest::test_context_call_for_context_managers",
"tests/unittest_inference.py::InferenceTest::test_conversion_of_dict_methods",
"tests/unittest_inference.py::InferenceTest::test_del1",
"tests/unittest_inference.py::InferenceTest::test_del2",
"tests/unittest_inference.py::InferenceTest::test_delayed_attributes_without_slots",
"tests/unittest_inference.py::InferenceTest::test_dict_inference",
"tests/unittest_inference.py::InferenceTest::test_dict_inference_for_multiple_starred",
"tests/unittest_inference.py::InferenceTest::test_dict_inference_kwargs",
"tests/unittest_inference.py::InferenceTest::test_dict_inference_unpack_repeated_key",
"tests/unittest_inference.py::InferenceTest::test_dict_invalid_args",
"tests/unittest_inference.py::InferenceTest::test_exc_ancestors",
"tests/unittest_inference.py::InferenceTest::test_except_inference",
"tests/unittest_inference.py::InferenceTest::test_f_arg_f",
"tests/unittest_inference.py::InferenceTest::test_factory_method",
"tests/unittest_inference.py::InferenceTest::test_factory_methods_cls_call",
"tests/unittest_inference.py::InferenceTest::test_factory_methods_object_new_call",
"tests/unittest_inference.py::InferenceTest::test_float_complex_ambiguity",
"tests/unittest_inference.py::InferenceTest::test_frozenset_builtin_inference",
"tests/unittest_inference.py::InferenceTest::test_function_inference",
"tests/unittest_inference.py::InferenceTest::test_genexpr_bool_value",
"tests/unittest_inference.py::InferenceTest::test_getattr_inference1",
"tests/unittest_inference.py::InferenceTest::test_getattr_inference2",
"tests/unittest_inference.py::InferenceTest::test_getattr_inference3",
"tests/unittest_inference.py::InferenceTest::test_getattr_inference4",
"tests/unittest_inference.py::InferenceTest::test_getitem_of_class_raised_type_error",
"tests/unittest_inference.py::InferenceTest::test_im_func_unwrap",
"tests/unittest_inference.py::InferenceTest::test_import_as",
"tests/unittest_inference.py::InferenceTest::test_infer_abstract_property_return_values",
"tests/unittest_inference.py::InferenceTest::test_infer_arg_called_object_when_used_as_index_is_uninferable",
"tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_defined_in_outer_scope_is_uninferable",
"tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_is_uninferable",
"tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_when_used_as_index_is_uninferable",
"tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_when_used_as_subscript_is_uninferable",
"tests/unittest_inference.py::InferenceTest::test_infer_arguments",
"tests/unittest_inference.py::InferenceTest::test_infer_call_result_crash",
"tests/unittest_inference.py::InferenceTest::test_infer_call_result_invalid_dunder_call_on_instance",
"tests/unittest_inference.py::InferenceTest::test_infer_cls_in_class_methods",
"tests/unittest_inference.py::InferenceTest::test_infer_coercion_rules_for_floats_complex",
"tests/unittest_inference.py::InferenceTest::test_infer_empty_nodes",
"tests/unittest_inference.py::InferenceTest::test_infer_nested",
"tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_inner_class",
"tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_inner_class_works_indirectly",
"tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_instance_attr",
"tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_instance_attr_indirect",
"tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_outer_class",
"tests/unittest_inference.py::InferenceTest::test_infer_variable_arguments",
"tests/unittest_inference.py::InferenceTest::test_inference_restrictions",
"tests/unittest_inference.py::InferenceTest::test_inferring_context_manager_skip_index_error",
"tests/unittest_inference.py::InferenceTest::test_inferring_context_manager_unpacking_inference_error",
"tests/unittest_inference.py::InferenceTest::test_inferring_with_contextlib_contextmanager",
"tests/unittest_inference.py::InferenceTest::test_inferring_with_contextlib_contextmanager_failures",
"tests/unittest_inference.py::InferenceTest::test_inferring_with_statement",
"tests/unittest_inference.py::InferenceTest::test_inferring_with_statement_failures",
"tests/unittest_inference.py::InferenceTest::test_infinite_loop_for_decorators",
"tests/unittest_inference.py::InferenceTest::test_inner_value_redefined_by_subclass",
"tests/unittest_inference.py::InferenceTest::test_instance_binary_operations",
"tests/unittest_inference.py::InferenceTest::test_instance_binary_operations_multiple_methods",
"tests/unittest_inference.py::InferenceTest::test_instance_binary_operations_parent",
"tests/unittest_inference.py::InferenceTest::test_instance_slicing",
"tests/unittest_inference.py::InferenceTest::test_instance_slicing_fails",
"tests/unittest_inference.py::InferenceTest::test_instance_slicing_slices",
"tests/unittest_inference.py::InferenceTest::test_invalid_slicing_primaries",
"tests/unittest_inference.py::InferenceTest::test_invalid_subscripts",
"tests/unittest_inference.py::InferenceTest::test_lambda_as_methods",
"tests/unittest_inference.py::InferenceTest::test_list_builtin_inference",
"tests/unittest_inference.py::InferenceTest::test_list_inference",
"tests/unittest_inference.py::InferenceTest::test_listassign_name_inference",
"tests/unittest_inference.py::InferenceTest::test_lookup_cond_branches",
"tests/unittest_inference.py::InferenceTest::test_matmul",
"tests/unittest_inference.py::InferenceTest::test_metaclass__getitem__",
"tests/unittest_inference.py::InferenceTest::test_metaclass_custom_dunder_call",
"tests/unittest_inference.py::InferenceTest::test_metaclass_custom_dunder_call_boundnode",
"tests/unittest_inference.py::InferenceTest::test_metaclass_subclasses_arguments_are_classes_not_instances",
"tests/unittest_inference.py::InferenceTest::test_metaclass_with_keyword_args",
"tests/unittest_inference.py::InferenceTest::test_method_argument",
"tests/unittest_inference.py::InferenceTest::test_module_inference",
"tests/unittest_inference.py::InferenceTest::test_mul_list_supports__index__",
"tests/unittest_inference.py::InferenceTest::test_mulassign_inference",
"tests/unittest_inference.py::InferenceTest::test_name_bool_value",
"tests/unittest_inference.py::InferenceTest::test_nested_contextmanager",
"tests/unittest_inference.py::InferenceTest::test_no_infinite_ancestor_loop",
"tests/unittest_inference.py::InferenceTest::test_no_runtime_error_in_repeat_inference",
"tests/unittest_inference.py::InferenceTest::test_nonregr_absolute_import",
"tests/unittest_inference.py::InferenceTest::test_nonregr_func_arg",
"tests/unittest_inference.py::InferenceTest::test_nonregr_func_global",
"tests/unittest_inference.py::InferenceTest::test_nonregr_getitem_empty_tuple",
"tests/unittest_inference.py::InferenceTest::test_nonregr_inference_modifying_col_offset",
"tests/unittest_inference.py::InferenceTest::test_nonregr_instance_attrs",
"tests/unittest_inference.py::InferenceTest::test_nonregr_lambda_arg",
"tests/unittest_inference.py::InferenceTest::test_nonregr_layed_dictunpack",
"tests/unittest_inference.py::InferenceTest::test_nonregr_multi_referential_addition",
"tests/unittest_inference.py::InferenceTest::test_pluggable_inference",
"tests/unittest_inference.py::InferenceTest::test_property",
"tests/unittest_inference.py::InferenceTest::test_python25_no_relative_import",
"tests/unittest_inference.py::InferenceTest::test_scope_lookup_same_attributes",
"tests/unittest_inference.py::InferenceTest::test_set_builtin_inference",
"tests/unittest_inference.py::InferenceTest::test_simple_for",
"tests/unittest_inference.py::InferenceTest::test_simple_for_genexpr",
"tests/unittest_inference.py::InferenceTest::test_simple_subscript",
"tests/unittest_inference.py::InferenceTest::test_simple_tuple",
"tests/unittest_inference.py::InferenceTest::test_slicing_list",
"tests/unittest_inference.py::InferenceTest::test_slicing_str",
"tests/unittest_inference.py::InferenceTest::test_slicing_tuple",
"tests/unittest_inference.py::InferenceTest::test_special_method_masquerading_as_another",
"tests/unittest_inference.py::InferenceTest::test_starred_in_list_literal",
"tests/unittest_inference.py::InferenceTest::test_starred_in_literals_inference_issues",
"tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_inference_issues",
"tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_literal",
"tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_literal_no_inference_possible",
"tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_literal_non_const_keys_values",
"tests/unittest_inference.py::InferenceTest::test_starred_in_set_literal",
"tests/unittest_inference.py::InferenceTest::test_starred_in_tuple_literal",
"tests/unittest_inference.py::InferenceTest::test_stop_iteration_leak",
"tests/unittest_inference.py::InferenceTest::test_str_methods",
"tests/unittest_inference.py::InferenceTest::test_subscript_inference_error",
"tests/unittest_inference.py::InferenceTest::test_subscript_multi_slice",
"tests/unittest_inference.py::InferenceTest::test_subscript_multi_value",
"tests/unittest_inference.py::InferenceTest::test_subscript_supports__index__",
"tests/unittest_inference.py::InferenceTest::test_swap_assign_inference",
"tests/unittest_inference.py::InferenceTest::test_tuple_builtin_inference",
"tests/unittest_inference.py::InferenceTest::test_tuple_then_list",
"tests/unittest_inference.py::InferenceTest::test_tupleassign_name_inference",
"tests/unittest_inference.py::InferenceTest::test_two_parents_from_same_module",
"tests/unittest_inference.py::InferenceTest::test_type__new__invalid_attrs",
"tests/unittest_inference.py::InferenceTest::test_type__new__invalid_bases",
"tests/unittest_inference.py::InferenceTest::test_type__new__invalid_mcs_argument",
"tests/unittest_inference.py::InferenceTest::test_type__new__invalid_name",
"tests/unittest_inference.py::InferenceTest::test_type__new__metaclass_and_ancestors_lookup",
"tests/unittest_inference.py::InferenceTest::test_type__new__metaclass_lookup",
"tests/unittest_inference.py::InferenceTest::test_type__new__not_enough_arguments",
"tests/unittest_inference.py::InferenceTest::test_type__new__with_metaclass",
"tests/unittest_inference.py::InferenceTest::test_unary_empty_type_errors",
"tests/unittest_inference.py::InferenceTest::test_unary_not",
"tests/unittest_inference.py::InferenceTest::test_unary_op_assignment",
"tests/unittest_inference.py::InferenceTest::test_unary_op_classes",
"tests/unittest_inference.py::InferenceTest::test_unary_op_instance_method_not_callable",
"tests/unittest_inference.py::InferenceTest::test_unary_op_leaks_stop_iteration",
"tests/unittest_inference.py::InferenceTest::test_unary_op_numbers",
"tests/unittest_inference.py::InferenceTest::test_unary_operands",
"tests/unittest_inference.py::InferenceTest::test_unary_type_errors",
"tests/unittest_inference.py::InferenceTest::test_unary_type_errors_for_non_instance_objects",
"tests/unittest_inference.py::InferenceTest::test_unbound_method_inference",
"tests/unittest_inference.py::InferenceTest::test_unicode_methods",
"tests/unittest_inference.py::GetattrTest::test_attribute_missing",
"tests/unittest_inference.py::GetattrTest::test_attrname_not_string",
"tests/unittest_inference.py::GetattrTest::test_default",
"tests/unittest_inference.py::GetattrTest::test_lambda",
"tests/unittest_inference.py::GetattrTest::test_lookup",
"tests/unittest_inference.py::GetattrTest::test_yes_when_unknown",
"tests/unittest_inference.py::HasattrTest::test_attribute_is_missing",
"tests/unittest_inference.py::HasattrTest::test_attribute_is_not_missing",
"tests/unittest_inference.py::HasattrTest::test_inference_errors",
"tests/unittest_inference.py::HasattrTest::test_lambda",
"tests/unittest_inference.py::BoolOpTest::test_bool_ops",
"tests/unittest_inference.py::BoolOpTest::test_other_nodes",
"tests/unittest_inference.py::BoolOpTest::test_yes_when_unknown",
"tests/unittest_inference.py::TestCallable::test_callable",
"tests/unittest_inference.py::TestCallable::test_callable_methods",
"tests/unittest_inference.py::TestCallable::test_inference_errors",
"tests/unittest_inference.py::TestCallable::test_not_callable",
"tests/unittest_inference.py::TestBool::test_bool",
"tests/unittest_inference.py::TestBool::test_bool_bool_special_method",
"tests/unittest_inference.py::TestBool::test_bool_instance_not_callable",
"tests/unittest_inference.py::TestType::test_type",
"tests/unittest_inference.py::ArgumentsTest::test_args",
"tests/unittest_inference.py::ArgumentsTest::test_defaults",
"tests/unittest_inference.py::ArgumentsTest::test_fail_to_infer_args",
"tests/unittest_inference.py::ArgumentsTest::test_kwargs",
"tests/unittest_inference.py::ArgumentsTest::test_kwargs_access_by_name",
"tests/unittest_inference.py::ArgumentsTest::test_kwargs_and_other_named_parameters",
"tests/unittest_inference.py::ArgumentsTest::test_kwargs_are_overridden",
"tests/unittest_inference.py::ArgumentsTest::test_kwonly_args",
"tests/unittest_inference.py::ArgumentsTest::test_multiple_kwargs",
"tests/unittest_inference.py::ArgumentsTest::test_multiple_starred_args",
"tests/unittest_inference.py::SliceTest::test_slice",
"tests/unittest_inference.py::SliceTest::test_slice_attributes",
"tests/unittest_inference.py::SliceTest::test_slice_inference_error",
"tests/unittest_inference.py::SliceTest::test_slice_type",
"tests/unittest_inference.py::CallSiteTest::test_call_site",
"tests/unittest_inference.py::CallSiteTest::test_call_site_starred_args",
"tests/unittest_inference.py::CallSiteTest::test_call_site_valid_arguments",
"tests/unittest_inference.py::CallSiteTest::test_duplicated_keyword_arguments",
"tests/unittest_inference.py::ObjectDunderNewTest::test_object_dunder_new_is_inferred_if_decorator",
"tests/unittest_inference.py::test_augassign_recursion",
"tests/unittest_inference.py::test_infer_custom_inherit_from_property",
"tests/unittest_inference.py::test_cannot_infer_call_result_for_builtin_methods",
"tests/unittest_inference.py::test_unpack_dicts_in_assignment",
"tests/unittest_inference.py::test_slice_inference_in_for_loops",
"tests/unittest_inference.py::test_slice_inference_in_for_loops_not_working",
"tests/unittest_inference.py::test_unpacking_starred_and_dicts_in_assignment",
"tests/unittest_inference.py::test_unpacking_starred_empty_list_in_assignment",
"tests/unittest_inference.py::test_regression_infinite_loop_decorator",
"tests/unittest_inference.py::test_stop_iteration_in_int",
"tests/unittest_inference.py::test_call_on_instance_with_inherited_dunder_call_method",
"tests/unittest_inference.py::TestInferencePropagation::test_call_starargs_propagation",
"tests/unittest_inference.py::TestInferencePropagation::test_call_kwargs_propagation",
"tests/unittest_inference.py::test_limit_inference_result_amount",
"tests/unittest_inference.py::test_attribute_inference_should_not_access_base_classes",
"tests/unittest_inference.py::test_attribute_mro_object_inference",
"tests/unittest_inference.py::test_inferred_sequence_unpacking_works",
"tests/unittest_inference.py::test_recursion_error_inferring_slice",
"tests/unittest_inference.py::test_exception_lookup_last_except_handler_wins",
"tests/unittest_inference.py::test_exception_lookup_name_bound_in_except_handler",
"tests/unittest_inference.py::test_builtin_inference_list_of_exceptions",
"tests/unittest_inference.py::test_cannot_getattr_ann_assigns",
"tests/unittest_inference.py::test_prevent_recursion_error_in_igetattr_and_context_manager_inference",
"tests/unittest_inference.py::test_infer_context_manager_with_unknown_args",
"tests/unittest_inference.py::test_subclass_of_exception[\\n",
"tests/unittest_inference.py::test_ifexp_inference",
"tests/unittest_inference.py::test_assert_last_function_returns_none_on_inference",
"tests/unittest_inference.py::test_posonlyargs_inference",
"tests/unittest_inference.py::test_infer_args_unpacking_of_self",
"tests/unittest_inference.py::test_infer_exception_instance_attributes",
"tests/unittest_inference.py::test_inference_is_limited_to_the_boundnode[\\n",
"tests/unittest_inference.py::test_property_inference",
"tests/unittest_inference.py::test_property_as_string",
"tests/unittest_inference.py::test_property_callable_inference",
"tests/unittest_inference.py::test_recursion_error_inferring_builtin_containers",
"tests/unittest_inference.py::test_inferaugassign_picking_parent_instead_of_stmt",
"tests/unittest_inference.py::test_classmethod_from_builtins_inferred_as_bound",
"tests/unittest_inference.py::test_infer_dict_passes_context",
"tests/unittest_inference.py::test_custom_decorators_for_classmethod_and_staticmethods[\\n",
"tests/unittest_inference.py::test_dataclasses_subscript_inference_recursion_error_39",
"tests/unittest_inference.py::test_self_reference_infer_does_not_trigger_recursion_error",
"tests/unittest_inference.py::test_inferring_properties_multiple_time_does_not_mutate_locals_multiple_times",
"tests/unittest_inference.py::test_getattr_fails_on_empty_values",
"tests/unittest_inference.py::test_infer_first_argument_of_static_method_in_metaclass",
"tests/unittest_inference.py::test_recursion_error_metaclass_monkeypatching",
"tests/unittest_inference.py::test_allow_retrieving_instance_attrs_and_special_attrs_for_functions",
"tests/unittest_inference.py::test_implicit_parameters_bound_method",
"tests/unittest_inference.py::test_super_inference_of_abstract_property",
"tests/unittest_inference.py::test_infer_generated_setter",
"tests/unittest_inference.py::test_infer_list_of_uninferables_does_not_crash",
"tests/unittest_inference.py::test_issue926_infer_stmts_referencing_same_name_is_not_uninferable",
"tests/unittest_inference.py::test_issue926_binop_referencing_same_name_is_not_uninferable",
"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/unittest_scoped_nodes.py::ModuleNodeTest::test_getattr",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_1",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_2",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_module_getattr",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_public_names",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name_beyond_top_level",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_special_attributes",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_stream_api",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_wildcard_import_names",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_argnames",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_decorator_builtin_descriptors",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_default_value",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dict_interface",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_classmethod",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_function",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_method",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args_keyword_only_args",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_four_args",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_func_instance_attr",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_igetattr",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract_decorated",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_generator",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_method",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_pytype",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_qname",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_method_init_subclass",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_navigation",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_annotation_is_not_the_last",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_nothing",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_special_attributes",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_type_builtin_descriptor_subclasses",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test__bases__attribute",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test__mro__attribute",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_add_metaclass",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_all_ancestors_need_slots",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_ancestors",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_frame_is_not_class",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_assignment_names_are_considered",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_callfunc_are_considered",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_same_name_considered",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_getattr",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_keywords",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_classmethod_attributes",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_1",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_2",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_dict_interface",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_duplicate_bases_namedtuple",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_extra_decorators_only_class_level_assignments",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_function_with_decorator_lineno",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_generator_from_infer_call_result_parent",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_from_grandpa",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_method_transform",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_has_dynamic_getattr",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass_lookup",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_inner_classes",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_attr_ancestors",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas_2",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr_with_class_attr",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_special_attributes",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_kite_graph",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_ancestors",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_invalid_mro",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_mro",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_error",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_inference_errors",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_using_same_class",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_type",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_yes_leak",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_methods",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_1",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_2",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_3",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_4",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_5",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_6",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_7",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_1",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_2",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_attribute_classes",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_factories",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_navigation",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop_with_redefine",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_nonregr_infer_callresult",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_added_dynamically_still_inferred",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_empty_list_of_slots",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_for_dict_keys",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_taken_from_parents",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_type",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_type_three_arguments",
"tests/unittest_scoped_nodes.py::test_issue940_metaclass_subclass_property",
"tests/unittest_scoped_nodes.py::test_issue940_property_grandchild",
"tests/unittest_scoped_nodes.py::test_issue940_metaclass_property",
"tests/unittest_scoped_nodes.py::test_issue940_with_metaclass_class_context_property",
"tests/unittest_scoped_nodes.py::test_issue940_metaclass_values_funcdef",
"tests/unittest_scoped_nodes.py::test_issue940_metaclass_derived_funcdef",
"tests/unittest_scoped_nodes.py::test_issue940_metaclass_funcdef_is_not_datadescriptor",
"tests/unittest_scoped_nodes.py::test_issue940_enums_as_a_real_world_usecase",
"tests/unittest_scoped_nodes.py::test_metaclass_cannot_infer_call_yields_an_instance",
"tests/unittest_scoped_nodes.py::test_posonlyargs_python_38[\\ndef",
"tests/unittest_scoped_nodes.py::test_posonlyargs_default_value",
"tests/unittest_scoped_nodes.py::test_ancestor_with_generic",
"tests/unittest_inference.py::InferenceTest::test_descriptor_are_callable",
"tests/unittest_inference.py::InferenceTest::test_function_metaclasses",
"tests/unittest_inference.py::InferenceTest::test_inner_value_redefined_by_subclass_with_mro",
"tests/unittest_inference.py::InferenceTest::test_metaclass_arguments_are_classes_not_instances",
"tests/unittest_inference.py::InferenceTest::test_string_interpolation",
"tests/unittest_inference.py::TestInferencePropagation::test_call_context_propagation",
"tests/unittest_inference.py::test_recursion_error_self_reference_type_call"
] |
[
"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/commit/b985475c38d530b9736a850945dc718005bc3d4d",
"https://github.com/pylint-dev/astroid/commit/600039253d239b1801f891685fb52ca038252e14",
"https://github.com/pylint-dev/astroid/commit/eeed56ead5fe9294b38affc4494022c9c9fca216",
"https://github.com/pylint-dev/astroid/commit/2031639cbd59e117b4b7f1703bbd0d8f2856c3f8",
"https://github.com/pylint-dev/astroid/commit/681d1d6821198fdedeb4f318e3261d8a3fcde5af",
"https://github.com/pylint-dev/astroid/commit/ab41594a37290f1e06c737479101ae3563f078ac"
] | 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_module_from_name_2",
"tests/unittest_modutils.py::LoadModuleFromNameTest::test_raise_load_module_from_name_1",
"tests/unittest_modutils.py::GetModulePartTest::test_get_module_part_exception",
"tests/unittest_modutils.py::GetModulePartTest::test_knownValues_get_builtin_module_part",
"tests/unittest_modutils.py::GetModulePartTest::test_knownValues_get_compiled_module_part",
"tests/unittest_modutils.py::GetModulePartTest::test_knownValues_get_module_part_1",
"tests/unittest_modutils.py::GetModulePartTest::test_knownValues_get_module_part_2",
"tests/unittest_modutils.py::GetModulePartTest::test_knownValues_get_module_part_3",
"tests/unittest_modutils.py::ModPathFromFileTest::test_import_symlink_both_outside_of_path",
"tests/unittest_modutils.py::ModPathFromFileTest::test_import_symlink_with_source_outside_of_path",
"tests/unittest_modutils.py::ModPathFromFileTest::test_knownValues_modpath_from_file_1",
"tests/unittest_modutils.py::ModPathFromFileTest::test_load_from_module_symlink_on_symlinked_paths_in_syspath",
"tests/unittest_modutils.py::ModPathFromFileTest::test_raise_modpath_from_file_Exception",
"tests/unittest_modutils.py::LoadModuleFromPathTest::test_do_not_load_twice",
"tests/unittest_modutils.py::FileFromModPathTest::test_builtin",
"tests/unittest_modutils.py::FileFromModPathTest::test_site_packages",
"tests/unittest_modutils.py::FileFromModPathTest::test_std_lib",
"tests/unittest_modutils.py::FileFromModPathTest::test_unexisting",
"tests/unittest_modutils.py::FileFromModPathTest::test_unicode_in_package_init",
"tests/unittest_modutils.py::GetSourceFileTest::test",
"tests/unittest_modutils.py::GetSourceFileTest::test_raise",
"tests/unittest_modutils.py::StandardLibModuleTest::test_4",
"tests/unittest_modutils.py::StandardLibModuleTest::test_builtin",
"tests/unittest_modutils.py::StandardLibModuleTest::test_builtins",
"tests/unittest_modutils.py::StandardLibModuleTest::test_custom_path",
"tests/unittest_modutils.py::StandardLibModuleTest::test_datetime",
"tests/unittest_modutils.py::StandardLibModuleTest::test_failing_edge_cases",
"tests/unittest_modutils.py::StandardLibModuleTest::test_nonstandard",
"tests/unittest_modutils.py::StandardLibModuleTest::test_unknown",
"tests/unittest_modutils.py::IsRelativeTest::test_deep_relative",
"tests/unittest_modutils.py::IsRelativeTest::test_deep_relative2",
"tests/unittest_modutils.py::IsRelativeTest::test_deep_relative3",
"tests/unittest_modutils.py::IsRelativeTest::test_deep_relative4",
"tests/unittest_modutils.py::IsRelativeTest::test_is_relative_bad_path",
"tests/unittest_modutils.py::IsRelativeTest::test_knownValues_is_relative_1",
"tests/unittest_modutils.py::IsRelativeTest::test_knownValues_is_relative_3",
"tests/unittest_modutils.py::GetModuleFilesTest::test_get_all_files",
"tests/unittest_modutils.py::GetModuleFilesTest::test_get_module_files_1",
"tests/unittest_modutils.py::GetModuleFilesTest::test_load_module_set_attribute"
] |
[
"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/commit/96d0496b422b264506629d8c2c0c4ec4a8f18b1d"
] | 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.py::FromToLineNoTest::test_if_lineno",
"tests/unittest_builder.py::FromToLineNoTest::test_try_except_lineno",
"tests/unittest_builder.py::FromToLineNoTest::test_try_finally_25_lineno",
"tests/unittest_builder.py::FromToLineNoTest::test_try_finally_lineno",
"tests/unittest_builder.py::FromToLineNoTest::test_with_lineno",
"tests/unittest_builder.py::BuilderTest::test_asstuple",
"tests/unittest_builder.py::BuilderTest::test_augassign_attr",
"tests/unittest_builder.py::BuilderTest::test_build_constants",
"tests/unittest_builder.py::BuilderTest::test_data_build_invalid_x_escape",
"tests/unittest_builder.py::BuilderTest::test_data_build_null_bytes",
"tests/unittest_builder.py::BuilderTest::test_future_imports",
"tests/unittest_builder.py::BuilderTest::test_gen_expr_var_scope",
"tests/unittest_builder.py::BuilderTest::test_globals",
"tests/unittest_builder.py::BuilderTest::test_infer_can_assign_has_slots",
"tests/unittest_builder.py::BuilderTest::test_infer_can_assign_regular_object",
"tests/unittest_builder.py::BuilderTest::test_inferred_build",
"tests/unittest_builder.py::BuilderTest::test_inferred_dont_pollute",
"tests/unittest_builder.py::BuilderTest::test_inspect_build0",
"tests/unittest_builder.py::BuilderTest::test_inspect_build1",
"tests/unittest_builder.py::BuilderTest::test_inspect_build3",
"tests/unittest_builder.py::BuilderTest::test_inspect_build_type_object",
"tests/unittest_builder.py::BuilderTest::test_inspect_transform_module",
"tests/unittest_builder.py::BuilderTest::test_missing_file",
"tests/unittest_builder.py::BuilderTest::test_missing_newline",
"tests/unittest_builder.py::BuilderTest::test_newstyle_detection",
"tests/unittest_builder.py::BuilderTest::test_no_future_imports",
"tests/unittest_builder.py::BuilderTest::test_not_implemented",
"tests/unittest_builder.py::BuilderTest::test_object",
"tests/unittest_builder.py::BuilderTest::test_package_name",
"tests/unittest_builder.py::BuilderTest::test_socket_build",
"tests/unittest_builder.py::BuilderTest::test_two_future_imports",
"tests/unittest_builder.py::BuilderTest::test_yield_parent",
"tests/unittest_builder.py::FileBuildTest::test_class_base_props",
"tests/unittest_builder.py::FileBuildTest::test_class_basenames",
"tests/unittest_builder.py::FileBuildTest::test_class_instance_attrs",
"tests/unittest_builder.py::FileBuildTest::test_class_locals",
"tests/unittest_builder.py::FileBuildTest::test_function_base_props",
"tests/unittest_builder.py::FileBuildTest::test_function_locals",
"tests/unittest_builder.py::FileBuildTest::test_method_base_props",
"tests/unittest_builder.py::FileBuildTest::test_method_locals",
"tests/unittest_builder.py::FileBuildTest::test_module_base_props",
"tests/unittest_builder.py::FileBuildTest::test_module_locals",
"tests/unittest_builder.py::FileBuildTest::test_unknown_encoding",
"tests/unittest_builder.py::test_module_build_dunder_file",
"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/unittest_scoped_nodes.py::ModuleNodeTest::test_getattr",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_1",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_2",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_module_getattr",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_public_names",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name_beyond_top_level",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_special_attributes",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_stream_api",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_wildcard_import_names",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_argnames",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_decorator_builtin_descriptors",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_default_value",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dict_interface",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_classmethod",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_function",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_method",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args_keyword_only_args",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_four_args",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_func_instance_attr",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_igetattr",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract_decorated",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_generator",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_method",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_pytype",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_qname",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_method_init_subclass",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_navigation",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_annotation_is_not_the_last",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_nothing",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_special_attributes",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_type_builtin_descriptor_subclasses",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test__bases__attribute",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test__mro__attribute",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_add_metaclass",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_all_ancestors_need_slots",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_ancestors",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_frame_is_not_class",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_assignment_names_are_considered",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_callfunc_are_considered",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_same_name_considered",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_getattr",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_keywords",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_classmethod_attributes",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_1",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_2",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_dict_interface",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_duplicate_bases_namedtuple",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_extra_decorators_only_class_level_assignments",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_function_with_decorator_lineno",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_generator_from_infer_call_result_parent",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_from_grandpa",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_method_transform",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_has_dynamic_getattr",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass_lookup",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_inner_classes",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_attr_ancestors",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas_2",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr_with_class_attr",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_special_attributes",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_kite_graph",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_ancestors",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_invalid_mro",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_mro",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_error",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_inference_errors",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_using_same_class",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_type",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_yes_leak",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_methods",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_1",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_2",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_3",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_4",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_5",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_6",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_7",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_1",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_2",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_attribute_classes",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_factories",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_navigation",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop_with_redefine",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_nonregr_infer_callresult",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_added_dynamically_still_inferred",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_empty_list_of_slots",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_for_dict_keys",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_taken_from_parents",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_type",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_type_three_arguments",
"tests/unittest_scoped_nodes.py::test_metaclass_cannot_infer_call_yields_an_instance",
"tests/unittest_scoped_nodes.py::test_posonlyargs_python_38[\\ndef",
"tests/unittest_scoped_nodes.py::test_posonlyargs_default_value"
] |
[
"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/commit/d412afbc45864c60f02acdb6c19c8a2ecc2d1e80",
"https://github.com/pylint-dev/astroid/commit/103f440af6a9369297a95d3b75d3f14d8d9c9c3e",
"https://github.com/pylint-dev/astroid/commit/e600a8fb347d01d0c61f2e10fc1faeafb44eb714",
"https://github.com/pylint-dev/astroid/commit/5ead61396f464af71cb6be69e919bfd6baad47b5"
] | 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/unittest_scoped_nodes.py::ModuleNodeTest::test_getattr",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_1",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_2",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_module_getattr",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_public_names",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name_beyond_top_level",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_special_attributes",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_stream_api",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_wildcard_import_names",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_argnames",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_decorator_builtin_descriptors",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_default_value",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dict_interface",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_classmethod",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_function",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_method",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args_keyword_only_args",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_four_args",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_func_instance_attr",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_igetattr",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract_decorated",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_generator",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_method",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_pytype",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_qname",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_method_init_subclass",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_navigation",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_annotation_is_not_the_last",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_nothing",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_special_attributes",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_type_builtin_descriptor_subclasses",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test__bases__attribute",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test__mro__attribute",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_add_metaclass",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_all_ancestors_need_slots",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_ancestors",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_frame_is_not_class",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_assignment_names_are_considered",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_callfunc_are_considered",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_same_name_considered",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_getattr",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_keywords",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_classmethod_attributes",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_1",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_2",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_dict_interface",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_duplicate_bases_namedtuple",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_extra_decorators_only_class_level_assignments",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_function_with_decorator_lineno",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_generator_from_infer_call_result_parent",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_from_grandpa",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_method_transform",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_has_dynamic_getattr",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass_lookup",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_inner_classes",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_attr_ancestors",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas_2",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr_with_class_attr",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_special_attributes",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_kite_graph",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_ancestors",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_invalid_mro",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_mro",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_error",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_inference_errors",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_using_same_class",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_type",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_yes_leak",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_methods",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_1",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_2",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_3",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_4",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_5",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_6",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_7",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_1",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_2",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_attribute_classes",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_factories",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_navigation",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop_with_redefine",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_nonregr_infer_callresult",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_added_dynamically_still_inferred",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_empty_list_of_slots",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_for_dict_keys",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_taken_from_parents",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_type",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_type_three_arguments",
"tests/unittest_scoped_nodes.py::test_issue940_property_grandchild",
"tests/unittest_scoped_nodes.py::test_issue940_metaclass_property",
"tests/unittest_scoped_nodes.py::test_issue940_with_metaclass_class_context_property",
"tests/unittest_scoped_nodes.py::test_issue940_metaclass_values_funcdef",
"tests/unittest_scoped_nodes.py::test_issue940_metaclass_derived_funcdef",
"tests/unittest_scoped_nodes.py::test_issue940_metaclass_funcdef_is_not_datadescriptor",
"tests/unittest_scoped_nodes.py::test_metaclass_cannot_infer_call_yields_an_instance",
"tests/unittest_scoped_nodes.py::test_posonlyargs_python_38[\\ndef",
"tests/unittest_scoped_nodes.py::test_posonlyargs_default_value"
] |
[
"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/test_nodes.py::test_str_repr_no_warnings[AsyncFor]",
"tests/test_nodes.py::test_str_repr_no_warnings[AsyncFunctionDef]",
"tests/test_nodes.py::test_str_repr_no_warnings[Attribute]",
"tests/test_nodes.py::test_str_repr_no_warnings[AugAssign]",
"tests/test_nodes.py::test_str_repr_no_warnings[Await]",
"tests/test_nodes.py::test_str_repr_no_warnings[BinOp]",
"tests/test_nodes.py::test_str_repr_no_warnings[Call]",
"tests/test_nodes.py::test_str_repr_no_warnings[Compare]",
"tests/test_nodes.py::test_str_repr_no_warnings[Comprehension]",
"tests/test_nodes.py::test_str_repr_no_warnings[Decorators]",
"tests/test_nodes.py::test_str_repr_no_warnings[DelAttr]",
"tests/test_nodes.py::test_str_repr_no_warnings[DictComp]",
"tests/test_nodes.py::test_str_repr_no_warnings[ExceptHandler]",
"tests/test_nodes.py::test_str_repr_no_warnings[Expr]",
"tests/test_nodes.py::test_str_repr_no_warnings[For]",
"tests/test_nodes.py::test_str_repr_no_warnings[FormattedValue]",
"tests/test_nodes.py::test_str_repr_no_warnings[FunctionDef]",
"tests/test_nodes.py::test_str_repr_no_warnings[GeneratorExp]",
"tests/test_nodes.py::test_str_repr_no_warnings[If]",
"tests/test_nodes.py::test_str_repr_no_warnings[IfExp]",
"tests/test_nodes.py::test_str_repr_no_warnings[Keyword]",
"tests/test_nodes.py::test_str_repr_no_warnings[Lambda]",
"tests/test_nodes.py::test_str_repr_no_warnings[ListComp]",
"tests/test_nodes.py::test_str_repr_no_warnings[Match]",
"tests/test_nodes.py::test_str_repr_no_warnings[MatchAs]",
"tests/test_nodes.py::test_str_repr_no_warnings[MatchCase]",
"tests/test_nodes.py::test_str_repr_no_warnings[MatchClass]",
"tests/test_nodes.py::test_str_repr_no_warnings[MatchMapping]",
"tests/test_nodes.py::test_str_repr_no_warnings[MatchOr]",
"tests/test_nodes.py::test_str_repr_no_warnings[MatchSequence]",
"tests/test_nodes.py::test_str_repr_no_warnings[MatchStar]",
"tests/test_nodes.py::test_str_repr_no_warnings[MatchValue]",
"tests/test_nodes.py::test_str_repr_no_warnings[Module]",
"tests/test_nodes.py::test_str_repr_no_warnings[NamedExpr]",
"tests/test_nodes.py::test_str_repr_no_warnings[Raise]",
"tests/test_nodes.py::test_str_repr_no_warnings[Return]",
"tests/test_nodes.py::test_str_repr_no_warnings[SetComp]",
"tests/test_nodes.py::test_str_repr_no_warnings[Slice]",
"tests/test_nodes.py::test_str_repr_no_warnings[Starred]",
"tests/test_nodes.py::test_str_repr_no_warnings[Subscript]",
"tests/test_nodes.py::test_str_repr_no_warnings[TryExcept]",
"tests/test_nodes.py::test_str_repr_no_warnings[UnaryOp]",
"tests/test_nodes.py::test_str_repr_no_warnings[While]",
"tests/test_nodes.py::test_str_repr_no_warnings[Yield]",
"tests/test_nodes.py::test_str_repr_no_warnings[YieldFrom]"
] |
[
"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_as_string_unknown",
"tests/test_nodes.py::AsStringTest::test_class_def",
"tests/test_nodes.py::AsStringTest::test_ellipsis",
"tests/test_nodes.py::AsStringTest::test_f_strings",
"tests/test_nodes.py::AsStringTest::test_frozenset_as_string",
"tests/test_nodes.py::AsStringTest::test_func_signature_issue_185",
"tests/test_nodes.py::AsStringTest::test_int_attribute",
"tests/test_nodes.py::AsStringTest::test_module2_as_string",
"tests/test_nodes.py::AsStringTest::test_module_as_string",
"tests/test_nodes.py::AsStringTest::test_operator_precedence",
"tests/test_nodes.py::AsStringTest::test_slice_and_subscripts",
"tests/test_nodes.py::AsStringTest::test_slices",
"tests/test_nodes.py::AsStringTest::test_tuple_as_string",
"tests/test_nodes.py::AsStringTest::test_varargs_kwargs_as_string",
"tests/test_nodes.py::IfNodeTest::test_block_range",
"tests/test_nodes.py::IfNodeTest::test_if_elif_else_node",
"tests/test_nodes.py::TryExceptNodeTest::test_block_range",
"tests/test_nodes.py::TryFinallyNodeTest::test_block_range",
"tests/test_nodes.py::TryExceptFinallyNodeTest::test_block_range",
"tests/test_nodes.py::ImportNodeTest::test_absolute_import",
"tests/test_nodes.py::ImportNodeTest::test_as_string",
"tests/test_nodes.py::ImportNodeTest::test_bad_import_inference",
"tests/test_nodes.py::ImportNodeTest::test_conditional",
"tests/test_nodes.py::ImportNodeTest::test_conditional_import",
"tests/test_nodes.py::ImportNodeTest::test_from_self_resolve",
"tests/test_nodes.py::ImportNodeTest::test_import_self_resolve",
"tests/test_nodes.py::ImportNodeTest::test_more_absolute_import",
"tests/test_nodes.py::ImportNodeTest::test_real_name",
"tests/test_nodes.py::CmpNodeTest::test_as_string",
"tests/test_nodes.py::ConstNodeTest::test_bool",
"tests/test_nodes.py::ConstNodeTest::test_complex",
"tests/test_nodes.py::ConstNodeTest::test_copy",
"tests/test_nodes.py::ConstNodeTest::test_float",
"tests/test_nodes.py::ConstNodeTest::test_int",
"tests/test_nodes.py::ConstNodeTest::test_none",
"tests/test_nodes.py::ConstNodeTest::test_str",
"tests/test_nodes.py::ConstNodeTest::test_str_kind",
"tests/test_nodes.py::ConstNodeTest::test_unicode",
"tests/test_nodes.py::NameNodeTest::test_assign_to_true",
"tests/test_nodes.py::TestNamedExprNode::test_frame",
"tests/test_nodes.py::TestNamedExprNode::test_scope",
"tests/test_nodes.py::AnnAssignNodeTest::test_as_string",
"tests/test_nodes.py::AnnAssignNodeTest::test_complex",
"tests/test_nodes.py::AnnAssignNodeTest::test_primitive",
"tests/test_nodes.py::AnnAssignNodeTest::test_primitive_without_initial_value",
"tests/test_nodes.py::ArgumentsNodeTC::test_kwoargs",
"tests/test_nodes.py::ArgumentsNodeTC::test_linenumbering",
"tests/test_nodes.py::ArgumentsNodeTC::test_positional_only",
"tests/test_nodes.py::UnboundMethodNodeTest::test_no_super_getattr",
"tests/test_nodes.py::BoundMethodNodeTest::test_is_property",
"tests/test_nodes.py::AliasesTest::test_aliases",
"tests/test_nodes.py::Python35AsyncTest::test_async_await_keywords",
"tests/test_nodes.py::Python35AsyncTest::test_asyncfor_as_string",
"tests/test_nodes.py::Python35AsyncTest::test_asyncwith_as_string",
"tests/test_nodes.py::Python35AsyncTest::test_await_as_string",
"tests/test_nodes.py::Python35AsyncTest::test_decorated_async_def_as_string",
"tests/test_nodes.py::ContextTest::test_list_del",
"tests/test_nodes.py::ContextTest::test_list_load",
"tests/test_nodes.py::ContextTest::test_list_store",
"tests/test_nodes.py::ContextTest::test_starred_load",
"tests/test_nodes.py::ContextTest::test_starred_store",
"tests/test_nodes.py::ContextTest::test_subscript_del",
"tests/test_nodes.py::ContextTest::test_subscript_load",
"tests/test_nodes.py::ContextTest::test_subscript_store",
"tests/test_nodes.py::ContextTest::test_tuple_load",
"tests/test_nodes.py::ContextTest::test_tuple_store",
"tests/test_nodes.py::test_unknown",
"tests/test_nodes.py::test_type_comments_with",
"tests/test_nodes.py::test_type_comments_for",
"tests/test_nodes.py::test_type_coments_assign",
"tests/test_nodes.py::test_type_comments_invalid_expression",
"tests/test_nodes.py::test_type_comments_invalid_function_comments",
"tests/test_nodes.py::test_type_comments_function",
"tests/test_nodes.py::test_type_comments_arguments",
"tests/test_nodes.py::test_type_comments_posonly_arguments",
"tests/test_nodes.py::test_correct_function_type_comment_parent",
"tests/test_nodes.py::test_is_generator_for_yield_assignments",
"tests/test_nodes.py::test_f_string_correct_line_numbering",
"tests/test_nodes.py::test_assignment_expression",
"tests/test_nodes.py::test_assignment_expression_in_functiondef",
"tests/test_nodes.py::test_get_doc",
"tests/test_nodes.py::test_parse_fstring_debug_mode",
"tests/test_nodes.py::test_parse_type_comments_with_proper_parent",
"tests/test_nodes.py::test_const_itered",
"tests/test_nodes.py::test_is_generator_for_yield_in_while",
"tests/test_nodes.py::test_is_generator_for_yield_in_if",
"tests/test_nodes.py::test_is_generator_for_yield_in_aug_assign",
"tests/test_nodes.py::test_str_repr_no_warnings[AssignName]",
"tests/test_nodes.py::test_str_repr_no_warnings[AsyncWith]",
"tests/test_nodes.py::test_str_repr_no_warnings[BoolOp]",
"tests/test_nodes.py::test_str_repr_no_warnings[Break]",
"tests/test_nodes.py::test_str_repr_no_warnings[ClassDef]",
"tests/test_nodes.py::test_str_repr_no_warnings[ComprehensionScope]",
"tests/test_nodes.py::test_str_repr_no_warnings[Const]",
"tests/test_nodes.py::test_str_repr_no_warnings[Continue]",
"tests/test_nodes.py::test_str_repr_no_warnings[Delete]",
"tests/test_nodes.py::test_str_repr_no_warnings[DelName]",
"tests/test_nodes.py::test_str_repr_no_warnings[Dict]",
"tests/test_nodes.py::test_str_repr_no_warnings[DictUnpack]",
"tests/test_nodes.py::test_str_repr_no_warnings[EmptyNode]",
"tests/test_nodes.py::test_str_repr_no_warnings[EvaluatedObject]",
"tests/test_nodes.py::test_str_repr_no_warnings[Global]",
"tests/test_nodes.py::test_str_repr_no_warnings[Import]",
"tests/test_nodes.py::test_str_repr_no_warnings[ImportFrom]",
"tests/test_nodes.py::test_str_repr_no_warnings[JoinedStr]",
"tests/test_nodes.py::test_str_repr_no_warnings[List]",
"tests/test_nodes.py::test_str_repr_no_warnings[LocalsDictNodeNG]",
"tests/test_nodes.py::test_str_repr_no_warnings[MatchSingleton]",
"tests/test_nodes.py::test_str_repr_no_warnings[Name]",
"tests/test_nodes.py::test_str_repr_no_warnings[Nonlocal]",
"tests/test_nodes.py::test_str_repr_no_warnings[Pass]",
"tests/test_nodes.py::test_str_repr_no_warnings[Pattern]",
"tests/test_nodes.py::test_str_repr_no_warnings[Set]",
"tests/test_nodes.py::test_str_repr_no_warnings[TryFinally]",
"tests/test_nodes.py::test_str_repr_no_warnings[TryStar]",
"tests/test_nodes.py::test_str_repr_no_warnings[Tuple]",
"tests/test_nodes.py::test_str_repr_no_warnings[Unknown]",
"tests/test_nodes.py::test_str_repr_no_warnings[With]"
] |
[
"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/commit/bc908f29e17f462c03f9011d366af8002e003528",
"https://github.com/pylint-dev/astroid/commit/06a5f2b493caac07ed063e00d8970c878761b4e8"
] | 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::InferenceTest::test_advanced_tupleassign_name_inference2",
"tests/test_inference.py::InferenceTest::test_ancestors_inference",
"tests/test_inference.py::InferenceTest::test_ancestors_inference2",
"tests/test_inference.py::InferenceTest::test_arg_keyword_no_default_value",
"tests/test_inference.py::InferenceTest::test_args_default_inference1",
"tests/test_inference.py::InferenceTest::test_args_default_inference2",
"tests/test_inference.py::InferenceTest::test_aug_different_types_aug_not_implemented",
"tests/test_inference.py::InferenceTest::test_aug_different_types_aug_not_implemented_rop_fallback",
"tests/test_inference.py::InferenceTest::test_aug_different_types_augop_implemented",
"tests/test_inference.py::InferenceTest::test_aug_different_types_no_method_implemented",
"tests/test_inference.py::InferenceTest::test_aug_op_same_type_aug_implemented",
"tests/test_inference.py::InferenceTest::test_aug_op_same_type_aug_not_implemented_normal_implemented",
"tests/test_inference.py::InferenceTest::test_aug_op_same_type_not_implemented",
"tests/test_inference.py::InferenceTest::test_aug_op_subtype_aug_op_is_implemented",
"tests/test_inference.py::InferenceTest::test_aug_op_subtype_both_not_implemented",
"tests/test_inference.py::InferenceTest::test_aug_op_subtype_normal_op_is_implemented",
"tests/test_inference.py::InferenceTest::test_augassign",
"tests/test_inference.py::InferenceTest::test_augop_supertypes_augop_implemented",
"tests/test_inference.py::InferenceTest::test_augop_supertypes_none_implemented",
"tests/test_inference.py::InferenceTest::test_augop_supertypes_normal_binop_implemented",
"tests/test_inference.py::InferenceTest::test_augop_supertypes_not_implemented_returned_for_all",
"tests/test_inference.py::InferenceTest::test_augop_supertypes_reflected_binop_implemented",
"tests/test_inference.py::InferenceTest::test_bin_op_classes",
"tests/test_inference.py::InferenceTest::test_bin_op_supertype_more_complicated_example",
"tests/test_inference.py::InferenceTest::test_binary_op_custom_class",
"tests/test_inference.py::InferenceTest::test_binary_op_float_div",
"tests/test_inference.py::InferenceTest::test_binary_op_int_add",
"tests/test_inference.py::InferenceTest::test_binary_op_int_bitand",
"tests/test_inference.py::InferenceTest::test_binary_op_int_bitor",
"tests/test_inference.py::InferenceTest::test_binary_op_int_bitxor",
"tests/test_inference.py::InferenceTest::test_binary_op_int_shiftleft",
"tests/test_inference.py::InferenceTest::test_binary_op_int_shiftright",
"tests/test_inference.py::InferenceTest::test_binary_op_int_sub",
"tests/test_inference.py::InferenceTest::test_binary_op_list_mul",
"tests/test_inference.py::InferenceTest::test_binary_op_list_mul_int",
"tests/test_inference.py::InferenceTest::test_binary_op_list_mul_none",
"tests/test_inference.py::InferenceTest::test_binary_op_not_used_in_boolean_context",
"tests/test_inference.py::InferenceTest::test_binary_op_on_self",
"tests/test_inference.py::InferenceTest::test_binary_op_or_union_type",
"tests/test_inference.py::InferenceTest::test_binary_op_other_type",
"tests/test_inference.py::InferenceTest::test_binary_op_other_type_using_reflected_operands",
"tests/test_inference.py::InferenceTest::test_binary_op_reflected_and_not_implemented_is_type_error",
"tests/test_inference.py::InferenceTest::test_binary_op_str_mul",
"tests/test_inference.py::InferenceTest::test_binary_op_tuple_add",
"tests/test_inference.py::InferenceTest::test_binary_op_type_errors",
"tests/test_inference.py::InferenceTest::test_binop_ambiguity",
"tests/test_inference.py::InferenceTest::test_binop_different_types_no_method_implemented",
"tests/test_inference.py::InferenceTest::test_binop_different_types_normal_not_implemented_and_reflected",
"tests/test_inference.py::InferenceTest::test_binop_different_types_reflected_and_normal_not_implemented",
"tests/test_inference.py::InferenceTest::test_binop_different_types_reflected_only",
"tests/test_inference.py::InferenceTest::test_binop_different_types_unknown_bases",
"tests/test_inference.py::InferenceTest::test_binop_inference_errors",
"tests/test_inference.py::InferenceTest::test_binop_list_with_elts",
"tests/test_inference.py::InferenceTest::test_binop_same_types",
"tests/test_inference.py::InferenceTest::test_binop_self_in_list",
"tests/test_inference.py::InferenceTest::test_binop_subtype",
"tests/test_inference.py::InferenceTest::test_binop_subtype_implemented_in_parent",
"tests/test_inference.py::InferenceTest::test_binop_subtype_not_implemented",
"tests/test_inference.py::InferenceTest::test_binop_supertype",
"tests/test_inference.py::InferenceTest::test_binop_supertype_both_not_implemented",
"tests/test_inference.py::InferenceTest::test_binop_supertype_rop_not_implemented",
"tests/test_inference.py::InferenceTest::test_bool_value",
"tests/test_inference.py::InferenceTest::test_bool_value_instances",
"tests/test_inference.py::InferenceTest::test_bool_value_recursive",
"tests/test_inference.py::InferenceTest::test_bool_value_variable",
"tests/test_inference.py::InferenceTest::test_bound_method_inference",
"tests/test_inference.py::InferenceTest::test_bt_ancestor_crash",
"tests/test_inference.py::InferenceTest::test_builtin_help",
"tests/test_inference.py::InferenceTest::test_builtin_inference_py3k",
"tests/test_inference.py::InferenceTest::test_builtin_name_inference",
"tests/test_inference.py::InferenceTest::test_builtin_new",
"tests/test_inference.py::InferenceTest::test_builtin_open",
"tests/test_inference.py::InferenceTest::test_builtin_types",
"tests/test_inference.py::InferenceTest::test_bytes_subscript",
"tests/test_inference.py::InferenceTest::test_callfunc_context_func",
"tests/test_inference.py::InferenceTest::test_callfunc_context_lambda",
"tests/test_inference.py::InferenceTest::test_callfunc_inference",
"tests/test_inference.py::InferenceTest::test_class_inference",
"tests/test_inference.py::InferenceTest::test_classmethod_inferred_by_context",
"tests/test_inference.py::InferenceTest::test_context_call_for_context_managers",
"tests/test_inference.py::InferenceTest::test_conversion_of_dict_methods",
"tests/test_inference.py::InferenceTest::test_copy_method_inference",
"tests/test_inference.py::InferenceTest::test_del1",
"tests/test_inference.py::InferenceTest::test_del2",
"tests/test_inference.py::InferenceTest::test_delayed_attributes_without_slots",
"tests/test_inference.py::InferenceTest::test_dict_inference",
"tests/test_inference.py::InferenceTest::test_dict_inference_for_multiple_starred",
"tests/test_inference.py::InferenceTest::test_dict_inference_kwargs",
"tests/test_inference.py::InferenceTest::test_dict_inference_unpack_repeated_key",
"tests/test_inference.py::InferenceTest::test_dict_invalid_args",
"tests/test_inference.py::InferenceTest::test_do_import_module_performance",
"tests/test_inference.py::InferenceTest::test_exc_ancestors",
"tests/test_inference.py::InferenceTest::test_except_inference",
"tests/test_inference.py::InferenceTest::test_f_arg_f",
"tests/test_inference.py::InferenceTest::test_factory_method",
"tests/test_inference.py::InferenceTest::test_factory_methods_cls_call",
"tests/test_inference.py::InferenceTest::test_factory_methods_object_new_call",
"tests/test_inference.py::InferenceTest::test_float_complex_ambiguity",
"tests/test_inference.py::InferenceTest::test_for_dict",
"tests/test_inference.py::InferenceTest::test_frozenset_builtin_inference",
"tests/test_inference.py::InferenceTest::test_function_inference",
"tests/test_inference.py::InferenceTest::test_genexpr_bool_value",
"tests/test_inference.py::InferenceTest::test_getattr_inference1",
"tests/test_inference.py::InferenceTest::test_getattr_inference2",
"tests/test_inference.py::InferenceTest::test_getattr_inference3",
"tests/test_inference.py::InferenceTest::test_getattr_inference4",
"tests/test_inference.py::InferenceTest::test_getitem_of_class_raised_type_error",
"tests/test_inference.py::InferenceTest::test_im_func_unwrap",
"tests/test_inference.py::InferenceTest::test_import_as",
"tests/test_inference.py::InferenceTest::test_infer_abstract_property_return_values",
"tests/test_inference.py::InferenceTest::test_infer_arg_called_object_when_used_as_index_is_uninferable",
"tests/test_inference.py::InferenceTest::test_infer_arg_called_type_defined_in_outer_scope_is_uninferable",
"tests/test_inference.py::InferenceTest::test_infer_arg_called_type_is_uninferable",
"tests/test_inference.py::InferenceTest::test_infer_arg_called_type_when_used_as_index_is_uninferable",
"tests/test_inference.py::InferenceTest::test_infer_arg_called_type_when_used_as_subscript_is_uninferable",
"tests/test_inference.py::InferenceTest::test_infer_arguments",
"tests/test_inference.py::InferenceTest::test_infer_call_result_crash",
"tests/test_inference.py::InferenceTest::test_infer_call_result_invalid_dunder_call_on_instance",
"tests/test_inference.py::InferenceTest::test_infer_call_result_with_metaclass",
"tests/test_inference.py::InferenceTest::test_infer_cls_in_class_methods",
"tests/test_inference.py::InferenceTest::test_infer_coercion_rules_for_floats_complex",
"tests/test_inference.py::InferenceTest::test_infer_empty_nodes",
"tests/test_inference.py::InferenceTest::test_infer_function_under_if",
"tests/test_inference.py::InferenceTest::test_infer_method_empty_body",
"tests/test_inference.py::InferenceTest::test_infer_nested",
"tests/test_inference.py::InferenceTest::test_infer_subclass_attr_inner_class",
"tests/test_inference.py::InferenceTest::test_infer_subclass_attr_inner_class_works_indirectly",
"tests/test_inference.py::InferenceTest::test_infer_subclass_attr_instance_attr",
"tests/test_inference.py::InferenceTest::test_infer_subclass_attr_instance_attr_indirect",
"tests/test_inference.py::InferenceTest::test_infer_subclass_attr_outer_class",
"tests/test_inference.py::InferenceTest::test_infer_variable_arguments",
"tests/test_inference.py::InferenceTest::test_inference_restrictions",
"tests/test_inference.py::InferenceTest::test_inferring_context_manager_skip_index_error",
"tests/test_inference.py::InferenceTest::test_inferring_context_manager_unpacking_inference_error",
"tests/test_inference.py::InferenceTest::test_inferring_with_contextlib_contextmanager",
"tests/test_inference.py::InferenceTest::test_inferring_with_contextlib_contextmanager_failures",
"tests/test_inference.py::InferenceTest::test_inferring_with_statement",
"tests/test_inference.py::InferenceTest::test_inferring_with_statement_failures",
"tests/test_inference.py::InferenceTest::test_infinite_loop_for_decorators",
"tests/test_inference.py::InferenceTest::test_inner_value_redefined_by_subclass",
"tests/test_inference.py::InferenceTest::test_inner_value_redefined_by_subclass_with_mro",
"tests/test_inference.py::InferenceTest::test_instance_binary_operations",
"tests/test_inference.py::InferenceTest::test_instance_binary_operations_multiple_methods",
"tests/test_inference.py::InferenceTest::test_instance_binary_operations_parent",
"tests/test_inference.py::InferenceTest::test_instance_slicing",
"tests/test_inference.py::InferenceTest::test_instance_slicing_fails",
"tests/test_inference.py::InferenceTest::test_instance_slicing_slices",
"tests/test_inference.py::InferenceTest::test_invalid_slicing_primaries",
"tests/test_inference.py::InferenceTest::test_invalid_subscripts",
"tests/test_inference.py::InferenceTest::test_lambda_as_methods",
"tests/test_inference.py::InferenceTest::test_list_builtin_inference",
"tests/test_inference.py::InferenceTest::test_list_inference",
"tests/test_inference.py::InferenceTest::test_listassign_name_inference",
"tests/test_inference.py::InferenceTest::test_lookup_cond_branches",
"tests/test_inference.py::InferenceTest::test_matmul",
"tests/test_inference.py::InferenceTest::test_metaclass__getitem__",
"tests/test_inference.py::InferenceTest::test_metaclass_custom_dunder_call",
"tests/test_inference.py::InferenceTest::test_metaclass_custom_dunder_call_boundnode",
"tests/test_inference.py::InferenceTest::test_metaclass_subclasses_arguments_are_classes_not_instances",
"tests/test_inference.py::InferenceTest::test_metaclass_with_keyword_args",
"tests/test_inference.py::InferenceTest::test_method_argument",
"tests/test_inference.py::InferenceTest::test_module_inference",
"tests/test_inference.py::InferenceTest::test_mul_list_supports__index__",
"tests/test_inference.py::InferenceTest::test_mulassign_inference",
"tests/test_inference.py::InferenceTest::test_name_bool_value",
"tests/test_inference.py::InferenceTest::test_name_repeat_inference",
"tests/test_inference.py::InferenceTest::test_nested_contextmanager",
"tests/test_inference.py::InferenceTest::test_no_infinite_ancestor_loop",
"tests/test_inference.py::InferenceTest::test_no_runtime_error_in_repeat_inference",
"tests/test_inference.py::InferenceTest::test_nonregr_absolute_import",
"tests/test_inference.py::InferenceTest::test_nonregr_func_arg",
"tests/test_inference.py::InferenceTest::test_nonregr_func_global",
"tests/test_inference.py::InferenceTest::test_nonregr_getitem_empty_tuple",
"tests/test_inference.py::InferenceTest::test_nonregr_inference_modifying_col_offset",
"tests/test_inference.py::InferenceTest::test_nonregr_instance_attrs",
"tests/test_inference.py::InferenceTest::test_nonregr_lambda_arg",
"tests/test_inference.py::InferenceTest::test_nonregr_layed_dictunpack",
"tests/test_inference.py::InferenceTest::test_nonregr_multi_referential_addition",
"tests/test_inference.py::InferenceTest::test_pluggable_inference",
"tests/test_inference.py::InferenceTest::test_property",
"tests/test_inference.py::InferenceTest::test_python25_no_relative_import",
"tests/test_inference.py::InferenceTest::test_scope_lookup_same_attributes",
"tests/test_inference.py::InferenceTest::test_set_builtin_inference",
"tests/test_inference.py::InferenceTest::test_simple_for",
"tests/test_inference.py::InferenceTest::test_simple_for_genexpr",
"tests/test_inference.py::InferenceTest::test_simple_subscript",
"tests/test_inference.py::InferenceTest::test_simple_tuple",
"tests/test_inference.py::InferenceTest::test_slicing_list",
"tests/test_inference.py::InferenceTest::test_slicing_str",
"tests/test_inference.py::InferenceTest::test_slicing_tuple",
"tests/test_inference.py::InferenceTest::test_special_method_masquerading_as_another",
"tests/test_inference.py::InferenceTest::test_starred_in_list_literal",
"tests/test_inference.py::InferenceTest::test_starred_in_literals_inference_issues",
"tests/test_inference.py::InferenceTest::test_starred_in_mapping_inference_issues",
"tests/test_inference.py::InferenceTest::test_starred_in_mapping_literal",
"tests/test_inference.py::InferenceTest::test_starred_in_mapping_literal_no_inference_possible",
"tests/test_inference.py::InferenceTest::test_starred_in_mapping_literal_non_const_keys_values",
"tests/test_inference.py::InferenceTest::test_starred_in_set_literal",
"tests/test_inference.py::InferenceTest::test_starred_in_tuple_literal",
"tests/test_inference.py::InferenceTest::test_stop_iteration_leak",
"tests/test_inference.py::InferenceTest::test_str_methods",
"tests/test_inference.py::InferenceTest::test_string_interpolation",
"tests/test_inference.py::InferenceTest::test_subscript_inference_error",
"tests/test_inference.py::InferenceTest::test_subscript_multi_slice",
"tests/test_inference.py::InferenceTest::test_subscript_multi_value",
"tests/test_inference.py::InferenceTest::test_subscript_supports__index__",
"tests/test_inference.py::InferenceTest::test_swap_assign_inference",
"tests/test_inference.py::InferenceTest::test_tuple_builtin_inference",
"tests/test_inference.py::InferenceTest::test_tuple_then_list",
"tests/test_inference.py::InferenceTest::test_tupleassign_name_inference",
"tests/test_inference.py::InferenceTest::test_two_parents_from_same_module",
"tests/test_inference.py::InferenceTest::test_type__new__invalid_attrs",
"tests/test_inference.py::InferenceTest::test_type__new__invalid_bases",
"tests/test_inference.py::InferenceTest::test_type__new__invalid_mcs_argument",
"tests/test_inference.py::InferenceTest::test_type__new__invalid_name",
"tests/test_inference.py::InferenceTest::test_type__new__metaclass_and_ancestors_lookup",
"tests/test_inference.py::InferenceTest::test_type__new__metaclass_lookup",
"tests/test_inference.py::InferenceTest::test_type__new__not_enough_arguments",
"tests/test_inference.py::InferenceTest::test_type__new__with_metaclass",
"tests/test_inference.py::InferenceTest::test_unary_empty_type_errors",
"tests/test_inference.py::InferenceTest::test_unary_not",
"tests/test_inference.py::InferenceTest::test_unary_op_assignment",
"tests/test_inference.py::InferenceTest::test_unary_op_classes",
"tests/test_inference.py::InferenceTest::test_unary_op_instance_method_not_callable",
"tests/test_inference.py::InferenceTest::test_unary_op_leaks_stop_iteration",
"tests/test_inference.py::InferenceTest::test_unary_op_numbers",
"tests/test_inference.py::InferenceTest::test_unary_operands",
"tests/test_inference.py::InferenceTest::test_unary_type_errors",
"tests/test_inference.py::InferenceTest::test_unary_type_errors_for_non_instance_objects",
"tests/test_inference.py::InferenceTest::test_unbound_method_inference",
"tests/test_inference.py::InferenceTest::test_unicode_methods",
"tests/test_inference.py::InferenceTest::test_uninferable_type_subscript",
"tests/test_inference.py::GetattrTest::test_attribute_missing",
"tests/test_inference.py::GetattrTest::test_attrname_not_string",
"tests/test_inference.py::GetattrTest::test_default",
"tests/test_inference.py::GetattrTest::test_lambda",
"tests/test_inference.py::GetattrTest::test_lookup",
"tests/test_inference.py::GetattrTest::test_yes_when_unknown",
"tests/test_inference.py::HasattrTest::test_attribute_is_missing",
"tests/test_inference.py::HasattrTest::test_attribute_is_not_missing",
"tests/test_inference.py::HasattrTest::test_inference_errors",
"tests/test_inference.py::HasattrTest::test_lambda",
"tests/test_inference.py::BoolOpTest::test_bool_ops",
"tests/test_inference.py::BoolOpTest::test_other_nodes",
"tests/test_inference.py::BoolOpTest::test_yes_when_unknown",
"tests/test_inference.py::TestCallable::test_callable",
"tests/test_inference.py::TestCallable::test_callable_methods",
"tests/test_inference.py::TestCallable::test_inference_errors",
"tests/test_inference.py::TestCallable::test_not_callable",
"tests/test_inference.py::TestBool::test_bool",
"tests/test_inference.py::TestBool::test_bool_bool_special_method",
"tests/test_inference.py::TestBool::test_bool_instance_not_callable",
"tests/test_inference.py::TestBool::test_class_subscript",
"tests/test_inference.py::TestBool::test_class_subscript_inference_context",
"tests/test_inference.py::TestType::test_type",
"tests/test_inference.py::ArgumentsTest::test_args",
"tests/test_inference.py::ArgumentsTest::test_args_overwritten",
"tests/test_inference.py::ArgumentsTest::test_defaults",
"tests/test_inference.py::ArgumentsTest::test_fail_to_infer_args",
"tests/test_inference.py::ArgumentsTest::test_kwargs",
"tests/test_inference.py::ArgumentsTest::test_kwargs_access_by_name",
"tests/test_inference.py::ArgumentsTest::test_kwargs_and_other_named_parameters",
"tests/test_inference.py::ArgumentsTest::test_kwargs_are_overridden",
"tests/test_inference.py::ArgumentsTest::test_kwonly_args",
"tests/test_inference.py::ArgumentsTest::test_multiple_kwargs",
"tests/test_inference.py::ArgumentsTest::test_multiple_starred_args",
"tests/test_inference.py::SliceTest::test_slice",
"tests/test_inference.py::SliceTest::test_slice_attributes",
"tests/test_inference.py::SliceTest::test_slice_inference_error",
"tests/test_inference.py::SliceTest::test_slice_type",
"tests/test_inference.py::CallSiteTest::test_call_site",
"tests/test_inference.py::CallSiteTest::test_call_site_starred_args",
"tests/test_inference.py::CallSiteTest::test_call_site_uninferable",
"tests/test_inference.py::CallSiteTest::test_call_site_valid_arguments",
"tests/test_inference.py::CallSiteTest::test_duplicated_keyword_arguments",
"tests/test_inference.py::ObjectDunderNewTest::test_object_dunder_new_is_inferred_if_decorator",
"tests/test_inference.py::test_augassign_recursion",
"tests/test_inference.py::test_infer_custom_inherit_from_property",
"tests/test_inference.py::test_cannot_infer_call_result_for_builtin_methods",
"tests/test_inference.py::test_unpack_dicts_in_assignment",
"tests/test_inference.py::test_slice_inference_in_for_loops",
"tests/test_inference.py::test_slice_inference_in_for_loops_not_working",
"tests/test_inference.py::test_slice_zero_step_does_not_raise_ValueError",
"tests/test_inference.py::test_slice_zero_step_on_str_does_not_raise_ValueError",
"tests/test_inference.py::test_unpacking_starred_and_dicts_in_assignment",
"tests/test_inference.py::test_unpacking_starred_empty_list_in_assignment",
"tests/test_inference.py::test_regression_infinite_loop_decorator",
"tests/test_inference.py::test_stop_iteration_in_int",
"tests/test_inference.py::test_call_on_instance_with_inherited_dunder_call_method",
"tests/test_inference.py::TestInferencePropagation::test_call_starargs_propagation",
"tests/test_inference.py::TestInferencePropagation::test_call_kwargs_propagation",
"tests/test_inference.py::test_compare[<-False]",
"tests/test_inference.py::test_compare[<=-True]",
"tests/test_inference.py::test_compare[==-True]",
"tests/test_inference.py::test_compare[>=-True]",
"tests/test_inference.py::test_compare[>-False]",
"tests/test_inference.py::test_compare[!=-False]",
"tests/test_inference.py::test_compare_membership[in-True]",
"tests/test_inference.py::test_compare_membership[not",
"tests/test_inference.py::test_compare_lesseq_types[1-1-True]",
"tests/test_inference.py::test_compare_lesseq_types[1-1.1-True]",
"tests/test_inference.py::test_compare_lesseq_types[1.1-1-False]",
"tests/test_inference.py::test_compare_lesseq_types[1.0-1.0-True]",
"tests/test_inference.py::test_compare_lesseq_types[abc-def-True]",
"tests/test_inference.py::test_compare_lesseq_types[abc--False]",
"tests/test_inference.py::test_compare_lesseq_types[lhs6-rhs6-True]",
"tests/test_inference.py::test_compare_lesseq_types[lhs7-rhs7-True]",
"tests/test_inference.py::test_compare_lesseq_types[lhs8-rhs8-False]",
"tests/test_inference.py::test_compare_lesseq_types[True-True-True]",
"tests/test_inference.py::test_compare_lesseq_types[True-False-False]",
"tests/test_inference.py::test_compare_lesseq_types[False-1-True]",
"tests/test_inference.py::test_compare_lesseq_types[(1+0j)-(2+0j)-result12]",
"tests/test_inference.py::test_compare_lesseq_types[0.0--0.0-True]",
"tests/test_inference.py::test_compare_lesseq_types[0-1-result14]",
"tests/test_inference.py::test_compare_lesseq_types[\\x00-\\x01-True]",
"tests/test_inference.py::test_compare_chained",
"tests/test_inference.py::test_compare_inferred_members",
"tests/test_inference.py::test_compare_instance_members",
"tests/test_inference.py::test_compare_uninferable_member",
"tests/test_inference.py::test_compare_chained_comparisons_shortcircuit_on_false",
"tests/test_inference.py::test_compare_chained_comparisons_continue_on_true",
"tests/test_inference.py::test_compare_ifexp_constant",
"tests/test_inference.py::test_compare_typeerror",
"tests/test_inference.py::test_compare_multiple_possibilites",
"tests/test_inference.py::test_compare_ambiguous_multiple_possibilites",
"tests/test_inference.py::test_compare_nonliteral",
"tests/test_inference.py::test_compare_unknown",
"tests/test_inference.py::test_limit_inference_result_amount",
"tests/test_inference.py::test_attribute_inference_should_not_access_base_classes",
"tests/test_inference.py::test_attribute_mro_object_inference",
"tests/test_inference.py::test_inferred_sequence_unpacking_works",
"tests/test_inference.py::test_recursion_error_inferring_slice",
"tests/test_inference.py::test_exception_lookup_last_except_handler_wins",
"tests/test_inference.py::test_exception_lookup_name_bound_in_except_handler",
"tests/test_inference.py::test_builtin_inference_list_of_exceptions",
"tests/test_inference.py::test_cannot_getattr_ann_assigns",
"tests/test_inference.py::test_prevent_recursion_error_in_igetattr_and_context_manager_inference",
"tests/test_inference.py::test_igetattr_idempotent",
"tests/test_inference.py::test_cache_usage_without_explicit_context",
"tests/test_inference.py::test_infer_context_manager_with_unknown_args",
"tests/test_inference.py::test_subclass_of_exception[\\n",
"tests/test_inference.py::test_ifexp_inference",
"tests/test_inference.py::test_assert_last_function_returns_none_on_inference",
"tests/test_inference.py::test_posonlyargs_inference",
"tests/test_inference.py::test_infer_args_unpacking_of_self",
"tests/test_inference.py::test_infer_exception_instance_attributes",
"tests/test_inference.py::test_infer_assign_attr",
"tests/test_inference.py::test_inference_is_limited_to_the_boundnode[\\n",
"tests/test_inference.py::test_property_inference",
"tests/test_inference.py::test_property_as_string",
"tests/test_inference.py::test_property_callable_inference",
"tests/test_inference.py::test_property_docstring",
"tests/test_inference.py::test_recursion_error_inferring_builtin_containers",
"tests/test_inference.py::test_inferaugassign_picking_parent_instead_of_stmt",
"tests/test_inference.py::test_classmethod_from_builtins_inferred_as_bound",
"tests/test_inference.py::test_infer_dict_passes_context",
"tests/test_inference.py::test_custom_decorators_for_classmethod_and_staticmethods[\\n",
"tests/test_inference.py::test_dataclasses_subscript_inference_recursion_error_39",
"tests/test_inference.py::test_self_reference_infer_does_not_trigger_recursion_error",
"tests/test_inference.py::test_inferring_properties_multiple_time_does_not_mutate_locals",
"tests/test_inference.py::test_getattr_fails_on_empty_values",
"tests/test_inference.py::test_infer_first_argument_of_static_method_in_metaclass",
"tests/test_inference.py::test_recursion_error_metaclass_monkeypatching",
"tests/test_inference.py::test_allow_retrieving_instance_attrs_and_special_attrs_for_functions",
"tests/test_inference.py::test_implicit_parameters_bound_method",
"tests/test_inference.py::test_super_inference_of_abstract_property",
"tests/test_inference.py::test_infer_generated_setter",
"tests/test_inference.py::test_infer_list_of_uninferables_does_not_crash",
"tests/test_inference.py::test_issue926_infer_stmts_referencing_same_name_is_not_uninferable",
"tests/test_inference.py::test_issue926_binop_referencing_same_name_is_not_uninferable",
"tests/test_inference.py::test_pylint_issue_4692_attribute_inference_error_in_infer_import_from",
"tests/test_inference.py::test_issue_1090_infer_yield_type_base_class",
"tests/test_inference.py::test_namespace_package",
"tests/test_inference.py::test_namespace_package_same_name",
"tests/test_inference.py::test_relative_imports_init_package",
"tests/test_inference.py::test_inference_of_items_on_module_dict",
"tests/test_inference.py::test_imported_module_var_inferable",
"tests/test_inference.py::test_imported_module_var_inferable2",
"tests/test_inference.py::test_imported_module_var_inferable3",
"tests/test_inference.py::test_recursion_on_inference_tip",
"tests/test_inference.py::test_function_def_cached_generator",
"tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting[empty-indexes]",
"tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting[numbered-indexes]",
"tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting[empty-indexes-from-positional]",
"tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting[numbered-indexes-from-positionl]",
"tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting[named-indexes-from-keyword]",
"tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting[empty-indexes-on-variable]",
"tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting[empty-indexes-from-variable0]",
"tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting[empty-indexes-from-variable1]",
"tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting_uninferable[\\n",
"tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting_uninferable[\"I",
"tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting_uninferable[20",
"tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting_uninferable[(\"%\"",
"tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting_with_specs",
"tests/test_inference.py::test_sys_argv_uninferable",
"tests/test_inference.py::InferenceTest::test_descriptor_are_callable",
"tests/test_inference.py::InferenceTest::test_factory_methods_inside_binary_operation",
"tests/test_inference.py::InferenceTest::test_function_metaclasses",
"tests/test_inference.py::InferenceTest::test_metaclass_arguments_are_classes_not_instances",
"tests/test_inference.py::TestInferencePropagation::test_call_context_propagation",
"tests/test_inference.py::test_compare_identity[is-True]",
"tests/test_inference.py::test_compare_identity[is",
"tests/test_inference.py::test_compare_dynamic",
"tests/test_inference.py::test_compare_known_false_branch",
"tests/test_inference.py::test_recursion_error_self_reference_type_call"
] |
[
"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::TestModUtilsRelativePath::test_path_format_variations",
"tests/test_get_relative_base_path.py::TestModUtilsRelativePath::test_special_path_components",
"tests/test_get_relative_base_path.py::TestModUtilsRelativePath::test_symlink_resolution",
"tests/test_get_relative_base_path.py::TestModUtilsRelativePath::test_valid_subdirectories"
] |
[
"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[int,"
] |
[
"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::AsStringTest::test_class_def",
"tests/unittest_nodes.py::AsStringTest::test_ellipsis",
"tests/unittest_nodes.py::AsStringTest::test_f_strings",
"tests/unittest_nodes.py::AsStringTest::test_frozenset_as_string",
"tests/unittest_nodes.py::AsStringTest::test_func_signature_issue_185",
"tests/unittest_nodes.py::AsStringTest::test_int_attribute",
"tests/unittest_nodes.py::AsStringTest::test_module2_as_string",
"tests/unittest_nodes.py::AsStringTest::test_module_as_string",
"tests/unittest_nodes.py::AsStringTest::test_operator_precedence",
"tests/unittest_nodes.py::AsStringTest::test_slice_and_subscripts",
"tests/unittest_nodes.py::AsStringTest::test_slices",
"tests/unittest_nodes.py::AsStringTest::test_tuple_as_string",
"tests/unittest_nodes.py::AsStringTest::test_varargs_kwargs_as_string",
"tests/unittest_nodes.py::IfNodeTest::test_block_range",
"tests/unittest_nodes.py::IfNodeTest::test_if_elif_else_node",
"tests/unittest_nodes.py::IfNodeTest::test_if_sys_guard",
"tests/unittest_nodes.py::IfNodeTest::test_if_typing_guard",
"tests/unittest_nodes.py::TryExceptNodeTest::test_block_range",
"tests/unittest_nodes.py::TryFinallyNodeTest::test_block_range",
"tests/unittest_nodes.py::TryExceptFinallyNodeTest::test_block_range",
"tests/unittest_nodes.py::ImportNodeTest::test_absolute_import",
"tests/unittest_nodes.py::ImportNodeTest::test_as_string",
"tests/unittest_nodes.py::ImportNodeTest::test_bad_import_inference",
"tests/unittest_nodes.py::ImportNodeTest::test_conditional",
"tests/unittest_nodes.py::ImportNodeTest::test_conditional_import",
"tests/unittest_nodes.py::ImportNodeTest::test_from_self_resolve",
"tests/unittest_nodes.py::ImportNodeTest::test_import_self_resolve",
"tests/unittest_nodes.py::ImportNodeTest::test_more_absolute_import",
"tests/unittest_nodes.py::ImportNodeTest::test_real_name",
"tests/unittest_nodes.py::CmpNodeTest::test_as_string",
"tests/unittest_nodes.py::ConstNodeTest::test_bool",
"tests/unittest_nodes.py::ConstNodeTest::test_complex",
"tests/unittest_nodes.py::ConstNodeTest::test_copy",
"tests/unittest_nodes.py::ConstNodeTest::test_float",
"tests/unittest_nodes.py::ConstNodeTest::test_int",
"tests/unittest_nodes.py::ConstNodeTest::test_none",
"tests/unittest_nodes.py::ConstNodeTest::test_str",
"tests/unittest_nodes.py::ConstNodeTest::test_str_kind",
"tests/unittest_nodes.py::ConstNodeTest::test_unicode",
"tests/unittest_nodes.py::NameNodeTest::test_assign_to_true",
"tests/unittest_nodes.py::TestNamedExprNode::test_frame",
"tests/unittest_nodes.py::TestNamedExprNode::test_scope",
"tests/unittest_nodes.py::AnnAssignNodeTest::test_as_string",
"tests/unittest_nodes.py::AnnAssignNodeTest::test_complex",
"tests/unittest_nodes.py::AnnAssignNodeTest::test_primitive",
"tests/unittest_nodes.py::AnnAssignNodeTest::test_primitive_without_initial_value",
"tests/unittest_nodes.py::ArgumentsNodeTC::test_kwoargs",
"tests/unittest_nodes.py::ArgumentsNodeTC::test_positional_only",
"tests/unittest_nodes.py::UnboundMethodNodeTest::test_no_super_getattr",
"tests/unittest_nodes.py::BoundMethodNodeTest::test_is_property",
"tests/unittest_nodes.py::AliasesTest::test_aliases",
"tests/unittest_nodes.py::Python35AsyncTest::test_async_await_keywords",
"tests/unittest_nodes.py::Python35AsyncTest::test_asyncfor_as_string",
"tests/unittest_nodes.py::Python35AsyncTest::test_asyncwith_as_string",
"tests/unittest_nodes.py::Python35AsyncTest::test_await_as_string",
"tests/unittest_nodes.py::Python35AsyncTest::test_decorated_async_def_as_string",
"tests/unittest_nodes.py::ContextTest::test_list_del",
"tests/unittest_nodes.py::ContextTest::test_list_load",
"tests/unittest_nodes.py::ContextTest::test_list_store",
"tests/unittest_nodes.py::ContextTest::test_starred_load",
"tests/unittest_nodes.py::ContextTest::test_starred_store",
"tests/unittest_nodes.py::ContextTest::test_subscript_del",
"tests/unittest_nodes.py::ContextTest::test_subscript_load",
"tests/unittest_nodes.py::ContextTest::test_subscript_store",
"tests/unittest_nodes.py::ContextTest::test_tuple_load",
"tests/unittest_nodes.py::ContextTest::test_tuple_store",
"tests/unittest_nodes.py::test_unknown",
"tests/unittest_nodes.py::test_type_comments_with",
"tests/unittest_nodes.py::test_type_comments_for",
"tests/unittest_nodes.py::test_type_coments_assign",
"tests/unittest_nodes.py::test_type_comments_invalid_expression",
"tests/unittest_nodes.py::test_type_comments_invalid_function_comments",
"tests/unittest_nodes.py::test_type_comments_function",
"tests/unittest_nodes.py::test_type_comments_arguments",
"tests/unittest_nodes.py::test_type_comments_posonly_arguments",
"tests/unittest_nodes.py::test_correct_function_type_comment_parent",
"tests/unittest_nodes.py::test_is_generator_for_yield_assignments",
"tests/unittest_nodes.py::test_f_string_correct_line_numbering",
"tests/unittest_nodes.py::test_assignment_expression",
"tests/unittest_nodes.py::test_assignment_expression_in_functiondef",
"tests/unittest_nodes.py::test_get_doc",
"tests/unittest_nodes.py::test_parse_fstring_debug_mode",
"tests/unittest_nodes.py::test_parse_type_comments_with_proper_parent",
"tests/unittest_nodes.py::test_const_itered",
"tests/unittest_nodes.py::test_is_generator_for_yield_in_while",
"tests/unittest_nodes.py::test_is_generator_for_yield_in_if",
"tests/unittest_nodes.py::test_is_generator_for_yield_in_aug_assign"
] |
[
"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
- 1