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://github.com/pylint-dev/astroid/commit/1f04c7ce746c83feab077e0462e058fbbb2253fe",
"https://github.com/pylint-dev/astroid/commit/650e1ab916ac48cfc1fb3d42fd0df94f9845b508",
"https://github.com/pylint-dev/astroid/commit/58e2a5c9de317ef852f7657986d04d69a3afb701",
"https://github.com/pylint-dev/astroid/commit/89c629a806effa517783bb53e86db700cb1df81c",
"https://github.com/pylint-dev/astroid/commit/99a0b4af9aaa53541fcd33b40fb2463b022550b0",
"https://github.com/pylint-dev/astroid/commit/a65b5eb4599d84595d4836e20bdde79a52b371e6"
] | 2022-06-07T10:37:43
|
pylint-dev__astroid-1602
|
[
"104"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index 7db3e6c682..4cc346a478 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -22,6 +22,10 @@ Release date: TBA
Closes PyCQA/pylint#3518
+* Calls to ``str.format`` are now correctly inferred.
+
+ Closes #104
+
* Adds missing enums from ``ssl`` module.
Closes PyCQA/pylint#3691
diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py
index 711444c5df..68445e731c 100644
--- a/astroid/brain/brain_builtin_inference.py
+++ b/astroid/brain/brain_builtin_inference.py
@@ -911,6 +911,48 @@ def _infer_copy_method(
raise UseInferenceDefault()
+def _is_str_format_call(node: nodes.Call) -> bool:
+ """Catch calls to str.format()."""
+ return (
+ isinstance(node.func, nodes.Attribute)
+ and node.func.attrname == "format"
+ and isinstance(node.func.expr, nodes.Const)
+ and isinstance(node.func.expr.value, str)
+ )
+
+
+def _infer_str_format_call(
+ node: nodes.Call, context: InferenceContext | None = None
+) -> Iterator[nodes.Const | type[util.Uninferable]]:
+ """Return a Const node based on the template and passed arguments."""
+ call = arguments.CallSite.from_call(node, context=context)
+ format_template: str = node.func.expr.value
+
+ # Get the positional arguments passed
+ inferred_positional = [
+ helpers.safe_infer(i, context) for i in call.positional_arguments
+ ]
+ if not all(isinstance(i, nodes.Const) for i in inferred_positional):
+ return iter([util.Uninferable])
+ pos_values: list[str] = [i.value for i in inferred_positional]
+
+ # Get the keyword arguments passed
+ inferred_keyword = {
+ k: helpers.safe_infer(v, context) for k, v in call.keyword_arguments.items()
+ }
+ if not all(isinstance(i, nodes.Const) for i in inferred_keyword.values()):
+ return iter([util.Uninferable])
+ keyword_values: dict[str, str] = {k: v.value for k, v in inferred_keyword.items()}
+
+ try:
+ formatted_string = format_template.format(*pos_values, **keyword_values)
+ except IndexError:
+ # If there is an IndexError there are too few arguments to interpolate
+ return iter([util.Uninferable])
+
+ return iter([nodes.const_factory(formatted_string)])
+
+
# Builtins inference
register_builtin_transform(infer_bool, "bool")
register_builtin_transform(infer_super, "super")
@@ -946,3 +988,7 @@ def _infer_copy_method(
lambda node: isinstance(node.func, nodes.Attribute)
and node.func.attrname == "copy",
)
+
+AstroidManager().register_transform(
+ nodes.Call, inference_tip(_infer_str_format_call), _is_str_format_call
+)
|
String formatting is inferred as empty string
Originally reported by: **Florian Bruhin (BitBucket: [The-Compiler](http://bitbucket.org/The-Compiler), GitHub: @The-Compiler?)**
---
With this code:
``` py
def foo(arg):
pass
foo('foo{}bar'.format(42))
foo('const')
```
The first call is inferred as an empty string.
I can reproduce this with pylint/astroid from tip and this pylint plugin:
``` py
import astroid
from pylint import interfaces, checkers
from pylint.checkers import utils
class TestChecker(checkers.BaseChecker):
__implements__ = interfaces.IAstroidChecker
name = 'foo'
msgs = {
'E0000': ('Got called with empty string!', 'empty-string', None),
}
priority = -1
@utils.check_messages('bad-config-call')
def visit_callfunc(self, node):
if not hasattr(node, 'func'):
return
infer = utils.safe_infer(node.func)
if infer is None or infer.name != 'foo':
return
try:
arg = utils.get_argument_from_call(node, position=0)
except utils.NoSuchArgumentError:
return
arg = utils.safe_infer(arg)
if not isinstance(arg, astroid.Const):
return
if arg.value == '':
self.add_message('empty-string', node=node)
def register(linter):
linter.register_checker(TestChecker(linter))
```
output:
```
$ PYTHONPATH=$PWD ./venv/bin/pylint foo.py --load-plugins=plugin
No config file found, using default configuration
************* Module foo
[...]
E: 4, 3: Got called with empty string! (empty-string)
[...]
```
Assigning to PCManticore as discussed in IRC.
---
- Bitbucket: https://bitbucket.org/logilab/astroid/issue/104
|
1602
|
pylint-dev/astroid
|
diff --git a/tests/unittest_brain_builtin.py b/tests/unittest_brain_builtin.py
index 0d7493034a..a659c4fdf2 100644
--- a/tests/unittest_brain_builtin.py
+++ b/tests/unittest_brain_builtin.py
@@ -6,12 +6,15 @@
import unittest
-from astroid import extract_node, objects
+import pytest
+
+from astroid import nodes, objects, util
+from astroid.builder import _extract_single_node
class BuiltinsTest(unittest.TestCase):
def test_infer_property(self):
- class_with_property = extract_node(
+ class_with_property = _extract_single_node(
"""
class Something:
def getter():
@@ -22,3 +25,85 @@ def getter():
inferred_property = list(class_with_property.value.infer())[0]
self.assertTrue(isinstance(inferred_property, objects.Property))
self.assertTrue(hasattr(inferred_property, "args"))
+
+
+class TestStringNodes:
+ @pytest.mark.parametrize(
+ "format_string",
+ [
+ pytest.param(
+ """"My name is {}, I'm {}".format("Daniel", 12)""", id="empty-indexes"
+ ),
+ pytest.param(
+ """"My name is {0}, I'm {1}".format("Daniel", 12)""",
+ id="numbered-indexes",
+ ),
+ pytest.param(
+ """"My name is {fname}, I'm {age}".format(fname = "Daniel", age = 12)""",
+ id="named-indexes",
+ ),
+ pytest.param(
+ """
+ name = "Daniel"
+ age = 12
+ "My name is {0}, I'm {1}".format(name, age)
+ """,
+ id="numbered-indexes-from-positional",
+ ),
+ pytest.param(
+ """
+ name = "Daniel"
+ age = 12
+ "My name is {fname}, I'm {age}".format(fname = name, age = age)
+ """,
+ id="named-indexes-from-keyword",
+ ),
+ pytest.param(
+ """
+ name = "Daniel"
+ age = 12
+ "My name is {0}, I'm {age}".format(name, age = age)
+ """,
+ id="mixed-indexes-from-mixed",
+ ),
+ ],
+ )
+ def test_string_format(self, format_string: str) -> None:
+ node: nodes.Call = _extract_single_node(format_string)
+ inferred = next(node.infer())
+ assert isinstance(inferred, nodes.Const)
+ assert inferred.value == "My name is Daniel, I'm 12"
+
+ @pytest.mark.parametrize(
+ "format_string",
+ [
+ """
+ from missing import Unknown
+ name = Unknown
+ age = 12
+ "My name is {fname}, I'm {age}".format(fname = name, age = age)
+ """,
+ """
+ from missing import Unknown
+ age = 12
+ "My name is {fname}, I'm {age}".format(fname = Unknown, age = age)
+ """,
+ """
+ from missing import Unknown
+ "My name is {}, I'm {}".format(Unknown, 12)
+ """,
+ """"I am {}".format()""",
+ ],
+ )
+ def test_string_format_uninferable(self, format_string: str) -> None:
+ node: nodes.Call = _extract_single_node(format_string)
+ inferred = next(node.infer())
+ assert inferred is util.Uninferable
+
+ def test_string_format_with_specs(self) -> None:
+ node: nodes.Call = _extract_single_node(
+ """"My name is {}, I'm {:.2f}".format("Daniel", 12)"""
+ )
+ inferred = next(node.infer())
+ assert isinstance(inferred, nodes.Const)
+ assert inferred.value == "My name is Daniel, I'm 12.00"
diff --git a/tests/unittest_inference.py b/tests/unittest_inference.py
index 6ae4f40ae3..cb808df7bb 100644
--- a/tests/unittest_inference.py
+++ b/tests/unittest_inference.py
@@ -2127,7 +2127,6 @@ def test_str_methods(self) -> None:
' '.decode() #@
' '.join('abcd') #@
' '.replace('a', 'b') #@
- ' '.format('a') #@
' '.capitalize() #@
' '.title() #@
' '.lower() #@
@@ -2143,20 +2142,22 @@ def test_str_methods(self) -> None:
' '.index() #@
' '.find() #@
' '.count() #@
+
+ ' '.format('a') #@
"""
ast = extract_node(code, __name__)
self.assertInferConst(ast[0], "")
- for i in range(1, 15):
+ for i in range(1, 14):
self.assertInferConst(ast[i], "")
- for i in range(15, 18):
+ for i in range(14, 17):
self.assertInferConst(ast[i], 0)
+ self.assertInferConst(ast[17], " ")
def test_unicode_methods(self) -> None:
code = """
u' '.decode() #@
u' '.join('abcd') #@
u' '.replace('a', 'b') #@
- u' '.format('a') #@
u' '.capitalize() #@
u' '.title() #@
u' '.lower() #@
@@ -2172,13 +2173,16 @@ def test_unicode_methods(self) -> None:
u' '.index() #@
u' '.find() #@
u' '.count() #@
+
+ u' '.format('a') #@
"""
ast = extract_node(code, __name__)
self.assertInferConst(ast[0], "")
- for i in range(1, 15):
+ for i in range(1, 14):
self.assertInferConst(ast[i], "")
- for i in range(15, 18):
+ for i in range(14, 17):
self.assertInferConst(ast[i], 0)
+ self.assertInferConst(ast[17], " ")
def test_scope_lookup_same_attributes(self) -> None:
code = """
diff --git a/tests/unittest_scoped_nodes.py b/tests/unittest_scoped_nodes.py
index 0236fcab27..45307c8bdc 100644
--- a/tests/unittest_scoped_nodes.py
+++ b/tests/unittest_scoped_nodes.py
@@ -1699,10 +1699,12 @@ def __init__(self):
"FinalClass",
"ClassB",
"MixinB",
- "",
+ # We don't recognize what 'cls' is at time of .format() call, only
+ # what it is at the end.
+ # "strMixin",
"ClassA",
"MixinA",
- "",
+ "intMixin",
"Base",
"object",
],
|
none
|
[
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[empty-indexes]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[numbered-indexes]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[named-indexes]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[numbered-indexes-from-positional]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[named-indexes-from-keyword]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[mixed-indexes-from-mixed]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_uninferable[\\n",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_uninferable[\"I",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_with_specs",
"tests/unittest_inference.py::InferenceTest::test_str_methods",
"tests/unittest_inference.py::InferenceTest::test_unicode_methods",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_factories"
] |
[
"tests/unittest_brain_builtin.py::BuiltinsTest::test_infer_property",
"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_self_in_list",
"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_new",
"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_copy_method_inference",
"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_for_dict",
"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_inner_value_redefined_by_subclass_with_mro",
"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_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_uninferable_type_subscript",
"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::TestBool::test_class_subscript",
"tests/unittest_inference.py::TestType::test_type",
"tests/unittest_inference.py::ArgumentsTest::test_args",
"tests/unittest_inference.py::ArgumentsTest::test_args_overwritten",
"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_compare[<-False]",
"tests/unittest_inference.py::test_compare[<=-True]",
"tests/unittest_inference.py::test_compare[==-True]",
"tests/unittest_inference.py::test_compare[>=-True]",
"tests/unittest_inference.py::test_compare[>-False]",
"tests/unittest_inference.py::test_compare[!=-False]",
"tests/unittest_inference.py::test_compare_membership[in-True]",
"tests/unittest_inference.py::test_compare_membership[not",
"tests/unittest_inference.py::test_compare_lesseq_types[1-1-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[1-1.1-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[1.1-1-False]",
"tests/unittest_inference.py::test_compare_lesseq_types[1.0-1.0-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[abc-def-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[abc--False]",
"tests/unittest_inference.py::test_compare_lesseq_types[lhs6-rhs6-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[lhs7-rhs7-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[lhs8-rhs8-False]",
"tests/unittest_inference.py::test_compare_lesseq_types[True-True-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[True-False-False]",
"tests/unittest_inference.py::test_compare_lesseq_types[False-1-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[(1+0j)-(2+0j)-result12]",
"tests/unittest_inference.py::test_compare_lesseq_types[0.0--0.0-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[0-1-result14]",
"tests/unittest_inference.py::test_compare_lesseq_types[\\x00-\\x01-True]",
"tests/unittest_inference.py::test_compare_chained",
"tests/unittest_inference.py::test_compare_inferred_members",
"tests/unittest_inference.py::test_compare_instance_members",
"tests/unittest_inference.py::test_compare_uninferable_member",
"tests/unittest_inference.py::test_compare_chained_comparisons_shortcircuit_on_false",
"tests/unittest_inference.py::test_compare_chained_comparisons_continue_on_true",
"tests/unittest_inference.py::test_compare_ifexp_constant",
"tests/unittest_inference.py::test_compare_typeerror",
"tests/unittest_inference.py::test_compare_multiple_possibilites",
"tests/unittest_inference.py::test_compare_ambiguous_multiple_possibilites",
"tests/unittest_inference.py::test_compare_nonliteral",
"tests/unittest_inference.py::test_compare_unknown",
"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_property_docstring",
"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_inference.py::test_pylint_issue_4692_attribute_inference_error_in_infer_import_from",
"tests/unittest_inference.py::test_issue_1090_infer_yield_type_base_class",
"tests/unittest_inference.py::test_namespace_package",
"tests/unittest_inference.py::test_namespace_package_same_name",
"tests/unittest_inference.py::test_relative_imports_init_package",
"tests/unittest_inference.py::test_inference_of_items_on_module_dict",
"tests/unittest_inference.py::test_imported_module_var_inferable",
"tests/unittest_inference.py::test_imported_module_var_inferable2",
"tests/unittest_inference.py::test_imported_module_var_inferable3",
"tests/unittest_inference.py::test_recursion_on_inference_tip",
"tests/unittest_inference.py::test_function_def_cached_generator",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_comment_before_docstring",
"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_multiline_docstring",
"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_singleline_docstring",
"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::ModuleNodeTest::test_without_docstring",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_abstract_methods_are_not_implicitly_none",
"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_docstring_special_cases",
"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_func_is_bound",
"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_getattr",
"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_multiline_docstring",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_multiline_docstring_async",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_navigation",
"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_scoped_nodes.py::FunctionNodeTest::test_positional_only_argnames",
"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_singleline_docstring",
"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::FunctionNodeTest::test_without_docstring",
"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_typing_extensions",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_attribute_classes",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_multiline_docstring",
"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_singleline_docstring",
"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::ClassNodeTest::test_without_docstring",
"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_scoped_nodes.py::test_slots_duplicate_bases_issue_1089",
"tests/unittest_scoped_nodes.py::TestFrameNodes::test_frame_node",
"tests/unittest_scoped_nodes.py::TestFrameNodes::test_non_frame_node",
"tests/unittest_scoped_nodes.py::test_deprecation_of_doc_attribute",
"tests/unittest_inference.py::InferenceTest::test_descriptor_are_callable",
"tests/unittest_inference.py::InferenceTest::test_function_metaclasses",
"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_compare_identity[is-True]",
"tests/unittest_inference.py::test_compare_identity[is",
"tests/unittest_inference.py::test_compare_dynamic",
"tests/unittest_inference.py::test_compare_known_false_branch",
"tests/unittest_inference.py::test_recursion_error_self_reference_type_call"
] |
[
"pytest -rA tests/"
] |
pytest
|
{
"files": 2,
"hunks": 3,
"lines": 50
}
|
||
ec96745c0fdb9432549d182e381164d1836e8a4b
|
[
"https://github.com/pylint-dev/astroid/commit/e712edced04a26e12e2aed94e555d6e2a25c9d4d"
] | 2020-06-20T00:58:26
|
pylint-dev__astroid-805
|
[
"777"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index 737b682ec4..c8c6bcfb1d 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -13,6 +13,10 @@ Release Date: TBA
Fixes PyCQA/pylint#3599
+* Prevent recursion error for self referential length calls
+
+ Close #777
+
* Added missing methods to the brain for ``mechanize``, to fix pylint false positives
Close #793
diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py
index 074ec476d7..3a4f364d86 100644
--- a/astroid/brain/brain_builtin_inference.py
+++ b/astroid/brain/brain_builtin_inference.py
@@ -759,6 +759,7 @@ def infer_len(node, context=None):
"({len}) given".format(len=len(call.positional_arguments))
)
[argument_node] = call.positional_arguments
+
try:
return nodes.Const(helpers.object_len(argument_node, context=context))
except (AstroidTypeError, InferenceError) as exc:
diff --git a/astroid/helpers.py b/astroid/helpers.py
index 8ab687999e..a7764d7acc 100644
--- a/astroid/helpers.py
+++ b/astroid/helpers.py
@@ -237,13 +237,31 @@ def object_len(node, context=None):
:raises AstroidTypeError: If an invalid node is returned
from __len__ method or no __len__ method exists
:raises InferenceError: If the given node cannot be inferred
- or if multiple nodes are inferred
+ or if multiple nodes are inferred or if the code executed in python
+ would result in a infinite recursive check for length
:rtype int: Integer length of node
"""
# pylint: disable=import-outside-toplevel; circular import
from astroid.objects import FrozenSet
inferred_node = safe_infer(node, context=context)
+
+ # prevent self referential length calls from causing a recursion error
+ # see https://github.com/PyCQA/astroid/issues/777
+ node_frame = node.frame()
+ if (
+ isinstance(node_frame, scoped_nodes.FunctionDef)
+ and node_frame.name == "__len__"
+ and inferred_node._proxied == node_frame.parent
+ ):
+ message = (
+ "Self referential __len__ function will "
+ "cause a RecursionError on line {} of {}".format(
+ node.lineno, node.root().file
+ )
+ )
+ raise exceptions.InferenceError(message)
+
if inferred_node is None or inferred_node is util.Uninferable:
raise exceptions.InferenceError(node=node)
if isinstance(inferred_node, nodes.Const) and isinstance(
|
Astroid Infinite loop when `__len__(self)` is mistakenly defined as `return len(self)`
### Steps to reproduce
Lint the following program with pylint
```python
class Crash:
def __len__(self) -> int:
return len(self)
```
### Current behavior
The following error is thrown and pylint crashes
```
RecursionError: maximum recursion depth exceeded
```
### Expected behavior
It should not crash.
### Asteroid version
2.4.0
|
805
|
pylint-dev/astroid
|
diff --git a/tests/unittest_brain.py b/tests/unittest_brain.py
index 25e2bb5b73..c308ddd535 100644
--- a/tests/unittest_brain.py
+++ b/tests/unittest_brain.py
@@ -2035,5 +2035,21 @@ def test_str_and_bytes(code, expected_class, expected_value):
assert inferred.value == expected_value
+def test_no_recursionerror_on_self_referential_length_check():
+ """
+ Regression test for https://github.com/PyCQA/astroid/issues/777
+ """
+ with pytest.raises(astroid.InferenceError):
+ node = astroid.extract_node(
+ """
+ class Crash:
+ def __len__(self) -> int:
+ return len(self)
+ len(Crash()) #@
+ """
+ )
+ node.inferred()
+
+
if __name__ == "__main__":
unittest.main()
|
none
|
[
"tests/unittest_brain.py::test_no_recursionerror_on_self_referential_length_check"
] |
[
"tests/unittest_brain.py::HashlibTest::test_hashlib",
"tests/unittest_brain.py::HashlibTest::test_hashlib_py36",
"tests/unittest_brain.py::CollectionsDequeTests::test_deque",
"tests/unittest_brain.py::CollectionsDequeTests::test_deque_py35methods",
"tests/unittest_brain.py::OrderedDictTest::test_ordered_dict_py34method",
"tests/unittest_brain.py::NamedTupleTest::test_invalid_label_does_not_crash_inference",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_access_class_fields",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_advanced_inference",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_base",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_bases_are_actually_names_not_nodes",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_func_form",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_func_form_args_and_kwargs",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_inference",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_inference_failure",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_instance_attrs",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_rename_duplicates",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_rename_keywords",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_rename_uninferable",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_uninferable_fields",
"tests/unittest_brain.py::DefaultDictTest::test_1",
"tests/unittest_brain.py::ModuleExtenderTest::testExtensionModules",
"tests/unittest_brain.py::SixBrainTest::test_attribute_access",
"tests/unittest_brain.py::SixBrainTest::test_from_imports",
"tests/unittest_brain.py::SixBrainTest::test_from_submodule_imports",
"tests/unittest_brain.py::MultiprocessingBrainTest::test_module_name",
"tests/unittest_brain.py::MultiprocessingBrainTest::test_multiprocessing_manager",
"tests/unittest_brain.py::MultiprocessingBrainTest::test_multiprocessing_module_attributes",
"tests/unittest_brain.py::ThreadingBrainTest::test_boundedsemaphore",
"tests/unittest_brain.py::ThreadingBrainTest::test_lock",
"tests/unittest_brain.py::ThreadingBrainTest::test_rlock",
"tests/unittest_brain.py::ThreadingBrainTest::test_semaphore",
"tests/unittest_brain.py::EnumBrainTest::test_dont_crash_on_for_loops_in_body",
"tests/unittest_brain.py::EnumBrainTest::test_enum_func_form_has_dunder_members",
"tests/unittest_brain.py::EnumBrainTest::test_enum_func_form_is_class_not_instance",
"tests/unittest_brain.py::EnumBrainTest::test_enum_func_form_iterable",
"tests/unittest_brain.py::EnumBrainTest::test_enum_func_form_subscriptable",
"tests/unittest_brain.py::EnumBrainTest::test_enum_multiple_base_classes",
"tests/unittest_brain.py::EnumBrainTest::test_enum_tuple_list_values",
"tests/unittest_brain.py::EnumBrainTest::test_ignores_with_nodes_from_body_of_enum",
"tests/unittest_brain.py::EnumBrainTest::test_infer_enum_value_as_the_right_type",
"tests/unittest_brain.py::EnumBrainTest::test_int_enum",
"tests/unittest_brain.py::EnumBrainTest::test_looks_like_enum_false_positive",
"tests/unittest_brain.py::EnumBrainTest::test_mingled_single_and_double_quotes_does_not_crash",
"tests/unittest_brain.py::EnumBrainTest::test_simple_enum",
"tests/unittest_brain.py::EnumBrainTest::test_special_characters_does_not_crash",
"tests/unittest_brain.py::PytestBrainTest::test_pytest",
"tests/unittest_brain.py::TypingBrain::test_has_dunder_args",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_base",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_can_correctly_access_methods",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_class_form",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_inference",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_instance_attrs",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_simple",
"tests/unittest_brain.py::TypingBrain::test_typing_namedtuple_dont_crash_on_no_fields",
"tests/unittest_brain.py::TypingBrain::test_typing_types",
"tests/unittest_brain.py::ReBrainTest::test_regex_flags",
"tests/unittest_brain.py::BrainFStrings::test_no_crash_on_const_reconstruction",
"tests/unittest_brain.py::BrainNamedtupleAnnAssignTest::test_no_crash_on_ann_assign_in_namedtuple",
"tests/unittest_brain.py::BrainUUIDTest::test_uuid_has_int_member",
"tests/unittest_brain.py::RandomSampleTest::test_inferred_successfully",
"tests/unittest_brain.py::SubprocessTest::test_subprcess_check_output",
"tests/unittest_brain.py::SubprocessTest::test_subprocess_args",
"tests/unittest_brain.py::TestIsinstanceInference::test_type_type",
"tests/unittest_brain.py::TestIsinstanceInference::test_object_type",
"tests/unittest_brain.py::TestIsinstanceInference::test_type_object",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_int_true",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_int_false",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_object_true",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_object_true3",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_class_false",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_type_false",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_str_true",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_str_false",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_tuple_argument",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_type_false2",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_object_true2",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_type_true",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_edge_case",
"tests/unittest_brain.py::TestIsinstanceInference::test_uninferable_bad_type",
"tests/unittest_brain.py::TestIsinstanceInference::test_uninferable_keywords",
"tests/unittest_brain.py::TestIsinstanceInference::test_too_many_args",
"tests/unittest_brain.py::TestIsinstanceInference::test_first_param_is_uninferable",
"tests/unittest_brain.py::TestIssubclassBrain::test_type_type",
"tests/unittest_brain.py::TestIssubclassBrain::test_object_type",
"tests/unittest_brain.py::TestIssubclassBrain::test_type_object",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_same_class",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_not_the_same_class",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_object_true",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_same_user_defined_class",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_different_user_defined_classes",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_type_false",
"tests/unittest_brain.py::TestIssubclassBrain::test_isinstance_tuple_argument",
"tests/unittest_brain.py::TestIssubclassBrain::test_isinstance_object_true2",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_short_circuit",
"tests/unittest_brain.py::TestIssubclassBrain::test_uninferable_bad_type",
"tests/unittest_brain.py::TestIssubclassBrain::test_uninferable_keywords",
"tests/unittest_brain.py::TestIssubclassBrain::test_too_many_args",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_list",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_tuple",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_var",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_dict",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_set",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_object",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_class_with_metaclass",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_object_failure",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_string",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_generator_failure",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_failure_missing_variable",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_bytes",
"tests/unittest_brain.py::TestLenBuiltinInference::test_int_subclass_result",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_builtin_inference_attribute_error_str",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_builtin_inference_recursion_error_self_referential_attribute",
"tests/unittest_brain.py::test_infer_str",
"tests/unittest_brain.py::test_infer_int",
"tests/unittest_brain.py::test_infer_dict_from_keys",
"tests/unittest_brain.py::TestFunctoolsPartial::test_invalid_functools_partial_calls",
"tests/unittest_brain.py::TestFunctoolsPartial::test_inferred_partial_function_calls",
"tests/unittest_brain.py::test_http_client_brain",
"tests/unittest_brain.py::test_http_status_brain",
"tests/unittest_brain.py::test_oserror_model",
"tests/unittest_brain.py::test_crypt_brain",
"tests/unittest_brain.py::test_dataclasses",
"tests/unittest_brain.py::test_str_and_bytes['hey'.encode()-Const-]",
"tests/unittest_brain.py::test_str_and_bytes[b'hey'.decode()-Const-]",
"tests/unittest_brain.py::test_str_and_bytes['hey'.encode().decode()-Const-]",
"tests/unittest_brain.py::TestLenBuiltinInference::test_int_subclass_argument"
] |
[
"pytest -rA tests"
] |
pytest
|
{
"files": 3,
"hunks": 3,
"lines": 25
}
|
||
Sorry for taking so long to get back to this. I think it is very likely that we might refactor `AstroidManager` in our efforts to fix our multiprocessing issues. That is why I'm inclined to leave this issue for now and see if it still exists after the refactor and what our stance would then be.
Ended up in the same place after opening #2124. I do think we should reconsider this as part of 3.0. We may look into multiprocessing first, or we may look at this part first, I'm not sure.
> We may look into multiprocessing first, or we may look at this part first, I'm not sure.
Caching the sensitive part seems a lot easier to implement than multiprocessing ? I imagine it as "making sure that we can cache a function because the value returned for a particular input is always the same then adding a decorator on a function" vs "making sure that the design we have to invent can merge the result of two parallel parsing then actually implement it" ?
> For instance, if you amend if mymodule.relative_to_absolute_name(modname, level) == mymodule.name: with if modname and mymodule.relative_to_absolute_name(modname, level) == mymodule.name:, then the bug is gone; but I'm not an astroid developer and I imagine that isn't the right place to fix the issue… it probably has a deeper root cause.
I just independently arrived at the same patch. I think it's correct. #1747 didn't intend to create endless re-instantiation of modules as described in #2124. I'll open a PR and credit you @ltcmelo. Thanks!
|
bb0573d876e91ff66c4ca59369e3d292681f6bd3
|
[
"https://github.com/pylint-dev/astroid/commit/3bbf264934aff17d49cf743f2982f153fa0ed2e6",
"https://github.com/pylint-dev/astroid/commit/2add5ab0bea7fbe6f971f06c2112b57ccb069fbe"
] | 2023-06-07T20:34:42
|
Sorry for taking so long to get back to this. I think it is very likely that we might refactor `AstroidManager` in our efforts to fix our multiprocessing issues. That is why I'm inclined to leave this issue for now and see if it still exists after the refactor and what our stance would then be.
Ended up in the same place after opening #2124. I do think we should reconsider this as part of 3.0. We may look into multiprocessing first, or we may look at this part first, I'm not sure.
> We may look into multiprocessing first, or we may look at this part first, I'm not sure.
Caching the sensitive part seems a lot easier to implement than multiprocessing ? I imagine it as "making sure that we can cache a function because the value returned for a particular input is always the same then adding a decorator on a function" vs "making sure that the design we have to invent can merge the result of two parallel parsing then actually implement it" ?
|
pylint-dev__astroid-2206
|
[
"2041"
] |
python
|
diff --git a/astroid/nodes/_base_nodes.py b/astroid/nodes/_base_nodes.py
index 3ef97b580c..c79fec799b 100644
--- a/astroid/nodes/_base_nodes.py
+++ b/astroid/nodes/_base_nodes.py
@@ -130,8 +130,11 @@ def do_import_module(self, modname: str | None = None) -> nodes.Module:
# If the module ImportNode is importing is a module with the same name
# as the file that contains the ImportNode we don't want to use the cache
# to make sure we use the import system to get the correct module.
- # pylint: disable-next=no-member # pylint doesn't recognize type of mymodule
- if mymodule.relative_to_absolute_name(modname, level) == mymodule.name:
+ if (
+ modname
+ # pylint: disable-next=no-member # pylint doesn't recognize type of mymodule
+ and mymodule.relative_to_absolute_name(modname, level) == mymodule.name
+ ):
use_cache = False
else:
use_cache = True
|
regression introduced in 2.13.0 (from 2.12.14) concerning `use_cache` in astroid's cache
This PR (#1747) introduced a regression in 2.13.0 (from 2.12.14). This regression causes undesired side effects — at least to me :-).
I rely on `AstroidManager.astroid_cache` to provide "special" implementations for certain modules. But the change in the PR mentioned above affects the behavior of `AstroidManager.astroid_cache` in a way that I can no longer ensure that those implementations are consistently used.
(And it appears that this side effect isn't intended by the PR, since the importing module isn't the same name as the imported module.)
Reproducible steps:
### Under path **/user/projects/** ###
File **/user/projects/main.py**
```python
import os
import os.path
import astroid
from astroid.manager import AstroidManager
mngr = AstroidManager()
app_dir_path = os.path.dirname(__file__)
def module_name_from_path(file_path: str):
subpath = os.path.relpath(file_path, app_dir_path)
mod_name = os.path.splitext(subpath)[0].replace(os.sep, '.')
return mod_name
def parse_and_cache(mod_file_path: str, mod_name: str):
with open(mod_file_path, 'r') as f:
code = f.read()
mod_node = astroid.parse(code, mod_name, mod_file_path, True)
if mod_name in mngr.astroid_cache:
del mngr.astroid_cache[mod_name]
mngr.cache_module(mod_node)
return mod_node
if __name__ == '__main__':
prog_mod_path = os.path.abspath(os.path.join(app_dir_path, 'prog.py'))
prog_mod_name = module_name_from_path(prog_mod_path)
prog_mod_node = parse_and_cache(prog_mod_path, prog_mod_name)
lib_dir_path = '/external/repository'
os_dir_path = os.path.abspath(os.path.join(lib_dir_path, 'os', '__init__.py'))
parse_and_cache(os_dir_path, 'os')
ospath_mod_path = os.path.abspath(os.path.join(lib_dir_path, 'os', 'path.py'))
parse_and_cache(ospath_mod_path, 'os.path')
val = next(prog_mod_node.body[1].body[0].value.func.infer())
print(val.parent.frame().file)
```
File **/user/projects/proj.py**:
```
import os.path
def f():
os.path.relpath('abc')
```
### Under path **/external/repository/** ###
This path must not be a subpath of **/user/projects/**.
Directory structure below:
```
$ tree /external/repository
/os
├── __init__.py
└── path.py
```
File **/external/repository/os/__init__.py**:
```
from . import path as path
```
File **/external/repository/os/path.py**:
```
def relpath(s):
return " "
```
## Output of run ##
With:
- astroid 2.12.14 (this is correct/expected "special" `os.path`)
**/external/repository/os/path.py**
- astroid 2.13.0 (the system `os.path`)
**/usr/local/Cellar/python/…/lib/python3.10/posixpath.py**
### Details ###
I can _observe_ the bug in `do_import_module` when `modname` is `None` and also `self.modname` is `None`, which in turn leads to `use_cache = False`. For instance, if you amend `if mymodule.relative_to_absolute_name(modname, level) == mymodule.name:` with `if modname and mymodule.relative_to_absolute_name(modname, level) == mymodule.name:`, then the bug is gone; but I'm not an astroid developer and I imagine that isn't the right place to fix the issue… it probably has a deeper root cause.
|
2206
|
pylint-dev/astroid
|
diff --git a/tests/test_inference.py b/tests/test_inference.py
index 29bf56ac2c..868c83bc5f 100644
--- a/tests/test_inference.py
+++ b/tests/test_inference.py
@@ -22,6 +22,7 @@
Uninferable,
arguments,
helpers,
+ manager,
nodes,
objects,
test_utils,
@@ -991,6 +992,16 @@ def test_import_as(self) -> None:
self.assertIsInstance(inferred[0], nodes.FunctionDef)
self.assertEqual(inferred[0].name, "exists")
+ def test_do_import_module_performance(self) -> None:
+ import_node = extract_node("import importlib")
+ import_node.modname = ""
+ import_node.do_import_module()
+ # calling file_from_module_name() indicates we didn't hit the cache
+ with unittest.mock.patch.object(
+ manager.AstroidManager, "file_from_module_name", side_effect=AssertionError
+ ):
+ import_node.do_import_module()
+
def _test_const_inferred(self, node: nodes.AssignName, value: float | str) -> None:
inferred = list(node.infer())
self.assertEqual(len(inferred), 1)
|
none
|
[
"tests/test_inference.py::InferenceTest::test_do_import_module_performance"
] |
[
"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_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_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_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_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::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_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_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::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"
] |
[
". venv/bin/activate && pytest -rA"
] |
pytest
|
{
"files": 1,
"hunks": 1,
"lines": 7
}
|
Hi, thanks for the report. I tried to reproduce this but I was not able, can you paste the exact code you used to demonstrate the issue?
@PCManticore, reproducibility of this one is straightforward to me, here's a (partial) example — but note that I had a typo in the original snippet: I missed the colon after `type`, which I just fixed; perhaps this is the reason you couldn't reproduce?
Assume an AST visitor with:
```
def visit_functiondef(self, node: nodes.FunctionDef)
print(f'the parent of type comment return is {node.type_comment_returns.parent}')
```
To me, this prints:
<img width="565" alt="Screen Shot 2021-01-04 at 12 06 04" src="https://user-images.githubusercontent.com/2905588/103548904-3a42b800-4e85-11eb-8bca-aa2f9a17313f.png">
I've just hit this myself. Here's what I did to reproduce:
```python
>>> import astroid
>>> f = astroid.extract_node("""
def f(a):
# type: (A) -> None
pass
""")
>>> f.type_comment_args[0].parent
<ast.FunctionDef object at 0x7f0b0fb077f0>
```
Thanks @AWhetter and @ltcmelo
|
5f67396894c79c4661e357ec8bb03aa134a51109
|
[
"https://github.com/pylint-dev/astroid/commit/217aa531a438c3b25cea8ecfd1bb0b834f5bc4f8"
] | 2021-01-31T06:43:56
|
Hi, thanks for the report. I tried to reproduce this but I was not able, can you paste the exact code you used to demonstrate the issue?
@PCManticore, reproducibility of this one is straightforward to me, here's a (partial) example — but note that I had a typo in the original snippet: I missed the colon after `type`, which I just fixed; perhaps this is the reason you couldn't reproduce?
Assume an AST visitor with:
```
def visit_functiondef(self, node: nodes.FunctionDef)
print(f'the parent of type comment return is {node.type_comment_returns.parent}')
```
To me, this prints:
<img width="565" alt="Screen Shot 2021-01-04 at 12 06 04" src="https://user-images.githubusercontent.com/2905588/103548904-3a42b800-4e85-11eb-8bca-aa2f9a17313f.png">
|
pylint-dev__astroid-887
|
[
"851"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index 9ff42a6e77..be30ed4525 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -119,6 +119,13 @@ Release Date: TBA
Close PyCQA/pylint#3904
+* Corrected the parent of function type comment nodes.
+
+ These nodes used to be parented to their original ast.FunctionDef parent
+ but are now correctly parented to their astroid.FunctionDef parent.
+
+ Close PyCQA/astroid#851
+
What's New in astroid 2.4.2?
============================
diff --git a/astroid/rebuilder.py b/astroid/rebuilder.py
index 3fc1a83f2b..e56abbf878 100644
--- a/astroid/rebuilder.py
+++ b/astroid/rebuilder.py
@@ -238,7 +238,7 @@ def check_type_comment(self, node, parent):
return type_object.value
- def check_function_type_comment(self, node):
+ def check_function_type_comment(self, node, parent):
type_comment = getattr(node, "type_comment", None)
if not type_comment:
return None
@@ -251,10 +251,10 @@ def check_function_type_comment(self, node):
returns = None
argtypes = [
- self.visit(elem, node) for elem in (type_comment_ast.argtypes or [])
+ self.visit(elem, parent) for elem in (type_comment_ast.argtypes or [])
]
if type_comment_ast.returns:
- returns = self.visit(type_comment_ast.returns, node)
+ returns = self.visit(type_comment_ast.returns, parent)
return returns, argtypes
@@ -615,7 +615,7 @@ def _visit_functiondef(self, cls, node, parent):
returns = None
type_comment_args = type_comment_returns = None
- type_comment_annotation = self.check_function_type_comment(node)
+ type_comment_annotation = self.check_function_type_comment(node, newnode)
if type_comment_annotation:
type_comment_returns, type_comment_args = type_comment_annotation
newnode.postinit(
|
calling `parent` on a node that is part of a type comment returns the (original) `_ast` module's FunctionDef
Consider this snippet:
```python
def f(s):
# type: (str) -> int
return 42
```
Given the `node` from the type comment, `Name.int(name='int')`, if I call its parent (i.e., `node.parent`), I get the original _ast module's FunctionDef, instead of astroid's FunctionDef.
|
887
|
pylint-dev/astroid
|
diff --git a/tests/unittest_nodes.py b/tests/unittest_nodes.py
index d138ee1704..0ba6b3e541 100644
--- a/tests/unittest_nodes.py
+++ b/tests/unittest_nodes.py
@@ -1181,6 +1181,19 @@ def f_arg_comment(
assert actual_arg.as_string() == expected_arg
+@pytest.mark.skipif(not HAS_TYPED_AST, reason="requires typed_ast")
+def test_correct_function_type_comment_parent():
+ data = """
+ def f(a):
+ # type: (A) -> A
+ pass
+ """
+ astroid = builder.parse(data)
+ f = astroid.body[0]
+ assert f.type_comment_args[0].parent is f
+ assert f.type_comment_returns.parent is f
+
+
def test_is_generator_for_yield_assignments():
node = astroid.extract_node(
"""
|
none
|
[
"tests/unittest_nodes.py::test_correct_function_type_comment_parent"
] |
[
"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::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_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_unicode",
"tests/unittest_nodes.py::NameNodeTest::test_assign_to_True",
"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_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_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": 4,
"lines": 15
}
|
6280a758733434cba32b719519908314a5c2955b
|
[
"https://github.com/pylint-dev/astroid/commit/4e8eca77e4cd577ec8b812ac2da92a96077c953d",
"https://github.com/pylint-dev/astroid/commit/cc49adde8ee7cb8ae23ec0e80f86063ad5de702c"
] | 2022-06-12T11:50:45
|
pylint-dev__astroid-1616
|
[
"1611"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index bcf244b1d9..262c3af41d 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -24,7 +24,7 @@ Release date: TBA
* Calls to ``str.format`` are now correctly inferred.
- Closes #104
+ Closes #104, Closes #1611
* Adds missing enums from ``ssl`` module.
diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py
index 00253f243b..af1ddf4d23 100644
--- a/astroid/brain/brain_builtin_inference.py
+++ b/astroid/brain/brain_builtin_inference.py
@@ -913,12 +913,15 @@ def _infer_copy_method(
def _is_str_format_call(node: nodes.Call) -> bool:
"""Catch calls to str.format()."""
- return (
- isinstance(node.func, nodes.Attribute)
- and node.func.attrname == "format"
- and isinstance(node.func.expr, nodes.Const)
- and isinstance(node.func.expr.value, str)
- )
+ if not isinstance(node.func, nodes.Attribute) or not node.func.attrname == "format":
+ return False
+
+ if isinstance(node.func.expr, nodes.Name):
+ value = helpers.safe_infer(node.func.expr)
+ else:
+ value = node.func.expr
+
+ return isinstance(value, nodes.Const) and isinstance(value.value, str)
def _infer_str_format_call(
@@ -926,7 +929,12 @@ def _infer_str_format_call(
) -> Iterator[nodes.Const | type[util.Uninferable]]:
"""Return a Const node based on the template and passed arguments."""
call = arguments.CallSite.from_call(node, context=context)
- format_template: str = node.func.expr.value
+ if isinstance(node.func.expr, nodes.Name):
+ value: nodes.Const = helpers.safe_infer(node.func.expr)
+ else:
+ value = node.func.expr
+
+ format_template = value.value
# Get the positional arguments passed
inferred_positional = [
|
Infer calls to str.format() on names
Future enhancement could infer this value instead of giving an empty string:
```python
from astroid import extract_node
call = extract_node("""
x = 'python is {}'
x.format('helpful sometimes')
""")
call.inferred()[0].value # gives ""
```
_Originally posted by @jacobtylerwalls in https://github.com/PyCQA/astroid/pull/1602#discussion_r893423433_
|
1616
|
pylint-dev/astroid
|
diff --git a/tests/unittest_brain_builtin.py b/tests/unittest_brain_builtin.py
index 54e7d2190d..dd99444b1f 100644
--- a/tests/unittest_brain_builtin.py
+++ b/tests/unittest_brain_builtin.py
@@ -66,6 +66,13 @@ class TestStringNodes:
""",
id="mixed-indexes-from-mixed",
),
+ pytest.param(
+ """
+ string = "My name is {}, I'm {}"
+ string.format("Daniel", 12)
+ """,
+ id="empty-indexes-on-variable",
+ ),
],
)
def test_string_format(self, format_string: str) -> None:
|
none
|
[
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[empty-indexes-on-variable]"
] |
[
"tests/unittest_brain_builtin.py::BuiltinsTest::test_infer_property",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[empty-indexes]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[numbered-indexes]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[named-indexes]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[numbered-indexes-from-positional]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[named-indexes-from-keyword]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[mixed-indexes-from-mixed]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_uninferable[\\n",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_uninferable[\"I",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_with_specs"
] |
[
"pytest -rA tests/"
] |
pytest
|
{
"files": 2,
"hunks": 3,
"lines": 24
}
|
||
I believe [this change](https://github.com/timmartin/astroid/commit/ffa6bcb757797c3ab2aebd8b9f29018a7022d9ea) will fix this, I just need to write a proper PR.
I think the problem is that when we run multiple inferences in `_inferred_bases`, the context is reused which means the second and subsequent inferences have bad data. Cloning the context before running the inference seems to address this.
@timmartin thanks for the report. I can reproduce it.
One interesting thing is:
```
import astroid
class_node = astroid.extract_node("""
from other import A, B
class Child(A, B): #@
pass
""")
print([cls.name for cls in class_node.mro()])
```
prints: `['Child', 'A', 'B', 'object']`
Yes, that's correct. I believe this is because in the first case, there is non-trivial inference that must be applied to each expression (`other.A`, `other.B`) to determine its type, and sharing the context between the two `infer` calls causes the second to fail. In the second case, the shared context doesn't affect the second `infer` call, either because the two expressions are so trivial or because there's no overlap between the names in the two expressions. I'm mostly guessing this from context, I don't yet properly understand how the inference works.
|
46297774d1a0e57815500a50b2323ea906bd50da
|
[
"https://github.com/pylint-dev/astroid/commit/7f1d5134d89aab9b3e49030676637debfd731dbb",
"https://github.com/pylint-dev/astroid/commit/c89dc0102bfe7a6e72b21e213742bdb982b438cc",
"https://github.com/pylint-dev/astroid/commit/c9c579206a21a00acb7f8fcca0d8f530e3daedef"
] | 2020-10-13T18:57:21
|
pylint-dev__astroid-844
|
[
"843"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index a5a0be55d2..27a61f00ec 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -53,6 +53,10 @@ Release Date: TBA
* Fixed exception-chaining error messages.
+* Fix failure to infer base class type with multiple inheritance and qualified names
+
+ Fixes #843
+
* Reduce memory usage of astroid's module cache.
What's New in astroid 2.4.3?
diff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py
index 5c94196689..a44e6282e3 100644
--- a/astroid/scoped_nodes.py
+++ b/astroid/scoped_nodes.py
@@ -2858,7 +2858,7 @@ def _inferred_bases(self, context=None):
for stmt in self.bases:
try:
- baseobj = next(stmt.infer(context=context))
+ baseobj = next(stmt.infer(context=context.clone()))
except exceptions.InferenceError:
continue
if isinstance(baseobj, bases.Instance):
|
Incorrect MRO inferred with multiple inheritance from module-qualified classes
### Steps to reproduce
File `other.py`:
class A:
pass
class B:
pass
Then run:
import astroid
class_node = astroid.extract_node("""
import other
class Child(other.A, other.B): #@
pass
""")
print([cls.name for cls.name in class_node.mro()])
### Current behavior
['Child', 'A', 'object']
### Expected behavior
['Child', 'A', 'B', 'object']
### ``python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"`` output
2.5.0
|
844
|
pylint-dev/astroid
|
diff --git a/tests/unittest_scoped_nodes.py b/tests/unittest_scoped_nodes.py
index c4597fa686..aef1a671fe 100644
--- a/tests/unittest_scoped_nodes.py
+++ b/tests/unittest_scoped_nodes.py
@@ -1417,6 +1417,22 @@ def __init__(self):
],
)
+ def test_mro_with_attribute_classes(self):
+ cls = builder.extract_node(
+ """
+ class A:
+ pass
+ class B:
+ pass
+ scope = object()
+ scope.A = A
+ scope.B = B
+ class C(scope.A, scope.B):
+ pass
+ """
+ )
+ self.assertEqualMro(cls, ["C", "A", "B", "object"])
+
def test_generator_from_infer_call_result_parent(self):
func = builder.extract_node(
"""
|
none
|
[
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_attribute_classes"
] |
[
"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_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_generator_hack",
"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_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::ClassNodeTest::test_using_invalid_six_add_metaclass_call",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_using_six_add_metaclass",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_with_metaclass_mro",
"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 -rA tests -maxfail=5 --disable-warnings",
"pytest -rA tests --maxfail=5 -p no:warnings"
] |
pytest
|
{
"files": 2,
"hunks": 2,
"lines": 6
}
|
|
0a697736138703c37571ac92d274e4ab0ee7adc3
|
[
"https://github.com/pylint-dev/astroid/commit/6b3e9f95ccf2d41948d8925d1095ffebb7e5dcdb",
"https://github.com/pylint-dev/astroid/commit/123499ffcdea28d7d4ab7a65b3e96d99a5707b52",
"https://github.com/pylint-dev/astroid/commit/0c7c5396c95acf931ad0b740566c0c249c8d00f9"
] | 2021-08-27T14:44:00
|
pylint-dev__astroid-1151
|
[
"1008"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index a8bf1711cc..b79ee7c264 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -6,6 +6,20 @@ What's New in astroid 2.8.0?
============================
Release date: TBA
+* Fixed bug in attribute inference from inside method calls.
+
+ Closes PyCQA/pylint#400
+
+* Fixed bug in inference for superclass instance methods called
+ from the class rather than an instance.
+
+ Closes #1008
+ Closes PyCQA/pylint#4377
+
+* Fixed bug in inference of chained attributes where a subclass
+ had an attribute that was an instance of its superclass.
+
+ Closes PyCQA/pylint#4220
What's New in astroid 2.7.3?
diff --git a/astroid/arguments.py b/astroid/arguments.py
index 3ee77ef9f4..a1104e2b67 100644
--- a/astroid/arguments.py
+++ b/astroid/arguments.py
@@ -216,11 +216,15 @@ def infer_argument(self, funcnode, name, context):
positional.append(arg)
if argindex is not None:
+ boundnode = getattr(context, "boundnode", None)
# 2. first argument of instance/class method
if argindex == 0 and funcnode.type in ("method", "classmethod"):
- if context.boundnode is not None:
- boundnode = context.boundnode
- else:
+ # context.boundnode is None when an instance method is called with
+ # the class, e.g. MyClass.method(obj, ...). In this case, self
+ # is the first argument.
+ if boundnode is None and funcnode.type == "method" and positional:
+ return positional[0].infer(context=context)
+ if boundnode is None:
# XXX can do better ?
boundnode = funcnode.parent.frame()
@@ -242,7 +246,7 @@ def infer_argument(self, funcnode, name, context):
# if we have a method, extract one position
# from the index, so we'll take in account
# the extra parameter represented by `self` or `cls`
- if funcnode.type in ("method", "classmethod"):
+ if funcnode.type in ("method", "classmethod") and boundnode:
argindex -= 1
# 2. search arg index
try:
diff --git a/astroid/bases.py b/astroid/bases.py
index bef2947f9e..554da766f6 100644
--- a/astroid/bases.py
+++ b/astroid/bases.py
@@ -169,6 +169,7 @@ def _infer_method_result_truth(instance, method_name, context):
if not meth.callable():
return util.Uninferable
try:
+ context.callcontext = contextmod.CallContext(args=[], callee=meth)
for value in meth.infer_call_result(instance, context=context):
if value is util.Uninferable:
return value
@@ -318,7 +319,6 @@ def bool_value(self, context=None):
all its instances are considered true.
"""
context = context or contextmod.InferenceContext()
- context.callcontext = contextmod.CallContext(args=[])
context.boundnode = self
try:
@@ -336,9 +336,9 @@ def getitem(self, index, context=None):
new_context = contextmod.bind_context_to_node(context, self)
if not context:
context = new_context
- # Create a new CallContext for providing index as an argument.
- new_context.callcontext = contextmod.CallContext(args=[index])
method = next(self.igetattr("__getitem__", context=context), None)
+ # Create a new CallContext for providing index as an argument.
+ new_context.callcontext = contextmod.CallContext(args=[index], callee=method)
if not isinstance(method, BoundMethod):
raise InferenceError(
"Could not find __getitem__ for {node!r}.", node=self, context=context
diff --git a/astroid/context.py b/astroid/context.py
index 6cb4cd641f..ecedd227cc 100644
--- a/astroid/context.py
+++ b/astroid/context.py
@@ -14,10 +14,10 @@
"""Various context related utilities, including inference and call contexts."""
import contextlib
import pprint
-from typing import TYPE_CHECKING, MutableMapping, Optional, Sequence, Tuple
+from typing import TYPE_CHECKING, List, MutableMapping, Optional, Sequence, Tuple
if TYPE_CHECKING:
- from astroid.nodes.node_classes import NodeNG
+ from astroid.nodes.node_classes import Keyword, NodeNG
_INFERENCE_CACHE = {}
@@ -164,19 +164,21 @@ def __str__(self):
class CallContext:
"""Holds information for a call site."""
- __slots__ = ("args", "keywords")
+ __slots__ = ("args", "keywords", "callee")
- def __init__(self, args, keywords=None):
- """
- :param List[NodeNG] args: Call positional arguments
- :param Union[List[nodes.Keyword], None] keywords: Call keywords
- """
- self.args = args
+ def __init__(
+ self,
+ args: List["NodeNG"],
+ keywords: Optional[List["Keyword"]] = None,
+ callee: Optional["NodeNG"] = None,
+ ):
+ self.args = args # Call positional arguments
if keywords:
keywords = [(arg.arg, arg.value) for arg in keywords]
else:
keywords = []
- self.keywords = keywords
+ self.keywords = keywords # Call keyword arguments
+ self.callee = callee # Function being called
def copy_context(context: Optional[InferenceContext]) -> InferenceContext:
diff --git a/astroid/helpers.py b/astroid/helpers.py
index f0fbedb6b1..586cf3a99f 100644
--- a/astroid/helpers.py
+++ b/astroid/helpers.py
@@ -219,13 +219,14 @@ def class_instance_as_index(node):
for instance when multiplying or subscripting a list.
"""
context = contextmod.InferenceContext()
- context.callcontext = contextmod.CallContext(args=[node])
try:
for inferred in node.igetattr("__index__", context=context):
if not isinstance(inferred, bases.BoundMethod):
continue
+ context.boundnode = node
+ context.callcontext = contextmod.CallContext(args=[], callee=inferred)
for result in inferred.infer_call_result(node, context=context):
if isinstance(result, nodes.Const) and isinstance(result.value, int):
return result
diff --git a/astroid/inference.py b/astroid/inference.py
index 80f7860d36..2c4b8c94df 100644
--- a/astroid/inference.py
+++ b/astroid/inference.py
@@ -223,9 +223,6 @@ def infer_name(self, context=None):
def infer_call(self, context=None):
"""infer a Call node by trying to guess what the function returns"""
callcontext = contextmod.copy_context(context)
- callcontext.callcontext = contextmod.CallContext(
- args=self.args, keywords=self.keywords
- )
callcontext.boundnode = None
if context is not None:
callcontext.extra_context = _populate_context_lookup(self, context.clone())
@@ -236,6 +233,9 @@ def infer_call(self, context=None):
continue
try:
if hasattr(callee, "infer_call_result"):
+ callcontext.callcontext = contextmod.CallContext(
+ args=self.args, keywords=self.keywords, callee=callee
+ )
yield from callee.infer_call_result(caller=self, context=callcontext)
except InferenceError:
continue
@@ -304,23 +304,7 @@ def infer_attribute(self, context=None):
yield owner
continue
- if context and context.boundnode:
- # This handles the situation where the attribute is accessed through a subclass
- # of a base class and the attribute is defined at the base class's level,
- # by taking in consideration a redefinition in the subclass.
- if isinstance(owner, bases.Instance) and isinstance(
- context.boundnode, bases.Instance
- ):
- try:
- if helpers.is_subtype(
- helpers.object_type(context.boundnode),
- helpers.object_type(owner),
- ):
- owner = context.boundnode
- except _NonDeducibleTypeHierarchy:
- # Can't determine anything useful.
- pass
- elif not context:
+ if not context:
context = contextmod.InferenceContext()
old_boundnode = context.boundnode
@@ -535,7 +519,10 @@ def _infer_unaryop(self, context=None):
continue
context = contextmod.copy_context(context)
- context.callcontext = contextmod.CallContext(args=[operand])
+ context.boundnode = operand
+ context.callcontext = contextmod.CallContext(
+ args=[], callee=inferred
+ )
call_results = inferred.infer_call_result(self, context=context)
result = next(call_results, None)
if result is None:
@@ -574,6 +561,7 @@ def _invoke_binop_inference(instance, opnode, op, other, context, method_name):
methods = dunder_lookup.lookup(instance, method_name)
context = contextmod.bind_context_to_node(context, instance)
method = methods[0]
+ context.callcontext.callee = method
try:
inferred = next(method.infer(context=context))
except StopIteration as e:
diff --git a/astroid/nodes/scoped_nodes.py b/astroid/nodes/scoped_nodes.py
index 40eac1c5f4..3d270e236d 100644
--- a/astroid/nodes/scoped_nodes.py
+++ b/astroid/nodes/scoped_nodes.py
@@ -2267,6 +2267,7 @@ def infer_call_result(self, caller, context=None):
# Call type.__call__ if not set metaclass
# (since type is the default metaclass)
context = contextmod.bind_context_to_node(context, self)
+ context.callcontext.callee = dunder_call
yield from dunder_call.infer_call_result(caller, context)
else:
yield self.instantiate_class()
@@ -2712,7 +2713,7 @@ def getitem(self, index, context=None):
# Create a new callcontext for providing index as an argument.
new_context = contextmod.bind_context_to_node(context, self)
- new_context.callcontext = contextmod.CallContext(args=[index])
+ new_context.callcontext = contextmod.CallContext(args=[index], callee=method)
try:
return next(method.infer_call_result(self, new_context), util.Uninferable)
diff --git a/astroid/protocols.py b/astroid/protocols.py
index 3ae9204df0..57fd1beddc 100644
--- a/astroid/protocols.py
+++ b/astroid/protocols.py
@@ -350,9 +350,13 @@ def _arguments_infer_argname(self, name, context):
return
if context and context.callcontext:
- call_site = arguments.CallSite(context.callcontext, context.extra_context)
- yield from call_site.infer_argument(self.parent, name, context)
- return
+ callee = context.callcontext.callee
+ while hasattr(callee, "_proxied"):
+ callee = callee._proxied
+ if getattr(callee, "name", None) == self.parent.name:
+ call_site = arguments.CallSite(context.callcontext, context.extra_context)
+ yield from call_site.infer_argument(self.parent, name, context)
+ return
if name == self.vararg:
vararg = nodes.const_factory(())
@@ -379,6 +383,16 @@ def _arguments_infer_argname(self, name, context):
def arguments_assigned_stmts(self, node=None, context=None, assign_path=None):
if context.callcontext:
+ callee = context.callcontext.callee
+ while hasattr(callee, "_proxied"):
+ callee = callee._proxied
+ else:
+ callee = None
+ if (
+ context.callcontext
+ and node
+ and getattr(callee, "name", None) == node.frame().name
+ ):
# reset call context/name
callcontext = context.callcontext
context = contextmod.copy_context(context)
|
Incorrect inference of `self` in methods defined in superclasses in unbound methods on a subclass
### Steps to reproduce
```python
import astroid
node = astroid.extract_node("""
class Base:
def replace(self):
return self
class Derived(Base):
def method(self):
return 123
this = Derived()
that = Derived.replace(this)
that
""")
inferred = next(node.infer())
inferred.getattr('method')
```
### Current behavior
`that` is inferred as an instance of `.Base` not `.Derived`, causing this exception:
```python
Traceback (most recent call last):
File "astroid/bases.py", line 182, in getattr
values = self._proxied.instance_attr(name, context)
File "astroid/scoped_nodes.py", line 2433, in instance_attr
raise exceptions.AttributeInferenceError(
astroid.exceptions.AttributeInferenceError: 'method' not found on <ClassDef.Base l.2 at 0x...>.
```
which leads to `no-member` warnings on `pylint`
### Expected behavior
`that` is inferred as an instance of `.Derived`.
### `python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"` output
2.5.7
### Related issues
Appears to be the root-cause of PyCQA/pylint#4377.
Ref PyCQA/pylint#4487
|
1151
|
pylint-dev/astroid
|
diff --git a/tests/unittest_inference.py b/tests/unittest_inference.py
index eac809e4e6..8653fab6e0 100644
--- a/tests/unittest_inference.py
+++ b/tests/unittest_inference.py
@@ -2384,14 +2384,27 @@ class LambdaInstance(object):
__neg__ = lambda self: self.lala + 1
@property
def lala(self): return 24
+ class InstanceWithAttr(object):
+ def __init__(self):
+ self.x = 42
+ def __pos__(self):
+ return self.x
+ def __neg__(self):
+ return +self - 41
+ def __invert__(self):
+ return self.x + 1
instance = GoodInstance()
lambda_instance = LambdaInstance()
+ instance_with_attr = InstanceWithAttr()
+instance #@
-instance #@
~instance #@
--instance #@
+lambda_instance #@
-lambda_instance #@
+ +instance_with_attr #@
+ -instance_with_attr #@
+ ~instance_with_attr #@
bad_instance = BadInstance()
+bad_instance #@
@@ -2405,13 +2418,13 @@ def lala(self): return 24
+BadInstance #@
"""
)
- expected = [42, 1, 42, -1, 24, 25]
- for node, value in zip(ast_nodes[:6], expected):
+ expected = [42, 1, 42, -1, 24, 25, 42, 1, 43]
+ for node, value in zip(ast_nodes[:9], expected):
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Const)
self.assertEqual(inferred.value, value)
- for bad_node in ast_nodes[6:]:
+ for bad_node in ast_nodes[9:]:
inferred = next(bad_node.infer())
self.assertEqual(inferred, util.Uninferable)
diff --git a/tests/unittest_inference_calls.py b/tests/unittest_inference_calls.py
new file mode 100644
index 0000000000..c14a8619a8
--- /dev/null
+++ b/tests/unittest_inference_calls.py
@@ -0,0 +1,566 @@
+"""Tests for function call inference"""
+
+from astroid import bases, builder, nodes
+from astroid.util import Uninferable
+
+
+def test_no_return():
+ """Test function with no return statements"""
+ node = builder.extract_node(
+ """
+ def f():
+ pass
+
+ f() #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert inferred[0] is Uninferable
+
+
+def test_one_return():
+ """Test function with a single return that always executes"""
+ node = builder.extract_node(
+ """
+ def f():
+ return 1
+
+ f() #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert isinstance(inferred[0], nodes.Const)
+ assert inferred[0].value == 1
+
+
+def test_one_return_possible():
+ """Test function with a single return that only sometimes executes
+
+ Note: currently, inference doesn't handle this type of control flow
+ """
+ node = builder.extract_node(
+ """
+ def f(x):
+ if x:
+ return 1
+
+ f(1) #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert isinstance(inferred[0], nodes.Const)
+ assert inferred[0].value == 1
+
+
+def test_multiple_returns():
+ """Test function with multiple returns"""
+ node = builder.extract_node(
+ """
+ def f(x):
+ if x > 10:
+ return 1
+ elif x > 20:
+ return 2
+ else:
+ return 3
+
+ f(100) #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 3
+ assert all(isinstance(node, nodes.Const) for node in inferred)
+ assert {node.value for node in inferred} == {1, 2, 3}
+
+
+def test_argument():
+ """Test function whose return value uses its arguments"""
+ node = builder.extract_node(
+ """
+ def f(x, y):
+ return x + y
+
+ f(1, 2) #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert isinstance(inferred[0], nodes.Const)
+ assert inferred[0].value == 3
+
+
+def test_inner_call():
+ """Test function where return value is the result of a separate function call"""
+ node = builder.extract_node(
+ """
+ def f():
+ return g()
+
+ def g():
+ return 1
+
+ f() #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert isinstance(inferred[0], nodes.Const)
+ assert inferred[0].value == 1
+
+
+def test_inner_call_with_const_argument():
+ """Test function where return value is the result of a separate function call,
+ with a constant value passed to the inner function.
+ """
+ node = builder.extract_node(
+ """
+ def f():
+ return g(1)
+
+ def g(y):
+ return y + 2
+
+ f() #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert isinstance(inferred[0], nodes.Const)
+ assert inferred[0].value == 3
+
+
+def test_inner_call_with_dynamic_argument():
+ """Test function where return value is the result of a separate function call,
+ with a dynamic value passed to the inner function.
+
+ Currently, this is Uninferable.
+ """
+ node = builder.extract_node(
+ """
+ def f(x):
+ return g(x)
+
+ def g(y):
+ return y + 2
+
+ f(1) #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert inferred[0] is Uninferable
+
+
+def test_method_const_instance_attr():
+ """Test method where the return value is based on an instance attribute with a
+ constant value.
+ """
+ node = builder.extract_node(
+ """
+ class A:
+ def __init__(self):
+ self.x = 1
+
+ def get_x(self):
+ return self.x
+
+ A().get_x() #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert isinstance(inferred[0], nodes.Const)
+ assert inferred[0].value == 1
+
+
+def test_method_const_instance_attr_multiple():
+ """Test method where the return value is based on an instance attribute with
+ multiple possible constant values, across different methods.
+ """
+ node = builder.extract_node(
+ """
+ class A:
+ def __init__(self, x):
+ if x:
+ self.x = 1
+ else:
+ self.x = 2
+
+ def set_x(self):
+ self.x = 3
+
+ def get_x(self):
+ return self.x
+
+ A().get_x() #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 3
+ assert all(isinstance(node, nodes.Const) for node in inferred)
+ assert {node.value for node in inferred} == {1, 2, 3}
+
+
+def test_method_const_instance_attr_same_method():
+ """Test method where the return value is based on an instance attribute with
+ multiple possible constant values, including in the method being called.
+
+ Note that even with a simple control flow where the assignment in the method body
+ is guaranteed to override any previous assignments, all possible constant values
+ are returned.
+ """
+ node = builder.extract_node(
+ """
+ class A:
+ def __init__(self, x):
+ if x:
+ self.x = 1
+ else:
+ self.x = 2
+
+ def set_x(self):
+ self.x = 3
+
+ def get_x(self):
+ self.x = 4
+ return self.x
+
+ A().get_x() #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 4
+ assert all(isinstance(node, nodes.Const) for node in inferred)
+ assert {node.value for node in inferred} == {1, 2, 3, 4}
+
+
+def test_method_dynamic_instance_attr_1():
+ """Test method where the return value is based on an instance attribute with
+ a dynamically-set value in a different method.
+
+ In this case, the return value is Uninferable.
+ """
+ node = builder.extract_node(
+ """
+ class A:
+ def __init__(self, x):
+ self.x = x
+
+ def get_x(self):
+ return self.x
+
+ A(1).get_x() #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert inferred[0] is Uninferable
+
+
+def test_method_dynamic_instance_attr_2():
+ """Test method where the return value is based on an instance attribute with
+ a dynamically-set value in the same method.
+ """
+ node = builder.extract_node(
+ """
+ class A:
+ # Note: no initializer, so the only assignment happens in get_x
+
+ def get_x(self, x):
+ self.x = x
+ return self.x
+
+ A().get_x(1) #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert isinstance(inferred[0], nodes.Const)
+ assert inferred[0].value == 1
+
+
+def test_method_dynamic_instance_attr_3():
+ """Test method where the return value is based on an instance attribute with
+ a dynamically-set value in a different method.
+
+ This is currently Uninferable.
+ """
+ node = builder.extract_node(
+ """
+ class A:
+ def get_x(self, x): # x is unused
+ return self.x
+
+ def set_x(self, x):
+ self.x = x
+
+ A().get_x(10) #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert inferred[0] is Uninferable # not 10!
+
+
+def test_method_dynamic_instance_attr_4():
+ """Test method where the return value is based on an instance attribute with
+ a dynamically-set value in a different method, and is passed a constant value.
+
+ This is currently Uninferable.
+ """
+ node = builder.extract_node(
+ """
+ class A:
+ # Note: no initializer, so the only assignment happens in get_x
+
+ def get_x(self):
+ self.set_x(10)
+ return self.x
+
+ def set_x(self, x):
+ self.x = x
+
+ A().get_x() #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert inferred[0] is Uninferable
+
+
+def test_method_dynamic_instance_attr_5():
+ """Test method where the return value is based on an instance attribute with
+ a dynamically-set value in a different method, and is passed a constant value.
+
+ But, where the outer and inner functions have the same signature.
+
+ Inspired by https://github.com/PyCQA/pylint/issues/400
+
+ This is currently Uninferable.
+ """
+ node = builder.extract_node(
+ """
+ class A:
+ # Note: no initializer, so the only assignment happens in get_x
+
+ def get_x(self, x):
+ self.set_x(10)
+ return self.x
+
+ def set_x(self, x):
+ self.x = x
+
+ A().get_x(1) #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert inferred[0] is Uninferable
+
+
+def test_method_dynamic_instance_attr_6():
+ """Test method where the return value is based on an instance attribute with
+ a dynamically-set value in a different method, and is passed a dynamic value.
+
+ This is currently Uninferable.
+ """
+ node = builder.extract_node(
+ """
+ class A:
+ # Note: no initializer, so the only assignment happens in get_x
+
+ def get_x(self, x):
+ self.set_x(x + 1)
+ return self.x
+
+ def set_x(self, x):
+ self.x = x
+
+ A().get_x(1) #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert inferred[0] is Uninferable
+
+
+def test_dunder_getitem():
+ """Test for the special method __getitem__ (used by Instance.getitem).
+
+ This is currently Uninferable, until we can infer instance attribute values through
+ constructor calls.
+ """
+ node = builder.extract_node(
+ """
+ class A:
+ def __init__(self, x):
+ self.x = x
+
+ def __getitem__(self, i):
+ return self.x + i
+
+ A(1)[2] #@
+ """
+ )
+
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert inferred[0] is Uninferable
+
+
+def test_instance_method():
+ """Tests for instance method, both bound and unbound."""
+ nodes_ = builder.extract_node(
+ """
+ class A:
+ def method(self, x):
+ return x
+
+ A().method(42) #@
+
+ # In this case, the 1 argument is bound to self, which is ignored in the method
+ A.method(1, 42) #@
+ """
+ )
+
+ for node in nodes_:
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert isinstance(inferred[0], nodes.Const)
+ assert inferred[0].value == 42
+
+
+def test_class_method():
+ """Tests for class method calls, both instance and with the class."""
+ nodes_ = builder.extract_node(
+ """
+ class A:
+ @classmethod
+ def method(cls, x):
+ return x
+
+ A.method(42) #@
+ A().method(42) #@
+
+ """
+ )
+
+ for node in nodes_:
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert isinstance(inferred[0], nodes.Const), node
+ assert inferred[0].value == 42
+
+
+def test_static_method():
+ """Tests for static method calls, both instance and with the class."""
+ nodes_ = builder.extract_node(
+ """
+ class A:
+ @staticmethod
+ def method(x):
+ return x
+
+ A.method(42) #@
+ A().method(42) #@
+ """
+ )
+
+ for node in nodes_:
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert isinstance(inferred[0], nodes.Const), node
+ assert inferred[0].value == 42
+
+
+def test_instance_method_inherited():
+ """Tests for instance methods that are inherited from a superclass.
+
+ Based on https://github.com/PyCQA/astroid/issues/1008.
+ """
+ nodes_ = builder.extract_node(
+ """
+ class A:
+ def method(self):
+ return self
+
+ class B(A):
+ pass
+
+ A().method() #@
+ A.method(A()) #@
+
+ B().method() #@
+ B.method(B()) #@
+ A.method(B()) #@
+ """
+ )
+ expected = ["A", "A", "B", "B", "B"]
+ for node, expected in zip(nodes_, expected):
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert isinstance(inferred[0], bases.Instance)
+ assert inferred[0].name == expected
+
+
+def test_class_method_inherited():
+ """Tests for class methods that are inherited from a superclass.
+
+ Based on https://github.com/PyCQA/astroid/issues/1008.
+ """
+ nodes_ = builder.extract_node(
+ """
+ class A:
+ @classmethod
+ def method(cls):
+ return cls
+
+ class B(A):
+ pass
+
+ A().method() #@
+ A.method() #@
+
+ B().method() #@
+ B.method() #@
+ """
+ )
+ expected = ["A", "A", "B", "B"]
+ for node, expected in zip(nodes_, expected):
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert isinstance(inferred[0], nodes.ClassDef)
+ assert inferred[0].name == expected
+
+
+def test_chained_attribute_inherited():
+ """Tests for class methods that are inherited from a superclass.
+
+ Based on https://github.com/PyCQA/pylint/issues/4220.
+ """
+ node = builder.extract_node(
+ """
+ class A:
+ def f(self):
+ return 42
+
+
+ class B(A):
+ def __init__(self):
+ self.a = A()
+ result = self.a.f()
+
+ def f(self):
+ pass
+
+
+ B().a.f() #@
+ """
+ )
+ inferred = node.inferred()
+ assert len(inferred) == 1
+ assert isinstance(inferred[0], nodes.Const)
+ assert inferred[0].value == 42
|
none
|
[
"tests/unittest_inference_calls.py::test_method_dynamic_instance_attr_3",
"tests/unittest_inference_calls.py::test_method_dynamic_instance_attr_5",
"tests/unittest_inference_calls.py::test_method_dynamic_instance_attr_6",
"tests/unittest_inference_calls.py::test_dunder_getitem",
"tests/unittest_inference_calls.py::test_instance_method",
"tests/unittest_inference_calls.py::test_instance_method_inherited",
"tests/unittest_inference_calls.py::test_chained_attribute_inherited"
] |
[
"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_args_overwritten",
"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_inference.py::test_pylint_issue_4692_attribute_inference_error_in_infer_import_from",
"tests/unittest_inference.py::test_issue_1090_infer_yield_type_base_class",
"tests/unittest_inference_calls.py::test_no_return",
"tests/unittest_inference_calls.py::test_one_return",
"tests/unittest_inference_calls.py::test_one_return_possible",
"tests/unittest_inference_calls.py::test_multiple_returns",
"tests/unittest_inference_calls.py::test_argument",
"tests/unittest_inference_calls.py::test_inner_call",
"tests/unittest_inference_calls.py::test_inner_call_with_const_argument",
"tests/unittest_inference_calls.py::test_inner_call_with_dynamic_argument",
"tests/unittest_inference_calls.py::test_method_const_instance_attr",
"tests/unittest_inference_calls.py::test_method_const_instance_attr_multiple",
"tests/unittest_inference_calls.py::test_method_const_instance_attr_same_method",
"tests/unittest_inference_calls.py::test_method_dynamic_instance_attr_1",
"tests/unittest_inference_calls.py::test_method_dynamic_instance_attr_2",
"tests/unittest_inference_calls.py::test_method_dynamic_instance_attr_4",
"tests/unittest_inference_calls.py::test_class_method",
"tests/unittest_inference_calls.py::test_static_method",
"tests/unittest_inference_calls.py::test_class_method_inherited",
"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": 8,
"hunks": 18,
"lines": 110
}
|
||
Thanks for creating the issue @degustaf
Yes, this is still a design goal that we'd want to achieve with `astroid`. There are two reasons for why this didn't happen yet, the first one being the one that you identified about not having enough time to do it. The second one is that it's a rather tricky issue, since there are various cyclic dependencies between `inference.py`, `protocols.py` and the rest of `astroid` files. We attempted to do this in the so called "2.0" branch of astroid (https://github.com/PyCQA/astroid/tree/2.0) which was an effort to reengineer most of astroid's architecture. If you look in that branch, you can see that we managed to reduce that monkeypatching quite a bit, if not all, but at this point, that branch is quite behind everything else and has a lot more changes that can't come easily in `master` without additional work.
If you're interested in helping, cherry-picking the refactoring for dropping the monkeypatch would be definitely amazing.
Can someone provide some details on this please?
astroid 2.0 branch is the default for a long time now, but Manticore's comment is quite recent.
Are there any examples before-after?
But overall I just saw "contributor friendly" tag and wanted to see if I could be of any help.
Hey @gyermolenko ! This might not be contributor friendly after all, as it requires going through https://github.com/PyCQA/astroid/tree/2.0 and bringing back into `master` the removal of monkeypatching methods. The gist of the solution is the use of single dispatch to register inference functions: https://github.com/PyCQA/astroid/blob/2.0/astroid/inference.py#L37
@DanielNoord made a start toward this by suggesting a new design where _nodes don't need to know how to infer themselves_ in #2167 (with a new `infer_object()` API).
Then I suggested an alternative in #2171 where we keep the existing API and just define the methods on the classes where we expect them, and solve cyclic imports along the way.
We have consensus that we'd like to fix this in an alpha of astroid 3.0, but we don't have consensus yet on which direction to take. I'd like to flow out all the concerns folks raised to make sure everything is sounded out before choosing a direction.
***
#### Concerns with the infer_object()/`AstroidManager` approach:
- [Requires "looking up" the inference method](https://github.com/pylint-dev/astroid/pull/2167#issuecomment-1546905250) through a series of isinstance() checks or a mapping from node types to inference methods
- JW: a mapping from node types to inference methods won't support subclassing (a la pylint's unidiomatic-type-check msg)
- JW: a series of isinstance() checks could commit us to a performance degradation
- DN: This could probably be improved upon with some better code-paths and more sharing of code-paths between node types, but it is indeed a cost.
- [The nodes no longer know how to infer themselves](https://github.com/pylint-dev/astroid/pull/2167#discussion_r1186850743)
- JW: from the perspective of making astroid easier to work with, the indirection created here is, for me, slightly better than the status quo, because you no longer have to search through various long files to find the assignment of a method, but it still doesn't seem like a Pythonic design: the node inference methods are node-specific (rely on attributes of those specific nodes). It strikes me as unwanted indirection to have to use a map from a node to node-specific method instead of having that node-specific method defined on the node.
- DN: Is knowing how to infer themselves really the responsibility of the nodes? Personally I believe that having the nodes act as an (almost) drop-in replacement of `ast` and letting another part of the code handle the inferences of said nodes makes more sense. It means that the `nodes` module would just become a data layer over `ast` while all of the core logic can be moved into a separate module. That _should_ reduce/remove a lot of the interdependencies between the data/model layer and the layer that actually uses it.
- API-breakage
- JW: I'm not sure what the final intended pattern is, e.g. if we're going to leave "infer()" as a shim forever--and accept a cyclic import of inference.infer_object--or if we're going to remove it. We have permission to remove interfaces in a major version, but the cost to users should be weighed in the total analysis as a minor factor.
- DN: I don't think in recent months/years we have seen many contributions from other users than `pylint`. In fact, the only person that was actively contributing for a longer period of time moved away because `astroid` is so incompatible. See https://github.com/pylint-dev/astroid/issues/1338 and other issues opened by them at that time. We don't seem to gain much from keeping API stability.
DN: I'd also like to reiterate that I do think that `infer_object` is less than optimal and think that we can improve upon it considerably. However, I wanted to do this in smaller steps, see my subsequent PR as well. My main intent is to have on `AstroidManager` class (or something similar) that is the entry point for inference and doesn't have any global state. I believe this is the only way to make `pylint` at least somewhat useful in a `multiprocessing` environment.
***
#### Concerns with keeping the existing API and refactoring to avoid cyclic imports
- [Introduces some mixin classes](https://github.com/pylint-dev/astroid/pull/2171#pullrequestreview-1425514532)
- JW: Personally, I rarely guard mixins against unintended instantiation. If there is concern about unintended instantiation, I'll just [get rid of the mixins and add a helper function](https://github.com/pylint-dev/astroid/pull/2171#discussion_r1193210178).
- DN: I really dislikes Mixins as the Python tooling such as `mypy` and `pylint` doesn't handle them very well.
- [Prevents decoupling nodes from inference in order to have a drop-in replacement for ast nodes](https://github.com/pylint-dev/astroid/pull/2167#issuecomment-1537439387)
- DN: See above as well. I think making `astroid` be more of a drop-in could (finally) increase the number of contributions.
- JW: Marc indicated [here](https://github.com/pylint-dev/astroid/issues/1361#issuecomment-1025275715) his inclination against viewing astroid as a drop-in replacement for ast nodes
- [NodeNG.infer() depends on global AstroidManager state](https://github.com/pylint-dev/astroid/pull/2167#issuecomment-1546910655)
- DN: https://github.com/pylint-dev/astroid/blob/ee121600c07ecdab55d5fc9179b9bdf2cba0fd74/astroid/nodes/node_ng.py#L178. Although we could probably work around this there are multiple places in our code where we just do `AstroidManager()` and then use the global state. As said above, I don't see `infer_object` as the final version of the inference system but I do see it as a clearer step towards having an inference system that can be instantiated on demand and without any shared state.
- JW: I didn't follow this one, hoping to grok it after DN's updates. I understand that global state jeopardizes parallelism, but that seems like an orthogonal problem to me. Do you have an example of how #2167 would help in this regard?
- [Composition when involving setting instance attributes](https://github.com/pylint-dev/astroid/pull/2167#issuecomment-1546910655)
- JW: Do you have an example of how #2167 would help in this regard? I didn't grok this.
- DN: See above. I don't like how we use `postinit` and have to see instance attributes as class-scope typed attributes to make things work for `mypy`. Mixins make this even worse. To me those types seem like an anti-pattern that we should try and avoid. #2167 doesn't fix this, but also doesn't make the problem worse.
- [The nodes modules will become longer](https://github.com/pylint-dev/astroid/pull/2171#pullrequestreview-1416999939)
DN: What I don't really like about keeping the existing API is that I don't see a clear path towards some of the existing issues we have. Although you showed that it does allow us to fix some of the cyclic imports etc. for me it just doesn't click how making one class/type responsible for everything improves the state of the codebase. I think separation of concerns would be better and makes it easier to tackle individual problems. Perhaps I'm too influenced by my day to day work but I tend to see `astroid` as having a data and an application layer (with `pylint` being the frontend if you want to complete this comparison). Separation between the data modelling layer and the layer that interacts with it feels more natural to me, but that might just be my own preference.
I hope to find time tonight to get back to this! My comment in https://github.com/pylint-dev/astroid/pull/2210 is also somewhat related to my general ideas about `astroid` startup.
I have added my comments to the list. Let's continue the discussion in comments from now on and not keep editing the original post by Jacob.
Thanks, I really appreciate your taking the time to add notes! I'm hoping the silly bullet-point debate-flow-outline might help others follow the discussions we had across several PRs. 😄
I'll let this be my last post on the subject for a while, because if I drone on it could discourage other people from speaking up. 📣
***
I'm hearing the arguments for the `infer_object()` approach[*] as mostly design-philosophical and priced with a "we think this will make future fixes easier" discount. That's not enough for a merge for me. I don't think making an inference a pure function instead of an instance method makes astroid either easier or harder to contribute to, or multiprocessing bugs either easier or harder to solve. Pure functions are beautiful! I spent a lot of the last year in React, which loves them. But even React has pragmatic escape-hatches when you need global state or side effects, and when we address the multiprocessing optimizations, we will ideally have less global state than now, but likely will still need a little global state, and then we'll need to put it somewhere, and then the pure `infer_object()` won't be so pure anymore. And then I'll be back where I started, wondering why we merged it (and potentially with new things to optimize, like the isisnstance checks).
Or not! But it's too early to know. Is this PR supposed to be the first PR in a series of PRs to fix multiprocessing? It seems to me like the wrong place to start. Or, in other words, it seems like only one person has a mental roadmap of how `infer_object()` would pay off for multiprocessing. Pierre [indicated](https://github.com/pylint-dev/astroid/pull/2167#issuecomment-1579358424) a similar hesitation. (I did look at the second PR, which I took to be #2168, but it just removes the monkey-patching, which we've already agreed both PRs do just fine.)
[*] just noticed that @DanielNoord edited the post to clarify that it's the "`infer_object()`/`AstroidManager`" approach, but this is the crux of the whole thing: I don't see the two as connected. I'll gladly work on PRs on the AstroidManager after merging my alternative to just get rid of the monkey patching. I feel like the in-person analogue of where we're at right now is that we have two contributors looking at a whiteboard and making opposite educated guesses; in that scenario, I think it's better to merge the consensual parts: just removing the monkey-patching.
***
> My main intent is to have on AstroidManager class (or something similar) that is the entry point for inference and doesn't have any global state. I believe this is the only way to make pylint at least somewhat useful in a multiprocessing environment.
Same as above, I'm not convinced this would be the only way to do that? I'd rather see at least some proof-of-concept of some element of removing global state and how infer_object() is necessary to make it work.
> What I don't really like about keeping the existing API is that I don't see a clear path towards some of the existing issues we have. Although you showed that it does allow us to fix some of the cyclic imports etc. for me it just doesn't click how making one class/type responsible for everything improves the state of the codebase. I think separation of concerns would be better and makes it easier to tackle individual problems.
> As said above, I don't see infer_object as the final version of the inference system but I do see it as a clearer step towards having an inference system that can be instantiated on demand and without any shared state.
To avoid repeating myself :D...
The multiprocessing bugs: just a cyclic-import behavior bug and then optimizing to make sure we actually are parallelizing the right things, right? Performance optimizations can be very surprising; it's better to optimize from reasoning about the existing system and profiling it, not from heuristics and design philosophy. This is why I'm so hesitant.
> I think making astroid be more of a drop-in could (finally) increase the number of contributions.
I confess to not even being sure how this would work. A few lines of pseudocode would help, if you're up for it. What do people want with the astroid library if they don't want inference? I know there was a comment along these lines from PCManticore in https://github.com/pylint-dev/astroid/issues/169#issuecomment-163118560, though.
I think the most impactful intervention for new contributors would be continuing to use the good-first-issues label and ensuring we don't ask for big refactors along the way. (The str/repr PR in #2198 was a good experience, I felt!)
> I'm hearing the arguments for the `infer_object()` approach[*] as mostly design-philosophical and priced with a "we think this will make future fixes easier" discount. That's not enough for a merge for me.
This is fair. I think the counter-argument is why I am so hesitant for the other approach: I don't see the end-goal and only a fix for one particular issue. We have so many difficulties with getting `astroid` fully typed an into a more modern codebase that support parallelisation that I think we would benefit from a more clear migration path (similar to the famous V2 branch). Since the end-goal I envisioned is 180 degrees different to what you propose in that PR I find it hard to see how we go to a truly better design from there.
> Is this PR supposed to be the first PR in a series of PRs to fix multiprocessing? It seems to me like the wrong place to start.
This is basically my argument above reworded in my opinion 😄 What is the end objective of that PR? And if there isn't one: shouldn't there be one?
> Or, in other words, it seems like only one person has a mental roadmap of how `infer_object()` would pay off for multiprocessing.
I agree, I should have discussed this more clearly.
> I feel like the in-person analogue of where we're at right now is that we have two contributors looking at a whiteboard and making opposite educated guesses; in that scenario, I think it's better to merge the consensual parts: just removing the monkey-patching.
👍
> Same as above, I'm not convinced this would be the only way to do that? I'd rather see at least some proof-of-concept of some element of removing global state and how infer_object() is necessary to make it work.
I think this is more of a philosophical/design decision. Like I said, to me it feels like we should disconnect the data and the data-handling as they have different responsibilities. `infer_object` is a move towards such a distinction, that's why it is connected in my mind.
> To avoid repeating myself :D... The multiprocessing bugs: just a cyclic-import behavior bug and then optimizing to make sure we actually are parallelizing the right things, right?
See https://github.com/pylint-dev/astroid/issues/2048. In the current setup I don't think we can parallelise what we should. That's an issue 😄
> I confess to not even being sure how this would work. A few lines of pseudocode would help, if you're up for it. What do people want with the astroid library if they don't want inference? I know there was a comment along these lines from PCManticore in [#169 (comment)](https://github.com/pylint-dev/astroid/issues/169#issuecomment-163118560), though.
Well, in https://github.com/pylint-dev/astroid/issues/1338 I know the author was trying to replace `ast` with `astroid` in a tool they wrote but weren't able to due to the API incompatibilities. I think they will likely want to have inference but if they could just do `AstroidManager().infer_this_node_for_me(node)` that would probably also be fine for them. By keeping the API of the nodes simple, minimal and mostly in line with `ast` they would have been able to use `astroid` as a replacement.
> I think the most impactful intervention for new contributors would be continuing to use the good-first-issues label and ensuring we don't ask for big refactors along the way. (The str/repr PR in #2198 was a good experience, I felt!)
Agreed!
|
8d57ce2f3e226c2ac3cdd7f6a57dac2dd5ec5a4b
|
[
"https://github.com/pylint-dev/astroid/commit/ed843e9a5d4dfb4f5cd7885055c8b388d325a22c",
"https://github.com/pylint-dev/astroid/commit/60f02def33c977b2712f946412027b992cf8f801",
"https://github.com/pylint-dev/astroid/commit/e910116a7c2d2ce714d03748348ab07409d49f1e",
"https://github.com/pylint-dev/astroid/commit/1688426a76c8f767aafb8dff919ab38f4c76f746",
"https://github.com/pylint-dev/astroid/commit/fd17782d913df7cb706eb529a9460c2d1645e38b",
"https://github.com/pylint-dev/astroid/commit/3bc4588d3ca6d940886604aa158d037476e26d20",
"https://github.com/pylint-dev/astroid/commit/27d150b5fa897e8d356a47c957a0adaf815af342",
"https://github.com/pylint-dev/astroid/commit/c8f0d2eb1adfb863b9a7b9f2a14477153e813202",
"https://github.com/pylint-dev/astroid/commit/ceff22c1c156d2a4f94ccaaa8efe5d75d93ddb03",
"https://github.com/pylint-dev/astroid/commit/76c10af85bb21318e251ae5b54a254c2dfdbad79",
"https://github.com/pylint-dev/astroid/commit/80c0391e775554e5a1fee8cc93b00c753f6b68e5"
] | 2023-05-08T15:00:30
|
Thanks for creating the issue @degustaf
Yes, this is still a design goal that we'd want to achieve with `astroid`. There are two reasons for why this didn't happen yet, the first one being the one that you identified about not having enough time to do it. The second one is that it's a rather tricky issue, since there are various cyclic dependencies between `inference.py`, `protocols.py` and the rest of `astroid` files. We attempted to do this in the so called "2.0" branch of astroid (https://github.com/PyCQA/astroid/tree/2.0) which was an effort to reengineer most of astroid's architecture. If you look in that branch, you can see that we managed to reduce that monkeypatching quite a bit, if not all, but at this point, that branch is quite behind everything else and has a lot more changes that can't come easily in `master` without additional work.
If you're interested in helping, cherry-picking the refactoring for dropping the monkeypatch would be definitely amazing.
Can someone provide some details on this please?
astroid 2.0 branch is the default for a long time now, but Manticore's comment is quite recent.
Are there any examples before-after?
But overall I just saw "contributor friendly" tag and wanted to see if I could be of any help.
Hey @gyermolenko ! This might not be contributor friendly after all, as it requires going through https://github.com/PyCQA/astroid/tree/2.0 and bringing back into `master` the removal of monkeypatching methods. The gist of the solution is the use of single dispatch to register inference functions: https://github.com/PyCQA/astroid/blob/2.0/astroid/inference.py#L37
|
pylint-dev__astroid-2171
|
[
"679"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index d05a19c909..0a4414809d 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -19,6 +19,13 @@ Release date: TBA
Closes #1780
Refs #2140
+* Remove the ``inference`` module. Node inference methods are now in the module
+ defining the node, rather than being associated to the node afterward.
+
+ Closes #679
+
+* Move ``LookupMixIn`` to ``astroid.nodes._base_nodes`` and make it private.
+
* Reduce file system access in ``ast_from_file()``.
* Reduce time to ``import astroid`` by delaying ``astroid_bootstrapping()`` until
diff --git a/astroid/__init__.py b/astroid/__init__.py
index f3c2c79018..29e052e1f7 100644
--- a/astroid/__init__.py
+++ b/astroid/__init__.py
@@ -40,7 +40,7 @@
# isort: on
-from astroid import inference, raw_building
+from astroid import raw_building
from astroid.__pkginfo__ import __version__, version
from astroid.astroid_manager import MANAGER
from astroid.bases import BaseInstance, BoundMethod, Instance, UnboundMethod
diff --git a/astroid/bases.py b/astroid/bases.py
index 2f756a615e..bd8f6bb958 100644
--- a/astroid/bases.py
+++ b/astroid/bases.py
@@ -10,9 +10,9 @@
import collections
import collections.abc
from collections.abc import Iterable, Iterator
-from typing import TYPE_CHECKING, Any, ClassVar, Literal
+from typing import TYPE_CHECKING, Any, Literal
-from astroid import nodes
+from astroid import decorators, nodes
from astroid.const import PY310_PLUS
from astroid.context import (
CallContext,
@@ -28,7 +28,6 @@
)
from astroid.interpreter import objectmodel
from astroid.typing import (
- InferBinaryOp,
InferenceErrorInfo,
InferenceResult,
SuccessfulInferenceResult,
@@ -346,7 +345,16 @@ class Instance(BaseInstance):
def __init__(self, proxied: nodes.ClassDef | None) -> None:
super().__init__(proxied)
- infer_binary_op: ClassVar[InferBinaryOp[Instance]]
+ @decorators.yes_if_nothing_inferred
+ def infer_binary_op(
+ self,
+ opnode: nodes.AugAssign | nodes.BinOp,
+ operator: str,
+ other: InferenceResult,
+ context: InferenceContext,
+ method: SuccessfulInferenceResult,
+ ) -> Generator[InferenceResult, None, None]:
+ return method.infer_call_result(self, context)
def __repr__(self) -> str:
return "<Instance of {}.{} at 0x{}>".format(
diff --git a/astroid/constraint.py b/astroid/constraint.py
index 6e23b592f1..08bb80e3c9 100644
--- a/astroid/constraint.py
+++ b/astroid/constraint.py
@@ -8,9 +8,9 @@
import sys
from abc import ABC, abstractmethod
from collections.abc import Iterator
-from typing import Union
+from typing import TYPE_CHECKING, Union
-from astroid import bases, nodes, util
+from astroid import nodes, util
from astroid.typing import InferenceResult
if sys.version_info >= (3, 11):
@@ -18,6 +18,9 @@
else:
from typing_extensions import Self
+if TYPE_CHECKING:
+ from astroid import bases
+
_NameNodes = Union[nodes.AssignAttr, nodes.Attribute, nodes.AssignName, nodes.Name]
diff --git a/astroid/filter_statements.py b/astroid/filter_statements.py
index 7f040dd4ed..acca676170 100644
--- a/astroid/filter_statements.py
+++ b/astroid/filter_statements.py
@@ -10,10 +10,14 @@
from __future__ import annotations
+from typing import TYPE_CHECKING
+
from astroid import nodes
-from astroid.nodes import node_classes
from astroid.typing import SuccessfulInferenceResult
+if TYPE_CHECKING:
+ from astroid.nodes import _base_nodes
+
def _get_filtered_node_statements(
base_node: nodes.NodeNG, stmt_nodes: list[nodes.NodeNG]
@@ -44,7 +48,7 @@ def _get_if_statement_ancestor(node: nodes.NodeNG) -> nodes.If | None:
def _filter_stmts(
- base_node: node_classes.LookupMixIn,
+ base_node: _base_nodes.LookupMixIn,
stmts: list[SuccessfulInferenceResult],
frame: nodes.LocalsDictNodeNG,
offset: int,
diff --git a/astroid/helpers.py b/astroid/helpers.py
index ab5ada3715..3e62fb99eb 100644
--- a/astroid/helpers.py
+++ b/astroid/helpers.py
@@ -324,3 +324,25 @@ def object_len(node, context: InferenceContext | None = None):
raise AstroidTypeError(
f"'{result_of_len}' object cannot be interpreted as an integer"
)
+
+
+def _higher_function_scope(node: nodes.NodeNG) -> nodes.FunctionDef | None:
+ """Search for the first function which encloses the given
+ scope.
+
+ This can be used for looking up in that function's
+ scope, in case looking up in a lower scope for a particular
+ name fails.
+
+ :param node: A scope node.
+ :returns:
+ ``None``, if no parent function scope was found,
+ otherwise an instance of :class:`astroid.nodes.scoped_nodes.Function`,
+ which encloses the given node.
+ """
+ current = node
+ while current.parent and not isinstance(current.parent, nodes.FunctionDef):
+ current = current.parent
+ if current and current.parent:
+ return current.parent
+ return None
diff --git a/astroid/inference.py b/astroid/inference.py
deleted file mode 100644
index d7caddc575..0000000000
--- a/astroid/inference.py
+++ /dev/null
@@ -1,1293 +0,0 @@
-# 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
-
-"""This module contains a set of functions to handle inference on astroid trees."""
-
-from __future__ import annotations
-
-import ast
-import functools
-import itertools
-import operator
-import typing
-from collections.abc import Callable, Generator, Iterable, Iterator
-from typing import TYPE_CHECKING, Any, Optional, TypeVar, Union
-
-from astroid import (
- bases,
- constraint,
- decorators,
- helpers,
- nodes,
- objects,
- protocols,
- util,
-)
-from astroid.const import PY310_PLUS
-from astroid.context import (
- CallContext,
- InferenceContext,
- bind_context_to_node,
- copy_context,
-)
-from astroid.exceptions import (
- AstroidBuildingError,
- AstroidError,
- AstroidIndexError,
- AstroidTypeError,
- AstroidValueError,
- AttributeInferenceError,
- InferenceError,
- NameInferenceError,
- _NonDeducibleTypeHierarchy,
-)
-from astroid.interpreter import dunder_lookup
-from astroid.manager import AstroidManager
-from astroid.typing import (
- InferenceErrorInfo,
- InferenceResult,
- SuccessfulInferenceResult,
-)
-
-if TYPE_CHECKING:
- from astroid.objects import Property
-
-
-_T = TypeVar("_T")
-_BaseContainerT = TypeVar("_BaseContainerT", bound=nodes.BaseContainer)
-_FunctionDefT = TypeVar("_FunctionDefT", bound=nodes.FunctionDef)
-
-GetFlowFactory = typing.Callable[
- [
- InferenceResult,
- Optional[InferenceResult],
- Union[nodes.AugAssign, nodes.BinOp],
- InferenceResult,
- Optional[InferenceResult],
- InferenceContext,
- InferenceContext,
- ],
- "list[functools.partial[Generator[InferenceResult, None, None]]]",
-]
-
-# .infer method ###############################################################
-
-
-def infer_end(
- self: _T, context: InferenceContext | None = None, **kwargs: Any
-) -> Iterator[_T]:
- """Inference's end for nodes that yield themselves on inference.
-
- These are objects for which inference does not have any semantic,
- such as Module or Consts.
- """
- yield self
-
-
-# We add ignores to all assignments to methods
-# See https://github.com/python/mypy/issues/2427
-nodes.Module._infer = infer_end
-nodes.ClassDef._infer = infer_end
-nodes.Lambda._infer = infer_end # type: ignore[assignment]
-nodes.Const._infer = infer_end # type: ignore[assignment]
-nodes.Slice._infer = infer_end # type: ignore[assignment]
-nodes.TypeAlias._infer = infer_end # type: ignore[assignment]
-nodes.TypeVar._infer = infer_end # type: ignore[assignment]
-nodes.ParamSpec._infer = infer_end # type: ignore[assignment]
-nodes.TypeVarTuple._infer = infer_end # type: ignore[assignment]
-
-
-def _infer_sequence_helper(
- node: _BaseContainerT, context: InferenceContext | None = None
-) -> list[SuccessfulInferenceResult]:
- """Infer all values based on _BaseContainer.elts."""
- values = []
-
- for elt in node.elts:
- if isinstance(elt, nodes.Starred):
- starred = helpers.safe_infer(elt.value, context)
- if not starred:
- raise InferenceError(node=node, context=context)
- if not hasattr(starred, "elts"):
- raise InferenceError(node=node, context=context)
- values.extend(_infer_sequence_helper(starred))
- elif isinstance(elt, nodes.NamedExpr):
- value = helpers.safe_infer(elt.value, context)
- if not value:
- raise InferenceError(node=node, context=context)
- values.append(value)
- else:
- values.append(elt)
- return values
-
-
-@decorators.raise_if_nothing_inferred
-def infer_sequence(
- self: _BaseContainerT,
- context: InferenceContext | None = None,
- **kwargs: Any,
-) -> Iterator[_BaseContainerT]:
- has_starred_named_expr = any(
- isinstance(e, (nodes.Starred, nodes.NamedExpr)) for e in self.elts
- )
- if has_starred_named_expr:
- values = _infer_sequence_helper(self, context)
- new_seq = type(self)(
- lineno=self.lineno,
- col_offset=self.col_offset,
- parent=self.parent,
- end_lineno=self.end_lineno,
- end_col_offset=self.end_col_offset,
- )
- new_seq.postinit(values)
-
- yield new_seq
- else:
- yield self
-
-
-nodes.List._infer = infer_sequence # type: ignore[assignment]
-nodes.Tuple._infer = infer_sequence # type: ignore[assignment]
-nodes.Set._infer = infer_sequence # type: ignore[assignment]
-
-
-def infer_map(
- self: nodes.Dict, context: InferenceContext | None = None
-) -> Iterator[nodes.Dict]:
- if not any(isinstance(k, nodes.DictUnpack) for k, _ in self.items):
- yield self
- else:
- items = _infer_map(self, context)
- new_seq = type(self)(
- self.lineno,
- self.col_offset,
- self.parent,
- end_lineno=self.end_lineno,
- end_col_offset=self.end_col_offset,
- )
- new_seq.postinit(list(items.items()))
- yield new_seq
-
-
-def _update_with_replacement(
- lhs_dict: dict[SuccessfulInferenceResult, SuccessfulInferenceResult],
- rhs_dict: dict[SuccessfulInferenceResult, SuccessfulInferenceResult],
-) -> dict[SuccessfulInferenceResult, SuccessfulInferenceResult]:
- """Delete nodes that equate to duplicate keys.
-
- Since an astroid node doesn't 'equal' another node with the same value,
- this function uses the as_string method to make sure duplicate keys
- don't get through
-
- Note that both the key and the value are astroid nodes
-
- Fixes issue with DictUnpack causing duplicate keys
- in inferred Dict items
-
- :param lhs_dict: Dictionary to 'merge' nodes into
- :param rhs_dict: Dictionary with nodes to pull from
- :return : merged dictionary of nodes
- """
- combined_dict = itertools.chain(lhs_dict.items(), rhs_dict.items())
- # Overwrite keys which have the same string values
- string_map = {key.as_string(): (key, value) for key, value in combined_dict}
- # Return to dictionary
- return dict(string_map.values())
-
-
-def _infer_map(
- node: nodes.Dict, context: InferenceContext | None
-) -> dict[SuccessfulInferenceResult, SuccessfulInferenceResult]:
- """Infer all values based on Dict.items."""
- values: dict[SuccessfulInferenceResult, SuccessfulInferenceResult] = {}
- for name, value in node.items:
- if isinstance(name, nodes.DictUnpack):
- double_starred = helpers.safe_infer(value, context)
- if not double_starred:
- raise InferenceError
- if not isinstance(double_starred, nodes.Dict):
- raise InferenceError(node=node, context=context)
- unpack_items = _infer_map(double_starred, context)
- values = _update_with_replacement(values, unpack_items)
- else:
- key = helpers.safe_infer(name, context=context)
- safe_value = helpers.safe_infer(value, context=context)
- if any(not elem for elem in (key, safe_value)):
- raise InferenceError(node=node, context=context)
- # safe_value is SuccessfulInferenceResult as bool(Uninferable) == False
- values = _update_with_replacement(values, {key: safe_value})
- return values
-
-
-nodes.Dict._infer = infer_map # type: ignore[assignment]
-
-
-def _higher_function_scope(node: nodes.NodeNG) -> nodes.FunctionDef | None:
- """Search for the first function which encloses the given
- scope. This can be used for looking up in that function's
- scope, in case looking up in a lower scope for a particular
- name fails.
-
- :param node: A scope node.
- :returns:
- ``None``, if no parent function scope was found,
- otherwise an instance of :class:`astroid.nodes.scoped_nodes.Function`,
- which encloses the given node.
- """
- current = node
- while current.parent and not isinstance(current.parent, nodes.FunctionDef):
- current = current.parent
- if current and current.parent:
- return current.parent # type: ignore[no-any-return]
- return None
-
-
-def infer_name(
- self: nodes.Name | nodes.AssignName,
- context: InferenceContext | None = None,
- **kwargs: Any,
-) -> Generator[InferenceResult, None, None]:
- """Infer a Name: use name lookup rules."""
- frame, stmts = self.lookup(self.name)
- if not stmts:
- # Try to see if the name is enclosed in a nested function
- # and use the higher (first function) scope for searching.
- parent_function = _higher_function_scope(self.scope())
- if parent_function:
- _, stmts = parent_function.lookup(self.name)
-
- if not stmts:
- raise NameInferenceError(
- name=self.name, scope=self.scope(), context=context
- )
- context = copy_context(context)
- context.lookupname = self.name
- context.constraints[self.name] = constraint.get_constraints(self, frame)
-
- return bases._infer_stmts(stmts, context, frame)
-
-
-# The order of the decorators here is important
-# See https://github.com/pylint-dev/astroid/commit/0a8a75db30da060a24922e05048bc270230f5
-nodes.Name._infer = decorators.raise_if_nothing_inferred(
- decorators.path_wrapper(infer_name)
-)
-nodes.AssignName.infer_lhs = infer_name # won't work with a path wrapper
-
-
-@decorators.raise_if_nothing_inferred
-@decorators.path_wrapper
-def infer_call(
- self: nodes.Call, context: InferenceContext | None = None, **kwargs: Any
-) -> Generator[InferenceResult, None, InferenceErrorInfo]:
- """Infer a Call node by trying to guess what the function returns."""
- callcontext = copy_context(context)
- callcontext.boundnode = None
- if context is not None:
- callcontext.extra_context = _populate_context_lookup(self, context.clone())
-
- for callee in self.func.infer(context):
- if isinstance(callee, util.UninferableBase):
- yield callee
- continue
- try:
- if hasattr(callee, "infer_call_result"):
- callcontext.callcontext = CallContext(
- args=self.args, keywords=self.keywords, callee=callee
- )
- yield from callee.infer_call_result(caller=self, context=callcontext)
- except InferenceError:
- continue
- return InferenceErrorInfo(node=self, context=context)
-
-
-nodes.Call._infer = infer_call # type: ignore[assignment]
-
-
-@decorators.raise_if_nothing_inferred
-@decorators.path_wrapper
-def infer_import(
- self: nodes.Import,
- context: InferenceContext | None = None,
- asname: bool = True,
- **kwargs: Any,
-) -> Generator[nodes.Module, None, None]:
- """Infer an Import node: return the imported module/object."""
- context = context or InferenceContext()
- name = context.lookupname
- if name is None:
- raise InferenceError(node=self, context=context)
-
- try:
- if asname:
- yield self.do_import_module(self.real_name(name))
- else:
- yield self.do_import_module(name)
- except AstroidBuildingError as exc:
- raise InferenceError(node=self, context=context) from exc
-
-
-nodes.Import._infer = infer_import
-
-
-@decorators.raise_if_nothing_inferred
-@decorators.path_wrapper
-def infer_import_from(
- self: nodes.ImportFrom,
- context: InferenceContext | None = None,
- asname: bool = True,
- **kwargs: Any,
-) -> Generator[InferenceResult, None, None]:
- """Infer a ImportFrom node: return the imported module/object."""
- context = context or InferenceContext()
- name = context.lookupname
- if name is None:
- raise InferenceError(node=self, context=context)
- if asname:
- try:
- name = self.real_name(name)
- except AttributeInferenceError as exc:
- # See https://github.com/pylint-dev/pylint/issues/4692
- raise InferenceError(node=self, context=context) from exc
- try:
- module = self.do_import_module()
- except AstroidBuildingError as exc:
- raise InferenceError(node=self, context=context) from exc
-
- try:
- context = copy_context(context)
- context.lookupname = name
- stmts = module.getattr(name, ignore_locals=module is self.root())
- return bases._infer_stmts(stmts, context)
- except AttributeInferenceError as error:
- raise InferenceError(
- str(error), target=self, attribute=name, context=context
- ) from error
-
-
-nodes.ImportFrom._infer = infer_import_from # type: ignore[assignment]
-
-
-def infer_attribute(
- self: nodes.Attribute | nodes.AssignAttr,
- context: InferenceContext | None = None,
- **kwargs: Any,
-) -> Generator[InferenceResult, None, InferenceErrorInfo]:
- """Infer an Attribute node by using getattr on the associated object."""
- for owner in self.expr.infer(context):
- if isinstance(owner, util.UninferableBase):
- yield owner
- continue
-
- context = copy_context(context)
- old_boundnode = context.boundnode
- try:
- context.boundnode = owner
- if isinstance(owner, (nodes.ClassDef, bases.Instance)):
- frame = owner if isinstance(owner, nodes.ClassDef) else owner._proxied
- context.constraints[self.attrname] = constraint.get_constraints(
- self, frame=frame
- )
- yield from owner.igetattr(self.attrname, context)
- except (
- AttributeInferenceError,
- InferenceError,
- AttributeError,
- ):
- pass
- finally:
- context.boundnode = old_boundnode
- return InferenceErrorInfo(node=self, context=context)
-
-
-# The order of the decorators here is important
-# See https://github.com/pylint-dev/astroid/commit/0a8a75db30da060a24922e05048bc270230f5
-nodes.Attribute._infer = decorators.raise_if_nothing_inferred(
- decorators.path_wrapper(infer_attribute)
-)
-# won't work with a path wrapper
-nodes.AssignAttr.infer_lhs = decorators.raise_if_nothing_inferred(infer_attribute)
-
-
-@decorators.raise_if_nothing_inferred
-@decorators.path_wrapper
-def infer_global(
- self: nodes.Global, context: InferenceContext | None = None, **kwargs: Any
-) -> Generator[InferenceResult, None, None]:
- if context is None or context.lookupname is None:
- raise InferenceError(node=self, context=context)
- try:
- return bases._infer_stmts(self.root().getattr(context.lookupname), context)
- except AttributeInferenceError as error:
- raise InferenceError(
- str(error), target=self, attribute=context.lookupname, context=context
- ) from error
-
-
-nodes.Global._infer = infer_global # type: ignore[assignment]
-
-
-_SUBSCRIPT_SENTINEL = object()
-
-
-def infer_subscript(
- self: nodes.Subscript, context: InferenceContext | None = None, **kwargs: Any
-) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
- """Inference for subscripts.
-
- We're understanding if the index is a Const
- or a slice, passing the result of inference
- to the value's `getitem` method, which should
- handle each supported index type accordingly.
- """
-
- found_one = False
- for value in self.value.infer(context):
- if isinstance(value, util.UninferableBase):
- yield util.Uninferable
- return None
- for index in self.slice.infer(context):
- if isinstance(index, util.UninferableBase):
- yield util.Uninferable
- return None
-
- # Try to deduce the index value.
- index_value = _SUBSCRIPT_SENTINEL
- if value.__class__ == bases.Instance:
- index_value = index
- elif index.__class__ == bases.Instance:
- instance_as_index = helpers.class_instance_as_index(index)
- if instance_as_index:
- index_value = instance_as_index
- else:
- index_value = index
-
- if index_value is _SUBSCRIPT_SENTINEL:
- raise InferenceError(node=self, context=context)
-
- try:
- assigned = value.getitem(index_value, context)
- except (
- AstroidTypeError,
- AstroidIndexError,
- AstroidValueError,
- AttributeInferenceError,
- AttributeError,
- ) as exc:
- raise InferenceError(node=self, context=context) from exc
-
- # Prevent inferring if the inferred subscript
- # is the same as the original subscripted object.
- if self is assigned or isinstance(assigned, util.UninferableBase):
- yield util.Uninferable
- return None
- yield from assigned.infer(context)
- found_one = True
-
- if found_one:
- return InferenceErrorInfo(node=self, context=context)
- return None
-
-
-# The order of the decorators here is important
-# See https://github.com/pylint-dev/astroid/commit/0a8a75db30da060a24922e05048bc270230f5
-nodes.Subscript._infer = decorators.raise_if_nothing_inferred( # type: ignore[assignment]
- decorators.path_wrapper(infer_subscript)
-)
-nodes.Subscript.infer_lhs = decorators.raise_if_nothing_inferred(infer_subscript)
-
-
-@decorators.raise_if_nothing_inferred
-@decorators.path_wrapper
-def _infer_boolop(
- self: nodes.BoolOp, context: InferenceContext | None = None, **kwargs: Any
-) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
- """Infer a boolean operation (and / or / not).
-
- The function will calculate the boolean operation
- for all pairs generated through inference for each component
- node.
- """
- values = self.values
- if self.op == "or":
- predicate = operator.truth
- else:
- predicate = operator.not_
-
- try:
- inferred_values = [value.infer(context=context) for value in values]
- except InferenceError:
- yield util.Uninferable
- return None
-
- for pair in itertools.product(*inferred_values):
- if any(isinstance(item, util.UninferableBase) for item in pair):
- # Can't infer the final result, just yield Uninferable.
- yield util.Uninferable
- continue
-
- bool_values = [item.bool_value() for item in pair]
- if any(isinstance(item, util.UninferableBase) for item in bool_values):
- # Can't infer the final result, just yield Uninferable.
- yield util.Uninferable
- continue
-
- # Since the boolean operations are short circuited operations,
- # this code yields the first value for which the predicate is True
- # and if no value respected the predicate, then the last value will
- # be returned (or Uninferable if there was no last value).
- # This is conforming to the semantics of `and` and `or`:
- # 1 and 0 -> 1
- # 0 and 1 -> 0
- # 1 or 0 -> 1
- # 0 or 1 -> 1
- value = util.Uninferable
- for value, bool_value in zip(pair, bool_values):
- if predicate(bool_value):
- yield value
- break
- else:
- yield value
-
- return InferenceErrorInfo(node=self, context=context)
-
-
-nodes.BoolOp._infer = _infer_boolop
-
-
-# UnaryOp, BinOp and AugAssign inferences
-
-
-def _filter_operation_errors(
- self: _T,
- infer_callable: Callable[
- [_T, InferenceContext | None],
- Generator[InferenceResult | util.BadOperationMessage, None, None],
- ],
- context: InferenceContext | None,
- error: type[util.BadOperationMessage],
-) -> Generator[InferenceResult, None, None]:
- for result in infer_callable(self, context):
- if isinstance(result, error):
- # For the sake of .infer(), we don't care about operation
- # errors, which is the job of pylint. So return something
- # which shows that we can't infer the result.
- yield util.Uninferable
- else:
- yield result
-
-
-def _infer_unaryop(
- self: nodes.UnaryOp, context: InferenceContext | None = None
-) -> Generator[InferenceResult | util.BadUnaryOperationMessage, None, None]:
- """Infer what an UnaryOp should return when evaluated."""
- for operand in self.operand.infer(context):
- try:
- yield operand.infer_unary_op(self.op)
- except TypeError as exc:
- # The operand doesn't support this operation.
- yield util.BadUnaryOperationMessage(operand, self.op, exc)
- except AttributeError as exc:
- meth = protocols.UNARY_OP_METHOD[self.op]
- if meth is None:
- # `not node`. Determine node's boolean
- # value and negate its result, unless it is
- # Uninferable, which will be returned as is.
- bool_value = operand.bool_value()
- if not isinstance(bool_value, util.UninferableBase):
- yield nodes.const_factory(not bool_value)
- else:
- yield util.Uninferable
- else:
- if not isinstance(operand, (bases.Instance, nodes.ClassDef)):
- # The operation was used on something which
- # doesn't support it.
- yield util.BadUnaryOperationMessage(operand, self.op, exc)
- continue
-
- try:
- try:
- methods = dunder_lookup.lookup(operand, meth)
- except AttributeInferenceError:
- yield util.BadUnaryOperationMessage(operand, self.op, exc)
- continue
-
- meth = methods[0]
- inferred = next(meth.infer(context=context), None)
- if (
- isinstance(inferred, util.UninferableBase)
- or not inferred.callable()
- ):
- continue
-
- context = copy_context(context)
- context.boundnode = operand
- context.callcontext = CallContext(args=[], callee=inferred)
-
- call_results = inferred.infer_call_result(self, context=context)
- result = next(call_results, None)
- if result is None:
- # Failed to infer, return the same type.
- yield operand
- else:
- yield result
- except AttributeInferenceError as inner_exc:
- # The unary operation special method was not found.
- yield util.BadUnaryOperationMessage(operand, self.op, inner_exc)
- except InferenceError:
- yield util.Uninferable
-
-
-@decorators.raise_if_nothing_inferred
-@decorators.path_wrapper
-def infer_unaryop(
- self: nodes.UnaryOp, context: InferenceContext | None = None, **kwargs: Any
-) -> Generator[InferenceResult, None, InferenceErrorInfo]:
- """Infer what an UnaryOp should return when evaluated."""
- yield from _filter_operation_errors(
- self, _infer_unaryop, context, util.BadUnaryOperationMessage
- )
- return InferenceErrorInfo(node=self, context=context)
-
-
-nodes.UnaryOp._infer_unaryop = _infer_unaryop
-nodes.UnaryOp._infer = infer_unaryop
-
-
-def _is_not_implemented(const) -> bool:
- """Check if the given const node is NotImplemented."""
- return isinstance(const, nodes.Const) and const.value is NotImplemented
-
-
-def _infer_old_style_string_formatting(
- instance: nodes.Const, other: nodes.NodeNG, context: InferenceContext
-) -> tuple[util.UninferableBase | nodes.Const]:
- """Infer the result of '"string" % ...'.
-
- TODO: Instead of returning Uninferable we should rely
- on the call to '%' to see if the result is actually uninferable.
- """
- if isinstance(other, nodes.Tuple):
- if util.Uninferable in other.elts:
- return (util.Uninferable,)
- inferred_positional = [helpers.safe_infer(i, context) for i in other.elts]
- if all(isinstance(i, nodes.Const) for i in inferred_positional):
- values = tuple(i.value for i in inferred_positional)
- else:
- values = None
- elif isinstance(other, nodes.Dict):
- values: dict[Any, Any] = {}
- for pair in other.items:
- key = helpers.safe_infer(pair[0], context)
- if not isinstance(key, nodes.Const):
- return (util.Uninferable,)
- value = helpers.safe_infer(pair[1], context)
- if not isinstance(value, nodes.Const):
- return (util.Uninferable,)
- values[key.value] = value.value
- elif isinstance(other, nodes.Const):
- values = other.value
- else:
- return (util.Uninferable,)
-
- try:
- return (nodes.const_factory(instance.value % values),)
- except (TypeError, KeyError, ValueError):
- return (util.Uninferable,)
-
-
-def _invoke_binop_inference(
- instance: InferenceResult,
- opnode: nodes.AugAssign | nodes.BinOp,
- op: str,
- other: InferenceResult,
- context: InferenceContext,
- method_name: str,
-) -> Generator[InferenceResult, None, None]:
- """Invoke binary operation inference on the given instance."""
- methods = dunder_lookup.lookup(instance, method_name)
- context = bind_context_to_node(context, instance)
- method = methods[0]
- context.callcontext.callee = method
-
- if (
- isinstance(instance, nodes.Const)
- and isinstance(instance.value, str)
- and op == "%"
- ):
- return iter(_infer_old_style_string_formatting(instance, other, context))
-
- try:
- inferred = next(method.infer(context=context))
- except StopIteration as e:
- raise InferenceError(node=method, context=context) from e
- if isinstance(inferred, util.UninferableBase):
- raise InferenceError
- if not isinstance(
- instance, (nodes.Const, nodes.Tuple, nodes.List, nodes.ClassDef, bases.Instance)
- ):
- raise InferenceError # pragma: no cover # Used as a failsafe
- return instance.infer_binary_op(opnode, op, other, context, inferred)
-
-
-def _aug_op(
- instance: InferenceResult,
- opnode: nodes.AugAssign,
- op: str,
- other: InferenceResult,
- context: InferenceContext,
- reverse: bool = False,
-) -> functools.partial[Generator[InferenceResult, None, None]]:
- """Get an inference callable for an augmented binary operation."""
- method_name = protocols.AUGMENTED_OP_METHOD[op]
- return functools.partial(
- _invoke_binop_inference,
- instance=instance,
- op=op,
- opnode=opnode,
- other=other,
- context=context,
- method_name=method_name,
- )
-
-
-def _bin_op(
- instance: InferenceResult,
- opnode: nodes.AugAssign | nodes.BinOp,
- op: str,
- other: InferenceResult,
- context: InferenceContext,
- reverse: bool = False,
-) -> functools.partial[Generator[InferenceResult, None, None]]:
- """Get an inference callable for a normal binary operation.
-
- If *reverse* is True, then the reflected method will be used instead.
- """
- if reverse:
- method_name = protocols.REFLECTED_BIN_OP_METHOD[op]
- else:
- method_name = protocols.BIN_OP_METHOD[op]
- return functools.partial(
- _invoke_binop_inference,
- instance=instance,
- op=op,
- opnode=opnode,
- other=other,
- context=context,
- method_name=method_name,
- )
-
-
-def _bin_op_or_union_type(
- left: bases.UnionType | nodes.ClassDef | nodes.Const,
- right: bases.UnionType | nodes.ClassDef | nodes.Const,
-) -> Generator[InferenceResult, None, None]:
- """Create a new UnionType instance for binary or, e.g. int | str."""
- yield bases.UnionType(left, right)
-
-
-def _get_binop_contexts(context, left, right):
- """Get contexts for binary operations.
-
- This will return two inference contexts, the first one
- for x.__op__(y), the other one for y.__rop__(x), where
- only the arguments are inversed.
- """
- # The order is important, since the first one should be
- # left.__op__(right).
- for arg in (right, left):
- new_context = context.clone()
- new_context.callcontext = CallContext(args=[arg])
- new_context.boundnode = None
- yield new_context
-
-
-def _same_type(type1, type2) -> bool:
- """Check if type1 is the same as type2."""
- return type1.qname() == type2.qname()
-
-
-def _get_binop_flow(
- left: InferenceResult,
- left_type: InferenceResult | None,
- binary_opnode: nodes.AugAssign | nodes.BinOp,
- right: InferenceResult,
- right_type: InferenceResult | None,
- context: InferenceContext,
- reverse_context: InferenceContext,
-) -> list[functools.partial[Generator[InferenceResult, None, None]]]:
- """Get the flow for binary operations.
-
- The rules are a bit messy:
-
- * if left and right have the same type, then only one
- method will be called, left.__op__(right)
- * if left and right are unrelated typewise, then first
- left.__op__(right) is tried and if this does not exist
- or returns NotImplemented, then right.__rop__(left) is tried.
- * if left is a subtype of right, then only left.__op__(right)
- is tried.
- * if left is a supertype of right, then right.__rop__(left)
- is first tried and then left.__op__(right)
- """
- op = binary_opnode.op
- if _same_type(left_type, right_type):
- methods = [_bin_op(left, binary_opnode, op, right, context)]
- elif helpers.is_subtype(left_type, right_type):
- methods = [_bin_op(left, binary_opnode, op, right, context)]
- elif helpers.is_supertype(left_type, right_type):
- methods = [
- _bin_op(right, binary_opnode, op, left, reverse_context, reverse=True),
- _bin_op(left, binary_opnode, op, right, context),
- ]
- else:
- methods = [
- _bin_op(left, binary_opnode, op, right, context),
- _bin_op(right, binary_opnode, op, left, reverse_context, reverse=True),
- ]
-
- if (
- PY310_PLUS
- and op == "|"
- and (
- isinstance(left, (bases.UnionType, nodes.ClassDef))
- or isinstance(left, nodes.Const)
- and left.value is None
- )
- and (
- isinstance(right, (bases.UnionType, nodes.ClassDef))
- or isinstance(right, nodes.Const)
- and right.value is None
- )
- ):
- methods.extend([functools.partial(_bin_op_or_union_type, left, right)])
- return methods
-
-
-def _get_aug_flow(
- left: InferenceResult,
- left_type: InferenceResult | None,
- aug_opnode: nodes.AugAssign,
- right: InferenceResult,
- right_type: InferenceResult | None,
- context: InferenceContext,
- reverse_context: InferenceContext,
-) -> list[functools.partial[Generator[InferenceResult, None, None]]]:
- """Get the flow for augmented binary operations.
-
- The rules are a bit messy:
-
- * if left and right have the same type, then left.__augop__(right)
- is first tried and then left.__op__(right).
- * if left and right are unrelated typewise, then
- left.__augop__(right) is tried, then left.__op__(right)
- is tried and then right.__rop__(left) is tried.
- * if left is a subtype of right, then left.__augop__(right)
- is tried and then left.__op__(right).
- * if left is a supertype of right, then left.__augop__(right)
- is tried, then right.__rop__(left) and then
- left.__op__(right)
- """
- bin_op = aug_opnode.op.strip("=")
- aug_op = aug_opnode.op
- if _same_type(left_type, right_type):
- methods = [
- _aug_op(left, aug_opnode, aug_op, right, context),
- _bin_op(left, aug_opnode, bin_op, right, context),
- ]
- elif helpers.is_subtype(left_type, right_type):
- methods = [
- _aug_op(left, aug_opnode, aug_op, right, context),
- _bin_op(left, aug_opnode, bin_op, right, context),
- ]
- elif helpers.is_supertype(left_type, right_type):
- methods = [
- _aug_op(left, aug_opnode, aug_op, right, context),
- _bin_op(right, aug_opnode, bin_op, left, reverse_context, reverse=True),
- _bin_op(left, aug_opnode, bin_op, right, context),
- ]
- else:
- methods = [
- _aug_op(left, aug_opnode, aug_op, right, context),
- _bin_op(left, aug_opnode, bin_op, right, context),
- _bin_op(right, aug_opnode, bin_op, left, reverse_context, reverse=True),
- ]
- return methods
-
-
-def _infer_binary_operation(
- left: InferenceResult,
- right: InferenceResult,
- binary_opnode: nodes.AugAssign | nodes.BinOp,
- context: InferenceContext,
- flow_factory: GetFlowFactory,
-) -> Generator[InferenceResult | util.BadBinaryOperationMessage, None, None]:
- """Infer a binary operation between a left operand and a right operand.
-
- This is used by both normal binary operations and augmented binary
- operations, the only difference is the flow factory used.
- """
-
- context, reverse_context = _get_binop_contexts(context, left, right)
- left_type = helpers.object_type(left)
- right_type = helpers.object_type(right)
- methods = flow_factory(
- left, left_type, binary_opnode, right, right_type, context, reverse_context
- )
- for method in methods:
- try:
- results = list(method())
- except AttributeError:
- continue
- except AttributeInferenceError:
- continue
- except InferenceError:
- yield util.Uninferable
- return
- else:
- if any(isinstance(result, util.UninferableBase) for result in results):
- yield util.Uninferable
- return
-
- if all(map(_is_not_implemented, results)):
- continue
- not_implemented = sum(
- 1 for result in results if _is_not_implemented(result)
- )
- if not_implemented and not_implemented != len(results):
- # Can't infer yet what this is.
- yield util.Uninferable
- return
-
- yield from results
- return
- # The operation doesn't seem to be supported so let the caller know about it
- yield util.BadBinaryOperationMessage(left_type, binary_opnode.op, right_type)
-
-
-def _infer_binop(
- self: nodes.BinOp, context: InferenceContext | None = None
-) -> Generator[InferenceResult | util.BadBinaryOperationMessage, None, None]:
- """Binary operation inference logic."""
- left = self.left
- right = self.right
-
- # we use two separate contexts for evaluating lhs and rhs because
- # 1. evaluating lhs may leave some undesired entries in context.path
- # which may not let us infer right value of rhs
- context = context or InferenceContext()
- lhs_context = copy_context(context)
- rhs_context = copy_context(context)
- lhs_iter = left.infer(context=lhs_context)
- rhs_iter = right.infer(context=rhs_context)
- for lhs, rhs in itertools.product(lhs_iter, rhs_iter):
- if any(isinstance(value, util.UninferableBase) for value in (rhs, lhs)):
- # Don't know how to process this.
- yield util.Uninferable
- return
-
- try:
- yield from _infer_binary_operation(lhs, rhs, self, context, _get_binop_flow)
- except _NonDeducibleTypeHierarchy:
- yield util.Uninferable
-
-
-@decorators.yes_if_nothing_inferred
-@decorators.path_wrapper
-def infer_binop(
- self: nodes.BinOp, context: InferenceContext | None = None, **kwargs: Any
-) -> Generator[InferenceResult, None, None]:
- return _filter_operation_errors(
- self, _infer_binop, context, util.BadBinaryOperationMessage
- )
-
-
-nodes.BinOp._infer_binop = _infer_binop
-nodes.BinOp._infer = infer_binop
-
-COMPARE_OPS: dict[str, Callable[[Any, Any], bool]] = {
- "==": operator.eq,
- "!=": operator.ne,
- "<": operator.lt,
- "<=": operator.le,
- ">": operator.gt,
- ">=": operator.ge,
- "in": lambda a, b: a in b,
- "not in": lambda a, b: a not in b,
-}
-UNINFERABLE_OPS = {
- "is",
- "is not",
-}
-
-
-def _to_literal(node: SuccessfulInferenceResult) -> Any:
- # Can raise SyntaxError or ValueError from ast.literal_eval
- # Can raise AttributeError from node.as_string() as not all nodes have a visitor
- # Is this the stupidest idea or the simplest idea?
- return ast.literal_eval(node.as_string())
-
-
-def _do_compare(
- left_iter: Iterable[InferenceResult], op: str, right_iter: Iterable[InferenceResult]
-) -> bool | util.UninferableBase:
- """
- If all possible combinations are either True or False, return that:
- >>> _do_compare([1, 2], '<=', [3, 4])
- True
- >>> _do_compare([1, 2], '==', [3, 4])
- False
-
- If any item is uninferable, or if some combinations are True and some
- are False, return Uninferable:
- >>> _do_compare([1, 3], '<=', [2, 4])
- util.Uninferable
- """
- retval: bool | None = None
- if op in UNINFERABLE_OPS:
- return util.Uninferable
- op_func = COMPARE_OPS[op]
-
- for left, right in itertools.product(left_iter, right_iter):
- if isinstance(left, util.UninferableBase) or isinstance(
- right, util.UninferableBase
- ):
- return util.Uninferable
-
- try:
- left, right = _to_literal(left), _to_literal(right)
- except (SyntaxError, ValueError, AttributeError):
- return util.Uninferable
-
- try:
- expr = op_func(left, right)
- except TypeError as exc:
- raise AstroidTypeError from exc
-
- if retval is None:
- retval = expr
- elif retval != expr:
- return util.Uninferable
- # (or both, but "True | False" is basically the same)
-
- assert retval is not None
- return retval # it was all the same value
-
-
-def _infer_compare(
- self: nodes.Compare, context: InferenceContext | None = None, **kwargs: Any
-) -> Generator[nodes.Const | util.UninferableBase, None, None]:
- """Chained comparison inference logic."""
- retval: bool | util.UninferableBase = True
-
- ops = self.ops
- left_node = self.left
- lhs = list(left_node.infer(context=context))
- # should we break early if first element is uninferable?
- for op, right_node in ops:
- # eagerly evaluate rhs so that values can be re-used as lhs
- rhs = list(right_node.infer(context=context))
- try:
- retval = _do_compare(lhs, op, rhs)
- except AstroidTypeError:
- retval = util.Uninferable
- break
- if retval is not True:
- break # short-circuit
- lhs = rhs # continue
- if retval is util.Uninferable:
- yield retval # type: ignore[misc]
- else:
- yield nodes.Const(retval)
-
-
-nodes.Compare._infer = _infer_compare # type: ignore[assignment]
-
-
-def _infer_augassign(
- self: nodes.AugAssign, context: InferenceContext | None = None
-) -> Generator[InferenceResult | util.BadBinaryOperationMessage, None, None]:
- """Inference logic for augmented binary operations."""
- context = context or InferenceContext()
-
- rhs_context = context.clone()
-
- lhs_iter = self.target.infer_lhs(context=context)
- rhs_iter = self.value.infer(context=rhs_context)
- for lhs, rhs in itertools.product(lhs_iter, rhs_iter):
- if any(isinstance(value, util.UninferableBase) for value in (rhs, lhs)):
- # Don't know how to process this.
- yield util.Uninferable
- return
-
- try:
- yield from _infer_binary_operation(
- left=lhs,
- right=rhs,
- binary_opnode=self,
- context=context,
- flow_factory=_get_aug_flow,
- )
- except _NonDeducibleTypeHierarchy:
- yield util.Uninferable
-
-
-@decorators.raise_if_nothing_inferred
-@decorators.path_wrapper
-def infer_augassign(
- self: nodes.AugAssign, context: InferenceContext | None = None, **kwargs: Any
-) -> Generator[InferenceResult, None, None]:
- return _filter_operation_errors(
- self, _infer_augassign, context, util.BadBinaryOperationMessage
- )
-
-
-nodes.AugAssign._infer_augassign = _infer_augassign
-nodes.AugAssign._infer = infer_augassign
-
-# End of binary operation inference.
-
-
-@decorators.raise_if_nothing_inferred
-def infer_arguments(
- self: nodes.Arguments, context: InferenceContext | None = None, **kwargs: Any
-) -> Generator[InferenceResult, None, None]:
- if context is None or context.lookupname is None:
- raise InferenceError(node=self, context=context)
- return protocols._arguments_infer_argname(self, context.lookupname, context)
-
-
-nodes.Arguments._infer = infer_arguments # type: ignore[assignment]
-
-
-@decorators.raise_if_nothing_inferred
-@decorators.path_wrapper
-def infer_assign(
- self: nodes.AssignName | nodes.AssignAttr,
- context: InferenceContext | None = None,
- **kwargs: Any,
-) -> Generator[InferenceResult, None, None]:
- """Infer a AssignName/AssignAttr: need to inspect the RHS part of the
- assign node.
- """
- if isinstance(self.parent, nodes.AugAssign):
- return self.parent.infer(context)
-
- stmts = list(self.assigned_stmts(context=context))
- return bases._infer_stmts(stmts, context)
-
-
-nodes.AssignName._infer = infer_assign
-nodes.AssignAttr._infer = infer_assign
-
-
-@decorators.raise_if_nothing_inferred
-@decorators.path_wrapper
-def infer_empty_node(
- self: nodes.EmptyNode, context: InferenceContext | None = None, **kwargs: Any
-) -> Generator[InferenceResult, None, None]:
- if not self.has_underlying_object():
- yield util.Uninferable
- else:
- try:
- yield from AstroidManager().infer_ast_from_something(
- self.object, context=context
- )
- except AstroidError:
- yield util.Uninferable
-
-
-nodes.EmptyNode._infer = infer_empty_node # type: ignore[assignment]
-
-
-def _populate_context_lookup(call: nodes.Call, context: InferenceContext | None):
- # Allows context to be saved for later
- # for inference inside a function
- context_lookup: dict[InferenceResult, InferenceContext] = {}
- if context is None:
- return context_lookup
- for arg in call.args:
- if isinstance(arg, nodes.Starred):
- context_lookup[arg.value] = context
- else:
- context_lookup[arg] = context
- keywords = call.keywords if call.keywords is not None else []
- for keyword in keywords:
- context_lookup[keyword.value] = context
- return context_lookup
-
-
-@decorators.raise_if_nothing_inferred
-def infer_ifexp(
- self: nodes.IfExp, context: InferenceContext | None = None, **kwargs: Any
-) -> Generator[InferenceResult, None, None]:
- """Support IfExp inference.
-
- If we can't infer the truthiness of the condition, we default
- to inferring both branches. Otherwise, we infer either branch
- depending on the condition.
- """
- both_branches = False
- # We use two separate contexts for evaluating lhs and rhs because
- # evaluating lhs may leave some undesired entries in context.path
- # which may not let us infer right value of rhs.
-
- context = context or InferenceContext()
- lhs_context = copy_context(context)
- rhs_context = copy_context(context)
- try:
- test = next(self.test.infer(context=context.clone()))
- except (InferenceError, StopIteration):
- both_branches = True
- else:
- if not isinstance(test, util.UninferableBase):
- if test.bool_value():
- yield from self.body.infer(context=lhs_context)
- else:
- yield from self.orelse.infer(context=rhs_context)
- else:
- both_branches = True
- if both_branches:
- yield from self.body.infer(context=lhs_context)
- yield from self.orelse.infer(context=rhs_context)
-
-
-nodes.IfExp._infer = infer_ifexp # type: ignore[assignment]
-
-
-def infer_functiondef(
- self: _FunctionDefT, context: InferenceContext | None = None, **kwargs: Any
-) -> Generator[Property | _FunctionDefT, None, InferenceErrorInfo]:
- if not self.decorators or not bases._is_property(self):
- yield self
- return InferenceErrorInfo(node=self, context=context)
-
- # When inferring a property, we instantiate a new `objects.Property` object,
- # which in turn, because it inherits from `FunctionDef`, sets itself in the locals
- # of the wrapping frame. This means that every time we infer a property, the locals
- # are mutated with a new instance of the property. To avoid this, we detect this
- # scenario and avoid passing the `parent` argument to the constructor.
- parent_frame = self.parent.frame()
- property_already_in_parent_locals = self.name in parent_frame.locals and any(
- isinstance(val, objects.Property) for val in parent_frame.locals[self.name]
- )
- # We also don't want to pass parent if the definition is within a Try node
- if isinstance(self.parent, (nodes.TryExcept, nodes.TryFinally, nodes.If)):
- property_already_in_parent_locals = True
-
- prop_func = objects.Property(
- function=self,
- name=self.name,
- lineno=self.lineno,
- parent=self.parent if not property_already_in_parent_locals else None,
- col_offset=self.col_offset,
- )
- if property_already_in_parent_locals:
- prop_func.parent = self.parent
- prop_func.postinit(body=[], args=self.args, doc_node=self.doc_node)
- yield prop_func
- return InferenceErrorInfo(node=self, context=context)
-
-
-nodes.FunctionDef._infer = infer_functiondef
diff --git a/astroid/manager.py b/astroid/manager.py
index 2df270f1ac..2d0903fe53 100644
--- a/astroid/manager.py
+++ b/astroid/manager.py
@@ -434,7 +434,7 @@ def clear_cache(self) -> None:
# pylint: disable=import-outside-toplevel
from astroid.inference_tip import clear_inference_tip_cache
from astroid.interpreter.objectmodel import ObjectModel
- from astroid.nodes.node_classes import LookupMixIn
+ from astroid.nodes._base_nodes import LookupMixIn
from astroid.nodes.scoped_nodes import ClassDef
clear_inference_tip_cache()
diff --git a/astroid/node_classes.py b/astroid/node_classes.py
index 980fa0a90b..7f3614e46b 100644
--- a/astroid/node_classes.py
+++ b/astroid/node_classes.py
@@ -48,7 +48,6 @@
JoinedStr,
Keyword,
List,
- LookupMixIn,
Match,
MatchAs,
MatchCase,
diff --git a/astroid/nodes/__init__.py b/astroid/nodes/__init__.py
index 84fcb521f2..44712f1074 100644
--- a/astroid/nodes/__init__.py
+++ b/astroid/nodes/__init__.py
@@ -11,10 +11,6 @@
"""
# Nodes not present in the builtin ast module: DictUnpack, Unknown, and EvaluatedObject.
-
-# This is the only node we re-export from the private _base_nodes module. This
-# is because it was originally part of the public API and hasn't been deprecated.
-from astroid.nodes._base_nodes import Statement
from astroid.nodes.node_classes import (
CONST_CLS,
AnnAssign,
@@ -115,10 +111,7 @@
)
from astroid.nodes.utils import Position
-_BaseContainer = BaseContainer # TODO Remove for astroid 3.0
-
ALL_NODE_CLASSES = (
- _BaseContainer,
BaseContainer,
AnnAssign,
Arguments,
@@ -223,6 +216,7 @@
"Attribute",
"AugAssign",
"Await",
+ "BaseContainer",
"BinOp",
"BoolOp",
"Break",
@@ -288,7 +282,6 @@
"SetComp",
"Slice",
"Starred",
- "Statement",
"Subscript",
"TryExcept",
"TryFinally",
diff --git a/astroid/nodes/_base_nodes.py b/astroid/nodes/_base_nodes.py
index 15cc6a9ad1..d6d80986a9 100644
--- a/astroid/nodes/_base_nodes.py
+++ b/astroid/nodes/_base_nodes.py
@@ -10,15 +10,42 @@
from __future__ import annotations
import itertools
-from collections.abc import Iterator
-from functools import cached_property
-from typing import TYPE_CHECKING, ClassVar
-
-from astroid.exceptions import AttributeInferenceError
+from collections.abc import Generator, Iterator
+from functools import cached_property, lru_cache, partial
+from typing import TYPE_CHECKING, Any, Callable, ClassVar, Optional, Union
+
+from astroid import bases, decorators, nodes, util
+from astroid.const import PY310_PLUS
+from astroid.context import (
+ CallContext,
+ InferenceContext,
+ bind_context_to_node,
+ copy_context,
+)
+from astroid.exceptions import (
+ AttributeInferenceError,
+ InferenceError,
+ NameInferenceError,
+)
+from astroid.interpreter import dunder_lookup
from astroid.nodes.node_ng import NodeNG
+from astroid.typing import InferenceErrorInfo, InferenceResult
if TYPE_CHECKING:
- from astroid import nodes
+ from astroid.nodes.node_classes import AssignedStmtsPossibleNode, LocalsDictNodeNG
+
+ GetFlowFactory = Callable[
+ [
+ InferenceResult,
+ Optional[InferenceResult],
+ Union[nodes.AugAssign, nodes.BinOp],
+ InferenceResult,
+ Optional[InferenceResult],
+ InferenceContext,
+ InferenceContext,
+ ],
+ list[partial[Generator[InferenceResult, None, None]]],
+ ]
class Statement(NodeNG):
@@ -223,3 +250,526 @@ def _elsed_block_range(
return lineno, orelse[-1].tolineno
return lineno, orelse[0].fromlineno - 1
return lineno, last or self.tolineno
+
+
+class LookupMixIn(NodeNG):
+ """Mixin to look up a name in the right scope."""
+
+ @lru_cache # noqa
+ def lookup(self, name: str) -> tuple[LocalsDictNodeNG, list[NodeNG]]:
+ """Lookup where the given variable is assigned.
+
+ The lookup starts from self's scope. If self is not a frame itself
+ and the name is found in the inner frame locals, statements will be
+ filtered to remove ignorable statements according to self's location.
+
+ :param name: The name of the variable to find assignments for.
+
+ :returns: The scope node and the list of assignments associated to the
+ given name according to the scope where it has been found (locals,
+ globals or builtin).
+ """
+ return self.scope().scope_lookup(self, name)
+
+ def ilookup(self, name):
+ """Lookup the inferred values of the given variable.
+
+ :param name: The variable name to find values for.
+ :type name: str
+
+ :returns: The inferred values of the statements returned from
+ :meth:`lookup`.
+ :rtype: iterable
+ """
+ frame, stmts = self.lookup(name)
+ context = InferenceContext()
+ return bases._infer_stmts(stmts, context, frame)
+
+
+def _reflected_name(name) -> str:
+ return "__r" + name[2:]
+
+
+def _augmented_name(name) -> str:
+ return "__i" + name[2:]
+
+
+BIN_OP_METHOD = {
+ "+": "__add__",
+ "-": "__sub__",
+ "/": "__truediv__",
+ "//": "__floordiv__",
+ "*": "__mul__",
+ "**": "__pow__",
+ "%": "__mod__",
+ "&": "__and__",
+ "|": "__or__",
+ "^": "__xor__",
+ "<<": "__lshift__",
+ ">>": "__rshift__",
+ "@": "__matmul__",
+}
+
+REFLECTED_BIN_OP_METHOD = {
+ key: _reflected_name(value) for (key, value) in BIN_OP_METHOD.items()
+}
+AUGMENTED_OP_METHOD = {
+ key + "=": _augmented_name(value) for (key, value) in BIN_OP_METHOD.items()
+}
+
+
+class OperatorNode(NodeNG):
+ @staticmethod
+ def _filter_operation_errors(
+ infer_callable: Callable[
+ [InferenceContext | None],
+ Generator[InferenceResult | util.BadOperationMessage, None, None],
+ ],
+ context: InferenceContext | None,
+ error: type[util.BadOperationMessage],
+ ) -> Generator[InferenceResult, None, None]:
+ for result in infer_callable(context):
+ if isinstance(result, error):
+ # For the sake of .infer(), we don't care about operation
+ # errors, which is the job of pylint. So return something
+ # which shows that we can't infer the result.
+ yield util.Uninferable
+ else:
+ yield result
+
+ @staticmethod
+ def _is_not_implemented(const) -> bool:
+ """Check if the given const node is NotImplemented."""
+ return isinstance(const, nodes.Const) and const.value is NotImplemented
+
+ @staticmethod
+ def _infer_old_style_string_formatting(
+ instance: nodes.Const, other: nodes.NodeNG, context: InferenceContext
+ ) -> tuple[util.UninferableBase | nodes.Const]:
+ """Infer the result of '"string" % ...'.
+
+ TODO: Instead of returning Uninferable we should rely
+ on the call to '%' to see if the result is actually uninferable.
+ """
+ from astroid import helpers # pylint: disable=import-outside-toplevel
+
+ if isinstance(other, nodes.Tuple):
+ if util.Uninferable in other.elts:
+ return (util.Uninferable,)
+ inferred_positional = [helpers.safe_infer(i, context) for i in other.elts]
+ if all(isinstance(i, nodes.Const) for i in inferred_positional):
+ values = tuple(i.value for i in inferred_positional)
+ else:
+ values = None
+ elif isinstance(other, nodes.Dict):
+ values: dict[Any, Any] = {}
+ for pair in other.items:
+ key = helpers.safe_infer(pair[0], context)
+ if not isinstance(key, nodes.Const):
+ return (util.Uninferable,)
+ value = helpers.safe_infer(pair[1], context)
+ if not isinstance(value, nodes.Const):
+ return (util.Uninferable,)
+ values[key.value] = value.value
+ elif isinstance(other, nodes.Const):
+ values = other.value
+ else:
+ return (util.Uninferable,)
+
+ try:
+ return (nodes.const_factory(instance.value % values),)
+ except (TypeError, KeyError, ValueError):
+ return (util.Uninferable,)
+
+ @staticmethod
+ def _invoke_binop_inference(
+ instance: InferenceResult,
+ opnode: nodes.AugAssign | nodes.BinOp,
+ op: str,
+ other: InferenceResult,
+ context: InferenceContext,
+ method_name: str,
+ ) -> Generator[InferenceResult, None, None]:
+ """Invoke binary operation inference on the given instance."""
+ methods = dunder_lookup.lookup(instance, method_name)
+ context = bind_context_to_node(context, instance)
+ method = methods[0]
+ context.callcontext.callee = method
+
+ if (
+ isinstance(instance, nodes.Const)
+ and isinstance(instance.value, str)
+ and op == "%"
+ ):
+ return iter(
+ OperatorNode._infer_old_style_string_formatting(
+ instance, other, context
+ )
+ )
+
+ try:
+ inferred = next(method.infer(context=context))
+ except StopIteration as e:
+ raise InferenceError(node=method, context=context) from e
+ if isinstance(inferred, util.UninferableBase):
+ raise InferenceError
+ if not isinstance(
+ instance,
+ (nodes.Const, nodes.Tuple, nodes.List, nodes.ClassDef, bases.Instance),
+ ):
+ raise InferenceError # pragma: no cover # Used as a failsafe
+ return instance.infer_binary_op(opnode, op, other, context, inferred)
+
+ @staticmethod
+ def _aug_op(
+ instance: InferenceResult,
+ opnode: nodes.AugAssign,
+ op: str,
+ other: InferenceResult,
+ context: InferenceContext,
+ reverse: bool = False,
+ ) -> partial[Generator[InferenceResult, None, None]]:
+ """Get an inference callable for an augmented binary operation."""
+ method_name = AUGMENTED_OP_METHOD[op]
+ return partial(
+ OperatorNode._invoke_binop_inference,
+ instance=instance,
+ op=op,
+ opnode=opnode,
+ other=other,
+ context=context,
+ method_name=method_name,
+ )
+
+ @staticmethod
+ def _bin_op(
+ instance: InferenceResult,
+ opnode: nodes.AugAssign | nodes.BinOp,
+ op: str,
+ other: InferenceResult,
+ context: InferenceContext,
+ reverse: bool = False,
+ ) -> partial[Generator[InferenceResult, None, None]]:
+ """Get an inference callable for a normal binary operation.
+
+ If *reverse* is True, then the reflected method will be used instead.
+ """
+ if reverse:
+ method_name = REFLECTED_BIN_OP_METHOD[op]
+ else:
+ method_name = BIN_OP_METHOD[op]
+ return partial(
+ OperatorNode._invoke_binop_inference,
+ instance=instance,
+ op=op,
+ opnode=opnode,
+ other=other,
+ context=context,
+ method_name=method_name,
+ )
+
+ @staticmethod
+ def _bin_op_or_union_type(
+ left: bases.UnionType | nodes.ClassDef | nodes.Const,
+ right: bases.UnionType | nodes.ClassDef | nodes.Const,
+ ) -> Generator[InferenceResult, None, None]:
+ """Create a new UnionType instance for binary or, e.g. int | str."""
+ yield bases.UnionType(left, right)
+
+ @staticmethod
+ def _get_binop_contexts(context, left, right):
+ """Get contexts for binary operations.
+
+ This will return two inference contexts, the first one
+ for x.__op__(y), the other one for y.__rop__(x), where
+ only the arguments are inversed.
+ """
+ # The order is important, since the first one should be
+ # left.__op__(right).
+ for arg in (right, left):
+ new_context = context.clone()
+ new_context.callcontext = CallContext(args=[arg])
+ new_context.boundnode = None
+ yield new_context
+
+ @staticmethod
+ def _same_type(type1, type2) -> bool:
+ """Check if type1 is the same as type2."""
+ return type1.qname() == type2.qname()
+
+ @staticmethod
+ def _get_aug_flow(
+ left: InferenceResult,
+ left_type: InferenceResult | None,
+ aug_opnode: nodes.AugAssign,
+ right: InferenceResult,
+ right_type: InferenceResult | None,
+ context: InferenceContext,
+ reverse_context: InferenceContext,
+ ) -> list[partial[Generator[InferenceResult, None, None]]]:
+ """Get the flow for augmented binary operations.
+
+ The rules are a bit messy:
+
+ * if left and right have the same type, then left.__augop__(right)
+ is first tried and then left.__op__(right).
+ * if left and right are unrelated typewise, then
+ left.__augop__(right) is tried, then left.__op__(right)
+ is tried and then right.__rop__(left) is tried.
+ * if left is a subtype of right, then left.__augop__(right)
+ is tried and then left.__op__(right).
+ * if left is a supertype of right, then left.__augop__(right)
+ is tried, then right.__rop__(left) and then
+ left.__op__(right)
+ """
+ from astroid import helpers # pylint: disable=import-outside-toplevel
+
+ bin_op = aug_opnode.op.strip("=")
+ aug_op = aug_opnode.op
+ if OperatorNode._same_type(left_type, right_type):
+ methods = [
+ OperatorNode._aug_op(left, aug_opnode, aug_op, right, context),
+ OperatorNode._bin_op(left, aug_opnode, bin_op, right, context),
+ ]
+ elif helpers.is_subtype(left_type, right_type):
+ methods = [
+ OperatorNode._aug_op(left, aug_opnode, aug_op, right, context),
+ OperatorNode._bin_op(left, aug_opnode, bin_op, right, context),
+ ]
+ elif helpers.is_supertype(left_type, right_type):
+ methods = [
+ OperatorNode._aug_op(left, aug_opnode, aug_op, right, context),
+ OperatorNode._bin_op(
+ right, aug_opnode, bin_op, left, reverse_context, reverse=True
+ ),
+ OperatorNode._bin_op(left, aug_opnode, bin_op, right, context),
+ ]
+ else:
+ methods = [
+ OperatorNode._aug_op(left, aug_opnode, aug_op, right, context),
+ OperatorNode._bin_op(left, aug_opnode, bin_op, right, context),
+ OperatorNode._bin_op(
+ right, aug_opnode, bin_op, left, reverse_context, reverse=True
+ ),
+ ]
+ return methods
+
+ @staticmethod
+ def _get_binop_flow(
+ left: InferenceResult,
+ left_type: InferenceResult | None,
+ binary_opnode: nodes.AugAssign | nodes.BinOp,
+ right: InferenceResult,
+ right_type: InferenceResult | None,
+ context: InferenceContext,
+ reverse_context: InferenceContext,
+ ) -> list[partial[Generator[InferenceResult, None, None]]]:
+ """Get the flow for binary operations.
+
+ The rules are a bit messy:
+
+ * if left and right have the same type, then only one
+ method will be called, left.__op__(right)
+ * if left and right are unrelated typewise, then first
+ left.__op__(right) is tried and if this does not exist
+ or returns NotImplemented, then right.__rop__(left) is tried.
+ * if left is a subtype of right, then only left.__op__(right)
+ is tried.
+ * if left is a supertype of right, then right.__rop__(left)
+ is first tried and then left.__op__(right)
+ """
+ from astroid import helpers # pylint: disable=import-outside-toplevel
+
+ op = binary_opnode.op
+ if OperatorNode._same_type(left_type, right_type):
+ methods = [OperatorNode._bin_op(left, binary_opnode, op, right, context)]
+ elif helpers.is_subtype(left_type, right_type):
+ methods = [OperatorNode._bin_op(left, binary_opnode, op, right, context)]
+ elif helpers.is_supertype(left_type, right_type):
+ methods = [
+ OperatorNode._bin_op(
+ right, binary_opnode, op, left, reverse_context, reverse=True
+ ),
+ OperatorNode._bin_op(left, binary_opnode, op, right, context),
+ ]
+ else:
+ methods = [
+ OperatorNode._bin_op(left, binary_opnode, op, right, context),
+ OperatorNode._bin_op(
+ right, binary_opnode, op, left, reverse_context, reverse=True
+ ),
+ ]
+
+ if (
+ PY310_PLUS
+ and op == "|"
+ and (
+ isinstance(left, (bases.UnionType, nodes.ClassDef))
+ or isinstance(left, nodes.Const)
+ and left.value is None
+ )
+ and (
+ isinstance(right, (bases.UnionType, nodes.ClassDef))
+ or isinstance(right, nodes.Const)
+ and right.value is None
+ )
+ ):
+ methods.extend([partial(OperatorNode._bin_op_or_union_type, left, right)])
+ return methods
+
+ @staticmethod
+ def _infer_binary_operation(
+ left: InferenceResult,
+ right: InferenceResult,
+ binary_opnode: nodes.AugAssign | nodes.BinOp,
+ context: InferenceContext,
+ flow_factory: GetFlowFactory,
+ ) -> Generator[InferenceResult | util.BadBinaryOperationMessage, None, None]:
+ """Infer a binary operation between a left operand and a right operand.
+
+ This is used by both normal binary operations and augmented binary
+ operations, the only difference is the flow factory used.
+ """
+ from astroid import helpers # pylint: disable=import-outside-toplevel
+
+ context, reverse_context = OperatorNode._get_binop_contexts(
+ context, left, right
+ )
+ left_type = helpers.object_type(left)
+ right_type = helpers.object_type(right)
+ methods = flow_factory(
+ left, left_type, binary_opnode, right, right_type, context, reverse_context
+ )
+ for method in methods:
+ try:
+ results = list(method())
+ except AttributeError:
+ continue
+ except AttributeInferenceError:
+ continue
+ except InferenceError:
+ yield util.Uninferable
+ return
+ else:
+ if any(isinstance(result, util.UninferableBase) for result in results):
+ yield util.Uninferable
+ return
+
+ if all(map(OperatorNode._is_not_implemented, results)):
+ continue
+ not_implemented = sum(
+ 1 for result in results if OperatorNode._is_not_implemented(result)
+ )
+ if not_implemented and not_implemented != len(results):
+ # Can't infer yet what this is.
+ yield util.Uninferable
+ return
+
+ yield from results
+ return
+
+ # The operation doesn't seem to be supported so let the caller know about it
+ yield util.BadBinaryOperationMessage(left_type, binary_opnode.op, right_type)
+
+
+class AttributeNode(NodeNG):
+ expr: NodeNG
+ """The name that this node represents."""
+ attrname: str
+
+ @decorators.raise_if_nothing_inferred
+ def _infer_attribute(
+ self,
+ context: InferenceContext | None = None,
+ **kwargs: Any,
+ ) -> Generator[InferenceResult, None, InferenceErrorInfo]:
+ """Infer an Attribute node by using getattr on the associated object."""
+ # pylint: disable=import-outside-toplevel
+ from astroid.constraint import get_constraints
+
+ for owner in self.expr.infer(context):
+ if isinstance(owner, util.UninferableBase):
+ yield owner
+ continue
+
+ context = copy_context(context)
+ old_boundnode = context.boundnode
+ try:
+ context.boundnode = owner
+ if isinstance(owner, (nodes.ClassDef, bases.Instance)):
+ frame = (
+ owner if isinstance(owner, nodes.ClassDef) else owner._proxied
+ )
+ context.constraints[self.attrname] = get_constraints(
+ self, frame=frame
+ )
+ yield from owner.igetattr(self.attrname, context)
+ except (
+ AttributeInferenceError,
+ InferenceError,
+ AttributeError,
+ ):
+ pass
+ finally:
+ context.boundnode = old_boundnode
+ return InferenceErrorInfo(node=self, context=context)
+
+
+class AssignNode(NodeNG):
+ @decorators.raise_if_nothing_inferred
+ @decorators.path_wrapper
+ def _infer_assign(
+ self,
+ context: InferenceContext | None = None,
+ **kwargs: Any,
+ ) -> Generator[InferenceResult, None, None]:
+ """Infer a AssignName/AssignAttr: need to inspect the RHS part of the
+ assign node.
+ """
+ if isinstance(self.parent, nodes.AugAssign):
+ return self.parent.infer(context)
+
+ stmts = list(self.assigned_stmts(context=context))
+ return bases._infer_stmts(stmts, context)
+
+ def assigned_stmts(
+ self: nodes.AssignName | nodes.AssignAttr,
+ node: AssignedStmtsPossibleNode = None,
+ context: InferenceContext | None = None,
+ assign_path: list[int] | None = None,
+ ) -> Any:
+ """Returns the assigned statement (non inferred) according to the assignment type."""
+ return self.parent.assigned_stmts(node=self, context=context)
+
+
+class NameNode(LookupMixIn):
+ name: str
+
+ @decorators.raise_if_nothing_inferred
+ def _infer_name_node(
+ self,
+ context: InferenceContext | None = None,
+ **kwargs: Any,
+ ) -> Generator[InferenceResult, None, None]:
+ """Infer a Name: use name lookup rules."""
+ # pylint: disable=import-outside-toplevel
+ from astroid.constraint import get_constraints
+ from astroid.helpers import _higher_function_scope
+
+ frame, stmts = self.lookup(self.name)
+ if not stmts:
+ # Try to see if the name is enclosed in a nested function
+ # and use the higher (first function) scope for searching.
+ parent_function = _higher_function_scope(self.scope())
+ if parent_function:
+ _, stmts = parent_function.lookup(self.name)
+
+ if not stmts:
+ raise NameInferenceError(
+ name=self.name, scope=self.scope(), context=context
+ )
+ context = copy_context(context)
+ context.lookupname = self.name
+ context.constraints[self.name] = get_constraints(self, frame)
+
+ return bases._infer_stmts(stmts, context, frame)
diff --git a/astroid/nodes/node_classes.py b/astroid/nodes/node_classes.py
index 349385e976..4f2bc949fe 100644
--- a/astroid/nodes/node_classes.py
+++ b/astroid/nodes/node_classes.py
@@ -7,41 +7,46 @@
from __future__ import annotations
import abc
+import ast
import itertools
+import operator
import sys
import typing
import warnings
from collections.abc import Generator, Iterable, Iterator, Mapping
-from functools import cached_property, lru_cache
+from functools import cached_property
from typing import (
TYPE_CHECKING,
Any,
Callable,
- ClassVar,
Literal,
Optional,
Union,
)
-from astroid import decorators, util
+from astroid import decorators, protocols, util
from astroid.bases import Instance, _infer_stmts
from astroid.const import _EMPTY_OBJECT_MARKER, Context
-from astroid.context import InferenceContext
+from astroid.context import CallContext, InferenceContext, copy_context
from astroid.exceptions import (
+ AstroidBuildingError,
+ AstroidError,
AstroidIndexError,
AstroidTypeError,
AstroidValueError,
+ AttributeInferenceError,
InferenceError,
NoDefault,
ParentMissingError,
+ _NonDeducibleTypeHierarchy,
)
+from astroid.interpreter import dunder_lookup
from astroid.manager import AstroidManager
from astroid.nodes import _base_nodes
from astroid.nodes.const import OP_PRECEDENCE
from astroid.nodes.node_ng import NodeNG
from astroid.typing import (
ConstFactoryResult,
- InferBinaryOp,
InferenceErrorInfo,
InferenceResult,
SuccessfulInferenceResult,
@@ -52,7 +57,6 @@
else:
from typing_extensions import Self
-
if TYPE_CHECKING:
from astroid import nodes
from astroid.nodes import LocalsDictNodeNG
@@ -337,46 +341,67 @@ def pytype(self) -> str:
def get_children(self):
yield from self.elts
+ @decorators.raise_if_nothing_inferred
+ def _infer(
+ self,
+ context: InferenceContext | None = None,
+ **kwargs: Any,
+ ) -> Iterator[Self]:
+ has_starred_named_expr = any(
+ isinstance(e, (Starred, NamedExpr)) for e in self.elts
+ )
+ if has_starred_named_expr:
+ values = self._infer_sequence_helper(context)
+ new_seq = type(self)(
+ lineno=self.lineno,
+ col_offset=self.col_offset,
+ parent=self.parent,
+ end_lineno=self.end_lineno,
+ end_col_offset=self.end_col_offset,
+ )
+ new_seq.postinit(values)
-# TODO: Move into _base_nodes. Blocked by import of _infer_stmts from bases.
-class LookupMixIn(NodeNG):
- """Mixin to look up a name in the right scope."""
-
- @lru_cache # noqa
- def lookup(self, name: str) -> tuple[LocalsDictNodeNG, list[NodeNG]]:
- """Lookup where the given variable is assigned.
-
- The lookup starts from self's scope. If self is not a frame itself
- and the name is found in the inner frame locals, statements will be
- filtered to remove ignorable statements according to self's location.
-
- :param name: The name of the variable to find assignments for.
-
- :returns: The scope node and the list of assignments associated to the
- given name according to the scope where it has been found (locals,
- globals or builtin).
- """
- return self.scope().scope_lookup(self, name)
-
- def ilookup(self, name):
- """Lookup the inferred values of the given variable.
-
- :param name: The variable name to find values for.
- :type name: str
-
- :returns: The inferred values of the statements returned from
- :meth:`lookup`.
- :rtype: iterable
- """
- frame, stmts = self.lookup(name)
- context = InferenceContext()
- return _infer_stmts(stmts, context, frame)
+ yield new_seq
+ else:
+ yield self
+
+ def _infer_sequence_helper(
+ self, context: InferenceContext | None = None
+ ) -> list[SuccessfulInferenceResult]:
+ """Infer all values based on BaseContainer.elts."""
+ from astroid import helpers # pylint: disable=import-outside-toplevel
+
+ values = []
+
+ for elt in self.elts:
+ if isinstance(elt, Starred):
+ starred = helpers.safe_infer(elt.value, context)
+ if not starred:
+ raise InferenceError(node=self, context=context)
+ if not hasattr(starred, "elts"):
+ raise InferenceError(node=self, context=context)
+ # TODO: fresh context?
+ values.extend(starred._infer_sequence_helper(context))
+ elif isinstance(elt, NamedExpr):
+ value = helpers.safe_infer(elt.value, context)
+ if not value:
+ raise InferenceError(node=self, context=context)
+ values.append(value)
+ else:
+ values.append(elt)
+ return values
# Name classes
-class AssignName(_base_nodes.NoChildrenNode, LookupMixIn, _base_nodes.ParentAssignNode):
+class AssignName(
+ _base_nodes.NameNode,
+ _base_nodes.AssignNode,
+ _base_nodes.NoChildrenNode,
+ _base_nodes.LookupMixIn,
+ _base_nodes.ParentAssignNode,
+):
"""Variation of :class:`ast.Assign` representing assignment to a name.
An :class:`AssignName` is the name of something that is assigned to.
@@ -394,8 +419,6 @@ class AssignName(_base_nodes.NoChildrenNode, LookupMixIn, _base_nodes.ParentAssi
_other_fields = ("name",)
- infer_lhs: ClassVar[InferLHS[AssignName]]
-
def __init__(
self,
name: str,
@@ -417,13 +440,26 @@ def __init__(
parent=parent,
)
- assigned_stmts: ClassVar[AssignedStmtsCall[AssignName]]
+ assigned_stmts = protocols.assend_assigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
+ return self._infer_assign(context, **kwargs)
+
+ @decorators.raise_if_nothing_inferred
+ def infer_lhs(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
+ return self._infer_name_node(context, **kwargs)
+
-class DelName(_base_nodes.NoChildrenNode, LookupMixIn, _base_nodes.ParentAssignNode):
+class DelName(
+ _base_nodes.NoChildrenNode, _base_nodes.LookupMixIn, _base_nodes.ParentAssignNode
+):
"""Variation of :class:`ast.Delete` representing deletion of a name.
A :class:`DelName` is the name of something that is deleted.
@@ -460,7 +496,7 @@ def __init__(
)
-class Name(_base_nodes.NoChildrenNode, LookupMixIn):
+class Name(_base_nodes.NameNode, _base_nodes.NoChildrenNode):
"""Class representing an :class:`ast.Name` node.
A :class:`Name` node is something that is named, but not covered by
@@ -505,6 +541,12 @@ def _get_name_nodes(self):
for child_node in self.get_children():
yield from child_node._get_name_nodes()
+ @decorators.path_wrapper
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
+ return self._infer_name_node(context, **kwargs)
+
DEPRECATED_ARGUMENT_DEFAULT = object()
@@ -663,7 +705,7 @@ def postinit(
type_comment_posonlyargs = []
self.type_comment_posonlyargs = type_comment_posonlyargs
- assigned_stmts: ClassVar[AssignedStmtsCall[Arguments]]
+ assigned_stmts = protocols.arguments_assigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
@@ -894,6 +936,17 @@ def get_children(self):
if elt is not None:
yield elt
+ @decorators.raise_if_nothing_inferred
+ def _infer(
+ self: nodes.Arguments, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[InferenceResult, None, None]:
+ # pylint: disable-next=import-outside-toplevel
+ from astroid.protocols import _arguments_infer_argname
+
+ if context is None or context.lookupname is None:
+ raise InferenceError(node=self, context=context)
+ return _arguments_infer_argname(self, context.lookupname, context)
+
def _find_arg(argname, args):
for i, arg in enumerate(args):
@@ -934,7 +987,9 @@ def _format_args(
return ", ".join(values)
-class AssignAttr(_base_nodes.ParentAssignNode):
+class AssignAttr(
+ _base_nodes.AttributeNode, _base_nodes.AssignNode, _base_nodes.ParentAssignNode
+):
"""Variation of :class:`ast.Assign` representing assignment to an attribute.
>>> import astroid
@@ -950,11 +1005,6 @@ class AssignAttr(_base_nodes.ParentAssignNode):
_astroid_fields = ("expr",)
_other_fields = ("attrname",)
- infer_lhs: ClassVar[InferLHS[AssignAttr]]
-
- expr: NodeNG
- """What has the attribute that is being assigned to."""
-
def __init__(
self,
attrname: str,
@@ -979,7 +1029,7 @@ def __init__(
def postinit(self, expr: NodeNG) -> None:
self.expr = expr
- assigned_stmts: ClassVar[AssignedStmtsCall[AssignAttr]]
+ assigned_stmts = protocols.assend_assigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
@@ -987,6 +1037,16 @@ def postinit(self, expr: NodeNG) -> None:
def get_children(self):
yield self.expr
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
+ return self._infer_assign(context, **kwargs)
+
+ def infer_lhs(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
+ return self._infer_attribute(context, **kwargs)
+
class Assert(_base_nodes.Statement):
"""Class representing an :class:`ast.Assert` node.
@@ -1052,7 +1112,7 @@ def postinit(
self.value = value
self.type_annotation = type_annotation
- assigned_stmts: ClassVar[AssignedStmtsCall[Assign]]
+ assigned_stmts = protocols.assign_assigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
@@ -1108,7 +1168,7 @@ def postinit(
self.value = value
self.simple = simple
- assigned_stmts: ClassVar[AssignedStmtsCall[AnnAssign]]
+ assigned_stmts = protocols.assign_annassigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
@@ -1121,7 +1181,9 @@ def get_children(self):
yield self.value
-class AugAssign(_base_nodes.AssignTypeNode, _base_nodes.Statement):
+class AugAssign(
+ _base_nodes.AssignTypeNode, _base_nodes.OperatorNode, _base_nodes.Statement
+):
"""Class representing an :class:`ast.AugAssign` node.
An :class:`AugAssign` is an assignment paired with an operator.
@@ -1169,16 +1231,11 @@ def postinit(self, target: Name | Attribute | Subscript, value: NodeNG) -> None:
self.target = target
self.value = value
- assigned_stmts: ClassVar[AssignedStmtsCall[AugAssign]]
+ assigned_stmts = protocols.assign_assigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
- # This is set by inference.py
- _infer_augassign: ClassVar[
- InferBinaryOperation[AugAssign, util.BadBinaryOperationMessage]
- ]
-
def type_errors(self, context: InferenceContext | None = None):
"""Get a list of type errors which can occur during inference.
@@ -1207,8 +1264,45 @@ def _get_yield_nodes_skip_lambdas(self):
yield from self.value._get_yield_nodes_skip_lambdas()
yield from super()._get_yield_nodes_skip_lambdas()
+ def _infer_augassign(
+ self, context: InferenceContext | None = None
+ ) -> Generator[InferenceResult | util.BadBinaryOperationMessage, None, None]:
+ """Inference logic for augmented binary operations."""
+ context = context or InferenceContext()
+
+ rhs_context = context.clone()
+
+ lhs_iter = self.target.infer_lhs(context=context)
+ rhs_iter = self.value.infer(context=rhs_context)
+
+ for lhs, rhs in itertools.product(lhs_iter, rhs_iter):
+ if any(isinstance(value, util.UninferableBase) for value in (rhs, lhs)):
+ # Don't know how to process this.
+ yield util.Uninferable
+ return
+
+ try:
+ yield from self._infer_binary_operation(
+ left=lhs,
+ right=rhs,
+ binary_opnode=self,
+ context=context,
+ flow_factory=self._get_aug_flow,
+ )
+ except _NonDeducibleTypeHierarchy:
+ yield util.Uninferable
-class BinOp(NodeNG):
+ @decorators.raise_if_nothing_inferred
+ @decorators.path_wrapper
+ def _infer(
+ self: nodes.AugAssign, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[InferenceResult, None, None]:
+ return self._filter_operation_errors(
+ self._infer_augassign, context, util.BadBinaryOperationMessage
+ )
+
+
+class BinOp(_base_nodes.OperatorNode):
"""Class representing an :class:`ast.BinOp` node.
A :class:`BinOp` node is an application of a binary operator.
@@ -1253,9 +1347,6 @@ def postinit(self, left: NodeNG, right: NodeNG) -> None:
self.left = left
self.right = right
- # This is set by inference.py
- _infer_binop: ClassVar[InferBinaryOperation[BinOp, util.BadBinaryOperationMessage]]
-
def type_errors(self, context: InferenceContext | None = None):
"""Get a list of type errors which can occur during inference.
@@ -1286,6 +1377,43 @@ def op_left_associative(self) -> bool:
# 2**3**4 == 2**(3**4)
return self.op != "**"
+ def _infer_binop(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[InferenceResult, None, None]:
+ """Binary operation inference logic."""
+ left = self.left
+ right = self.right
+
+ # we use two separate contexts for evaluating lhs and rhs because
+ # 1. evaluating lhs may leave some undesired entries in context.path
+ # which may not let us infer right value of rhs
+ context = context or InferenceContext()
+ lhs_context = copy_context(context)
+ rhs_context = copy_context(context)
+ lhs_iter = left.infer(context=lhs_context)
+ rhs_iter = right.infer(context=rhs_context)
+ for lhs, rhs in itertools.product(lhs_iter, rhs_iter):
+ if any(isinstance(value, util.UninferableBase) for value in (rhs, lhs)):
+ # Don't know how to process this.
+ yield util.Uninferable
+ return
+
+ try:
+ yield from self._infer_binary_operation(
+ lhs, rhs, self, context, self._get_binop_flow
+ )
+ except _NonDeducibleTypeHierarchy:
+ yield util.Uninferable
+
+ @decorators.yes_if_nothing_inferred
+ @decorators.path_wrapper
+ def _infer(
+ self: nodes.BinOp, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[InferenceResult, None, None]:
+ return self._filter_operation_errors(
+ self._infer_binop, context, util.BadBinaryOperationMessage
+ )
+
class BoolOp(NodeNG):
"""Class representing an :class:`ast.BoolOp` node.
@@ -1355,6 +1483,60 @@ def get_children(self):
def op_precedence(self):
return OP_PRECEDENCE[self.op]
+ @decorators.raise_if_nothing_inferred
+ @decorators.path_wrapper
+ def _infer(
+ self: nodes.BoolOp, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
+ """Infer a boolean operation (and / or / not).
+
+ The function will calculate the boolean operation
+ for all pairs generated through inference for each component
+ node.
+ """
+ values = self.values
+ if self.op == "or":
+ predicate = operator.truth
+ else:
+ predicate = operator.not_
+
+ try:
+ inferred_values = [value.infer(context=context) for value in values]
+ except InferenceError:
+ yield util.Uninferable
+ return None
+
+ for pair in itertools.product(*inferred_values):
+ if any(isinstance(item, util.UninferableBase) for item in pair):
+ # Can't infer the final result, just yield Uninferable.
+ yield util.Uninferable
+ continue
+
+ bool_values = [item.bool_value() for item in pair]
+ if any(isinstance(item, util.UninferableBase) for item in bool_values):
+ # Can't infer the final result, just yield Uninferable.
+ yield util.Uninferable
+ continue
+
+ # Since the boolean operations are short circuited operations,
+ # this code yields the first value for which the predicate is True
+ # and if no value respected the predicate, then the last value will
+ # be returned (or Uninferable if there was no last value).
+ # This is conforming to the semantics of `and` and `or`:
+ # 1 and 0 -> 1
+ # 0 and 1 -> 0
+ # 1 or 0 -> 1
+ # 0 or 1 -> 1
+ value = util.Uninferable
+ for value, bool_value in zip(pair, bool_values):
+ if predicate(bool_value):
+ yield value
+ break
+ else:
+ yield value
+
+ return InferenceErrorInfo(node=self, context=context)
+
class Break(_base_nodes.NoChildrenNode, _base_nodes.Statement):
"""Class representing an :class:`ast.Break` node.
@@ -1412,6 +1594,64 @@ def get_children(self):
yield from self.keywords
+ @decorators.raise_if_nothing_inferred
+ @decorators.path_wrapper
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[InferenceResult, None, InferenceErrorInfo]:
+ """Infer a Call node by trying to guess what the function returns."""
+ callcontext = copy_context(context)
+ callcontext.boundnode = None
+ if context is not None:
+ callcontext.extra_context = self._populate_context_lookup(context.clone())
+
+ for callee in self.func.infer(context):
+ if isinstance(callee, util.UninferableBase):
+ yield callee
+ continue
+ try:
+ if hasattr(callee, "infer_call_result"):
+ callcontext.callcontext = CallContext(
+ args=self.args, keywords=self.keywords, callee=callee
+ )
+ yield from callee.infer_call_result(
+ caller=self, context=callcontext
+ )
+ except InferenceError:
+ continue
+ return InferenceErrorInfo(node=self, context=context)
+
+ def _populate_context_lookup(self, context: InferenceContext | None):
+ """Allows context to be saved for later for inference inside a function."""
+ context_lookup: dict[InferenceResult, InferenceContext] = {}
+ if context is None:
+ return context_lookup
+ for arg in self.args:
+ if isinstance(arg, Starred):
+ context_lookup[arg.value] = context
+ else:
+ context_lookup[arg] = context
+ keywords = self.keywords if self.keywords is not None else []
+ for keyword in keywords:
+ context_lookup[keyword.value] = context
+ return context_lookup
+
+
+COMPARE_OPS: dict[str, Callable[[Any, Any], bool]] = {
+ "==": operator.eq,
+ "!=": operator.ne,
+ "<": operator.lt,
+ "<=": operator.le,
+ ">": operator.gt,
+ ">=": operator.ge,
+ "in": lambda a, b: a in b,
+ "not in": lambda a, b: a not in b,
+}
+UNINFERABLE_OPS = {
+ "is",
+ "is not",
+}
+
class Compare(NodeNG):
"""Class representing an :class:`ast.Compare` node.
@@ -1461,6 +1701,88 @@ def last_child(self):
return self.ops[-1][1]
# return self.left
+ # TODO: move to util?
+ @staticmethod
+ def _to_literal(node: SuccessfulInferenceResult) -> Any:
+ # Can raise SyntaxError or ValueError from ast.literal_eval
+ # Can raise AttributeError from node.as_string() as not all nodes have a visitor
+ # Is this the stupidest idea or the simplest idea?
+ return ast.literal_eval(node.as_string())
+
+ def _do_compare(
+ self,
+ left_iter: Iterable[InferenceResult],
+ op: str,
+ right_iter: Iterable[InferenceResult],
+ ) -> bool | util.UninferableBase:
+ """
+ If all possible combinations are either True or False, return that:
+ >>> _do_compare([1, 2], '<=', [3, 4])
+ True
+ >>> _do_compare([1, 2], '==', [3, 4])
+ False
+
+ If any item is uninferable, or if some combinations are True and some
+ are False, return Uninferable:
+ >>> _do_compare([1, 3], '<=', [2, 4])
+ util.Uninferable
+ """
+ retval: bool | None = None
+ if op in UNINFERABLE_OPS:
+ return util.Uninferable
+ op_func = COMPARE_OPS[op]
+
+ for left, right in itertools.product(left_iter, right_iter):
+ if isinstance(left, util.UninferableBase) or isinstance(
+ right, util.UninferableBase
+ ):
+ return util.Uninferable
+
+ try:
+ left, right = self._to_literal(left), self._to_literal(right)
+ except (SyntaxError, ValueError, AttributeError):
+ return util.Uninferable
+
+ try:
+ expr = op_func(left, right)
+ except TypeError as exc:
+ raise AstroidTypeError from exc
+
+ if retval is None:
+ retval = expr
+ elif retval != expr:
+ return util.Uninferable
+ # (or both, but "True | False" is basically the same)
+
+ assert retval is not None
+ return retval # it was all the same value
+
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[nodes.Const | util.UninferableBase, None, None]:
+ """Chained comparison inference logic."""
+ retval: bool | util.UninferableBase = True
+
+ ops = self.ops
+ left_node = self.left
+ lhs = list(left_node.infer(context=context))
+ # should we break early if first element is uninferable?
+ for op, right_node in ops:
+ # eagerly evaluate rhs so that values can be re-used as lhs
+ rhs = list(right_node.infer(context=context))
+ try:
+ retval = self._do_compare(lhs, op, rhs)
+ except AstroidTypeError:
+ retval = util.Uninferable
+ break
+ if retval is not True:
+ break # short-circuit
+ lhs = rhs # continue
+ if retval is util.Uninferable:
+ yield retval # type: ignore[misc]
+ else:
+ yield Const(retval)
+
class Comprehension(NodeNG):
"""Class representing an :class:`ast.comprehension` node.
@@ -1506,7 +1828,7 @@ def postinit(
self.ifs = ifs
self.is_async = is_async
- assigned_stmts: ClassVar[AssignedStmtsCall[Comprehension]]
+ assigned_stmts = protocols.for_assigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
@@ -1603,8 +1925,8 @@ def __init__(
Instance.__init__(self, None)
- infer_unary_op: ClassVar[InferUnaryOp[Const]]
- infer_binary_op: ClassVar[InferBinaryOp[Const]]
+ infer_unary_op = protocols.const_infer_unary_op
+ infer_binary_op = protocols.const_infer_binary_op
def __getattr__(self, name):
# This is needed because of Proxy's __getattr__ method.
@@ -1692,6 +2014,11 @@ def bool_value(self, context: InferenceContext | None = None):
"""
return bool(self.value)
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Iterator[Const]:
+ yield self
+
class Continue(_base_nodes.NoChildrenNode, _base_nodes.Statement):
"""Class representing an :class:`ast.Continue` node.
@@ -1871,7 +2198,7 @@ def postinit(self, items: list[tuple[InferenceResult, InferenceResult]]) -> None
"""
self.items = items
- infer_unary_op: ClassVar[InferUnaryOp[Dict]]
+ infer_unary_op = protocols.dict_infer_unary_op
def pytype(self) -> Literal["builtins.dict"]:
"""Get the name of the type that this node represents.
@@ -1923,13 +2250,12 @@ def getitem(
:raises AstroidIndexError: If the given index does not exist in the
dictionary.
"""
- # pylint: disable-next=import-outside-toplevel; circular import
- from astroid.helpers import safe_infer
+ from astroid import helpers # pylint: disable=import-outside-toplevel
for key, value in self.items:
# TODO(cpopa): no support for overriding yet, {1:2, **{1: 3}}.
if isinstance(key, DictUnpack):
- inferred_value = safe_infer(value, context)
+ inferred_value = helpers.safe_infer(value, context)
if not isinstance(inferred_value, Dict):
continue
@@ -1955,6 +2281,74 @@ def bool_value(self, context: InferenceContext | None = None):
"""
return bool(self.items)
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Iterator[nodes.Dict]:
+ if not any(isinstance(k, DictUnpack) for k, _ in self.items):
+ yield self
+ else:
+ items = self._infer_map(context)
+ new_seq = type(self)(
+ lineno=self.lineno,
+ col_offset=self.col_offset,
+ parent=self.parent,
+ end_lineno=self.end_lineno,
+ end_col_offset=self.end_col_offset,
+ )
+ new_seq.postinit(list(items.items()))
+ yield new_seq
+
+ @staticmethod
+ def _update_with_replacement(
+ lhs_dict: dict[SuccessfulInferenceResult, SuccessfulInferenceResult],
+ rhs_dict: dict[SuccessfulInferenceResult, SuccessfulInferenceResult],
+ ) -> dict[SuccessfulInferenceResult, SuccessfulInferenceResult]:
+ """Delete nodes that equate to duplicate keys.
+
+ Since an astroid node doesn't 'equal' another node with the same value,
+ this function uses the as_string method to make sure duplicate keys
+ don't get through
+
+ Note that both the key and the value are astroid nodes
+
+ Fixes issue with DictUnpack causing duplicate keys
+ in inferred Dict items
+
+ :param lhs_dict: Dictionary to 'merge' nodes into
+ :param rhs_dict: Dictionary with nodes to pull from
+ :return : merged dictionary of nodes
+ """
+ combined_dict = itertools.chain(lhs_dict.items(), rhs_dict.items())
+ # Overwrite keys which have the same string values
+ string_map = {key.as_string(): (key, value) for key, value in combined_dict}
+ # Return to dictionary
+ return dict(string_map.values())
+
+ def _infer_map(
+ self, context: InferenceContext | None
+ ) -> dict[SuccessfulInferenceResult, SuccessfulInferenceResult]:
+ """Infer all values based on Dict.items."""
+ from astroid import helpers # pylint: disable=import-outside-toplevel
+
+ values: dict[SuccessfulInferenceResult, SuccessfulInferenceResult] = {}
+ for name, value in self.items:
+ if isinstance(name, DictUnpack):
+ double_starred = helpers.safe_infer(value, context)
+ if not double_starred:
+ raise InferenceError
+ if not isinstance(double_starred, Dict):
+ raise InferenceError(node=self, context=context)
+ unpack_items = double_starred._infer_map(context)
+ values = self._update_with_replacement(values, unpack_items)
+ else:
+ key = helpers.safe_infer(name, context=context)
+ safe_value = helpers.safe_infer(value, context=context)
+ if any(not elem for elem in (key, safe_value)):
+ raise InferenceError(node=self, context=context)
+ # safe_value is SuccessfulInferenceResult as bool(Uninferable) == False
+ values = self._update_with_replacement(values, {key: safe_value})
+ return values
+
class Expr(_base_nodes.Statement):
"""Class representing an :class:`ast.Expr` node.
@@ -2011,6 +2405,21 @@ def __init__(
def has_underlying_object(self) -> bool:
return self.object is not None and self.object is not _EMPTY_OBJECT_MARKER
+ @decorators.raise_if_nothing_inferred
+ @decorators.path_wrapper
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[InferenceResult, None, None]:
+ if not self.has_underlying_object():
+ yield util.Uninferable
+ else:
+ try:
+ yield from AstroidManager().infer_ast_from_something(
+ self.object, context=context
+ )
+ except AstroidError:
+ yield util.Uninferable
+
class ExceptHandler(
_base_nodes.MultiLineBlockNode, _base_nodes.AssignTypeNode, _base_nodes.Statement
@@ -2044,7 +2453,7 @@ class ExceptHandler(
body: list[NodeNG]
"""The contents of the block."""
- assigned_stmts: ClassVar[AssignedStmtsCall[ExceptHandler]]
+ assigned_stmts = protocols.excepthandler_assigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
@@ -2142,7 +2551,7 @@ def postinit(
self.orelse = orelse
self.type_annotation = type_annotation
- assigned_stmts: ClassVar[AssignedStmtsCall[For]]
+ assigned_stmts = protocols.for_assigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
@@ -2283,16 +2692,47 @@ def __init__(
parent=parent,
)
+ @decorators.raise_if_nothing_inferred
+ @decorators.path_wrapper
+ def _infer(
+ self,
+ context: InferenceContext | None = None,
+ asname: bool = True,
+ **kwargs: Any,
+ ) -> Generator[InferenceResult, None, None]:
+ """Infer a ImportFrom node: return the imported module/object."""
+ context = context or InferenceContext()
+ name = context.lookupname
+ if name is None:
+ raise InferenceError(node=self, context=context)
+ if asname:
+ try:
+ name = self.real_name(name)
+ except AttributeInferenceError as exc:
+ # See https://github.com/pylint-dev/pylint/issues/4692
+ raise InferenceError(node=self, context=context) from exc
+ try:
+ module = self.do_import_module()
+ except AstroidBuildingError as exc:
+ raise InferenceError(node=self, context=context) from exc
+
+ try:
+ context = copy_context(context)
+ context.lookupname = name
+ stmts = module.getattr(name, ignore_locals=module is self.root())
+ return _infer_stmts(stmts, context)
+ except AttributeInferenceError as error:
+ raise InferenceError(
+ str(error), target=self, attribute=name, context=context
+ ) from error
+
-class Attribute(NodeNG):
+class Attribute(_base_nodes.AttributeNode):
"""Class representing an :class:`ast.Attribute` node."""
_astroid_fields = ("expr",)
_other_fields = ("attrname",)
- expr: NodeNG
- """The name that this node represents."""
-
def __init__(
self,
attrname: str,
@@ -2320,6 +2760,12 @@ def postinit(self, expr: NodeNG) -> None:
def get_children(self):
yield self.expr
+ @decorators.path_wrapper
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[InferenceResult, None, None]:
+ return self._infer_attribute(context, **kwargs)
+
class Global(_base_nodes.NoChildrenNode, _base_nodes.Statement):
"""Class representing an :class:`ast.Global` node.
@@ -2371,6 +2817,21 @@ def __init__(
def _infer_name(self, frame, name):
return name
+ @decorators.raise_if_nothing_inferred
+ @decorators.path_wrapper
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[InferenceResult, None, None]:
+ if context is None or context.lookupname is None:
+ raise InferenceError(node=self, context=context)
+ try:
+ # pylint: disable-next=no-member
+ return _infer_stmts(self.root().getattr(context.lookupname), context)
+ except AttributeInferenceError as error:
+ raise InferenceError(
+ str(error), target=self, attribute=context.lookupname, context=context
+ ) from error
+
class If(_base_nodes.MultiLineWithElseBlockNode, _base_nodes.Statement):
"""Class representing an :class:`ast.If` node.
@@ -2469,6 +2930,40 @@ def op_left_associative(self) -> Literal[False]:
# `1 if True else (2 if False else 3)`
return False
+ @decorators.raise_if_nothing_inferred
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[InferenceResult, None, None]:
+ """Support IfExp inference.
+
+ If we can't infer the truthiness of the condition, we default
+ to inferring both branches. Otherwise, we infer either branch
+ depending on the condition.
+ """
+ both_branches = False
+ # We use two separate contexts for evaluating lhs and rhs because
+ # evaluating lhs may leave some undesired entries in context.path
+ # which may not let us infer right value of rhs.
+
+ context = context or InferenceContext()
+ lhs_context = copy_context(context)
+ rhs_context = copy_context(context)
+ try:
+ test = next(self.test.infer(context=context.clone()))
+ except (InferenceError, StopIteration):
+ both_branches = True
+ else:
+ if not isinstance(test, util.UninferableBase):
+ if test.bool_value():
+ yield from self.body.infer(context=lhs_context)
+ else:
+ yield from self.orelse.infer(context=rhs_context)
+ else:
+ both_branches = True
+ if both_branches:
+ yield from self.body.infer(context=lhs_context)
+ yield from self.orelse.infer(context=rhs_context)
+
class Import(_base_nodes.ImportNode):
"""Class representing an :class:`ast.Import` node.
@@ -2521,6 +3016,28 @@ def __init__(
parent=parent,
)
+ @decorators.raise_if_nothing_inferred
+ @decorators.path_wrapper
+ def _infer(
+ self,
+ context: InferenceContext | None = None,
+ asname: bool = True,
+ **kwargs: Any,
+ ) -> Generator[nodes.Module, None, None]:
+ """Infer an Import node: return the imported module/object."""
+ context = context or InferenceContext()
+ name = context.lookupname
+ if name is None:
+ raise InferenceError(node=self, context=context)
+
+ try:
+ if asname:
+ yield self.do_import_module(self.real_name(name))
+ else:
+ yield self.do_import_module(name)
+ except AstroidBuildingError as exc:
+ raise InferenceError(node=self, context=context) from exc
+
class Keyword(NodeNG):
"""Class representing an :class:`ast.keyword` node.
@@ -2614,13 +3131,13 @@ def __init__(
parent=parent,
)
- assigned_stmts: ClassVar[AssignedStmtsCall[List]]
+ assigned_stmts = protocols.sequence_assigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
- infer_unary_op: ClassVar[InferUnaryOp[List]]
- infer_binary_op: ClassVar[InferBinaryOp[List]]
+ infer_unary_op = protocols.list_infer_unary_op
+ infer_binary_op = protocols.tl_infer_binary_op
def pytype(self) -> Literal["builtins.list"]:
"""Get the name of the type that this node represents.
@@ -2727,6 +3244,11 @@ def __init__(
def postinit(self, *, name: AssignName) -> None:
self.name = name
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Iterator[ParamSpec]:
+ yield self
+
class Pass(_base_nodes.NoChildrenNode, _base_nodes.Statement):
"""Class representing an :class:`ast.Pass` node.
@@ -2819,7 +3341,7 @@ class Set(BaseContainer):
<Set.set l.1 at 0x7f23b2e71d68>
"""
- infer_unary_op: ClassVar[InferUnaryOp[Set]]
+ infer_unary_op = protocols.set_infer_unary_op
def pytype(self) -> Literal["builtins.set"]:
"""Get the name of the type that this node represents.
@@ -2912,6 +3434,11 @@ def get_children(self):
if self.step is not None:
yield self.step
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Iterator[Slice]:
+ yield self
+
class Starred(_base_nodes.ParentAssignNode):
"""Class representing an :class:`ast.Starred` node.
@@ -2952,7 +3479,7 @@ def __init__(
def postinit(self, value: NodeNG) -> None:
self.value = value
- assigned_stmts: ClassVar[AssignedStmtsCall[Starred]]
+ assigned_stmts = protocols.starred_assigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
@@ -2970,11 +3497,10 @@ class Subscript(NodeNG):
<Subscript l.1 at 0x7f23b2e71f60>
"""
+ _SUBSCRIPT_SENTINEL = object()
_astroid_fields = ("value", "slice")
_other_fields = ("ctx",)
- infer_lhs: ClassVar[InferLHS[Subscript]]
-
value: NodeNG
"""What is being indexed."""
@@ -3011,6 +3537,74 @@ def get_children(self):
yield self.value
yield self.slice
+ def _infer_subscript(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
+ """Inference for subscripts.
+
+ We're understanding if the index is a Const
+ or a slice, passing the result of inference
+ to the value's `getitem` method, which should
+ handle each supported index type accordingly.
+ """
+ from astroid import helpers # pylint: disable=import-outside-toplevel
+
+ found_one = False
+ for value in self.value.infer(context):
+ if isinstance(value, util.UninferableBase):
+ yield util.Uninferable
+ return None
+ for index in self.slice.infer(context):
+ if isinstance(index, util.UninferableBase):
+ yield util.Uninferable
+ return None
+
+ # Try to deduce the index value.
+ index_value = self._SUBSCRIPT_SENTINEL
+ if value.__class__ == Instance:
+ index_value = index
+ elif index.__class__ == Instance:
+ instance_as_index = helpers.class_instance_as_index(index)
+ if instance_as_index:
+ index_value = instance_as_index
+ else:
+ index_value = index
+
+ if index_value is self._SUBSCRIPT_SENTINEL:
+ raise InferenceError(node=self, context=context)
+
+ try:
+ assigned = value.getitem(index_value, context)
+ except (
+ AstroidTypeError,
+ AstroidIndexError,
+ AstroidValueError,
+ AttributeInferenceError,
+ AttributeError,
+ ) as exc:
+ raise InferenceError(node=self, context=context) from exc
+
+ # Prevent inferring if the inferred subscript
+ # is the same as the original subscripted object.
+ if self is assigned or isinstance(assigned, util.UninferableBase):
+ yield util.Uninferable
+ return None
+ yield from assigned.infer(context)
+ found_one = True
+
+ if found_one:
+ return InferenceErrorInfo(node=self, context=context)
+ return None
+
+ @decorators.raise_if_nothing_inferred
+ @decorators.path_wrapper
+ def _infer(self, context: InferenceContext | None = None, **kwargs: Any):
+ return self._infer_subscript(context, **kwargs)
+
+ @decorators.raise_if_nothing_inferred
+ def infer_lhs(self, context: InferenceContext | None = None, **kwargs: Any):
+ return self._infer_subscript(context, **kwargs)
+
class TryExcept(_base_nodes.MultiLineWithElseBlockNode, _base_nodes.Statement):
"""Class representing an :class:`ast.TryExcept` node.
@@ -3318,13 +3912,13 @@ def __init__(
parent=parent,
)
- assigned_stmts: ClassVar[AssignedStmtsCall[Tuple]]
+ assigned_stmts = protocols.sequence_assigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
- infer_unary_op: ClassVar[InferUnaryOp[Tuple]]
- infer_binary_op: ClassVar[InferBinaryOp[Tuple]]
+ infer_unary_op = protocols.tuple_infer_unary_op
+ infer_binary_op = protocols.tl_infer_binary_op
def pytype(self) -> Literal["builtins.tuple"]:
"""Get the name of the type that this node represents.
@@ -3385,6 +3979,11 @@ def postinit(
self.type_params = type_params
self.value = value
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Iterator[TypeAlias]:
+ yield self
+
class TypeVar(_base_nodes.AssignTypeNode):
"""Class representing a :class:`ast.TypeVar` node.
@@ -3421,6 +4020,11 @@ def postinit(self, *, name: AssignName, bound: NodeNG | None) -> None:
self.name = name
self.bound = bound
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Iterator[TypeVar]:
+ yield self
+
class TypeVarTuple(_base_nodes.AssignTypeNode):
"""Class representing a :class:`ast.TypeVarTuple` node.
@@ -3455,8 +4059,21 @@ def __init__(
def postinit(self, *, name: AssignName) -> None:
self.name = name
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Iterator[TypeVarTuple]:
+ yield self
+
-class UnaryOp(NodeNG):
+UNARY_OP_METHOD = {
+ "+": "__pos__",
+ "-": "__neg__",
+ "~": "__invert__",
+ "not": None, # XXX not '__nonzero__'
+}
+
+
+class UnaryOp(_base_nodes.OperatorNode):
"""Class representing an :class:`ast.UnaryOp` node.
>>> import astroid
@@ -3495,19 +4112,14 @@ def __init__(
def postinit(self, operand: NodeNG) -> None:
self.operand = operand
- # This is set by inference.py
- _infer_unaryop: ClassVar[
- InferBinaryOperation[UnaryOp, util.BadUnaryOperationMessage]
- ]
-
def type_errors(self, context: InferenceContext | None = None):
"""Get a list of type errors which can occur during inference.
- Each TypeError is represented by a :class:`BadBinaryOperationMessage`,
+ Each TypeError is represented by a :class:`BadUnaryOperationMessage`,
which holds the original exception.
:returns: The list of possible type errors.
- :rtype: list(BadBinaryOperationMessage)
+ :rtype: list(BadUnaryOperationMessage)
"""
try:
results = self._infer_unaryop(context=context)
@@ -3528,6 +4140,81 @@ def op_precedence(self):
return super().op_precedence()
+ def _infer_unaryop(
+ self: nodes.UnaryOp, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[
+ InferenceResult | util.BadUnaryOperationMessage, None, InferenceErrorInfo
+ ]:
+ """Infer what an UnaryOp should return when evaluated."""
+ from astroid.nodes import ClassDef # pylint: disable=import-outside-toplevel
+
+ for operand in self.operand.infer(context):
+ try:
+ yield operand.infer_unary_op(self.op)
+ except TypeError as exc:
+ # The operand doesn't support this operation.
+ yield util.BadUnaryOperationMessage(operand, self.op, exc)
+ except AttributeError as exc:
+ meth = UNARY_OP_METHOD[self.op]
+ if meth is None:
+ # `not node`. Determine node's boolean
+ # value and negate its result, unless it is
+ # Uninferable, which will be returned as is.
+ bool_value = operand.bool_value()
+ if not isinstance(bool_value, util.UninferableBase):
+ yield const_factory(not bool_value)
+ else:
+ yield util.Uninferable
+ else:
+ if not isinstance(operand, (Instance, ClassDef)):
+ # The operation was used on something which
+ # doesn't support it.
+ yield util.BadUnaryOperationMessage(operand, self.op, exc)
+ continue
+
+ try:
+ try:
+ methods = dunder_lookup.lookup(operand, meth)
+ except AttributeInferenceError:
+ yield util.BadUnaryOperationMessage(operand, self.op, exc)
+ continue
+
+ meth = methods[0]
+ inferred = next(meth.infer(context=context), None)
+ if (
+ isinstance(inferred, util.UninferableBase)
+ or not inferred.callable()
+ ):
+ continue
+
+ context = copy_context(context)
+ context.boundnode = operand
+ context.callcontext = CallContext(args=[], callee=inferred)
+
+ call_results = inferred.infer_call_result(self, context=context)
+ result = next(call_results, None)
+ if result is None:
+ # Failed to infer, return the same type.
+ yield operand
+ else:
+ yield result
+ except AttributeInferenceError as inner_exc:
+ # The unary operation special method was not found.
+ yield util.BadUnaryOperationMessage(operand, self.op, inner_exc)
+ except InferenceError:
+ yield util.Uninferable
+
+ @decorators.raise_if_nothing_inferred
+ @decorators.path_wrapper
+ def _infer(
+ self: nodes.UnaryOp, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[InferenceResult, None, InferenceErrorInfo]:
+ """Infer what an UnaryOp should return when evaluated."""
+ yield from self._filter_operation_errors(
+ self._infer_unaryop, context, util.BadUnaryOperationMessage
+ )
+ return InferenceErrorInfo(node=self, context=context)
+
class While(_base_nodes.MultiLineWithElseBlockNode, _base_nodes.Statement):
"""Class representing an :class:`ast.While` node.
@@ -3671,7 +4358,7 @@ def postinit(
self.body = body
self.type_annotation = type_annotation
- assigned_stmts: ClassVar[AssignedStmtsCall[With]]
+ assigned_stmts = protocols.with_assigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
@@ -3944,7 +4631,7 @@ def postinit(self, target: NodeNG, value: NodeNG) -> None:
self.target = target
self.value = value
- assigned_stmts: ClassVar[AssignedStmtsCall[NamedExpr]]
+ assigned_stmts = protocols.named_expr_assigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
@@ -4345,17 +5032,7 @@ def postinit(
self.patterns = patterns
self.rest = rest
- assigned_stmts: ClassVar[
- Callable[
- [
- MatchMapping,
- AssignName,
- InferenceContext | None,
- None,
- ],
- Generator[NodeNG, None, None],
- ]
- ]
+ assigned_stmts = protocols.match_mapping_assigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
@@ -4452,17 +5129,7 @@ def __init__(
def postinit(self, *, name: AssignName | None) -> None:
self.name = name
- assigned_stmts: ClassVar[
- Callable[
- [
- MatchStar,
- AssignName,
- InferenceContext | None,
- None,
- ],
- Generator[NodeNG, None, None],
- ]
- ]
+ assigned_stmts = protocols.match_star_assigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
@@ -4523,17 +5190,7 @@ def postinit(
self.pattern = pattern
self.name = name
- assigned_stmts: ClassVar[
- Callable[
- [
- MatchAs,
- AssignName,
- InferenceContext | None,
- None,
- ],
- Generator[NodeNG, None, None],
- ]
- ]
+ assigned_stmts = protocols.match_as_assigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
diff --git a/astroid/nodes/scoped_nodes/mixin.py b/astroid/nodes/scoped_nodes/mixin.py
index fa6aad412e..da03e06796 100644
--- a/astroid/nodes/scoped_nodes/mixin.py
+++ b/astroid/nodes/scoped_nodes/mixin.py
@@ -9,7 +9,7 @@
from typing import TYPE_CHECKING, TypeVar, overload
from astroid.filter_statements import _filter_stmts
-from astroid.nodes import node_classes, scoped_nodes
+from astroid.nodes import _base_nodes, node_classes, scoped_nodes
from astroid.nodes.scoped_nodes.utils import builtin_lookup
from astroid.typing import InferenceResult, SuccessfulInferenceResult
@@ -19,7 +19,7 @@
_T = TypeVar("_T")
-class LocalsDictNodeNG(node_classes.LookupMixIn):
+class LocalsDictNodeNG(_base_nodes.LookupMixIn):
"""this class provides locals handling common to Module, FunctionDef
and ClassDef nodes, including a dict like interface for direct access
to locals information
@@ -52,7 +52,7 @@ def scope(self: _T) -> _T:
return self
def scope_lookup(
- self, node: node_classes.LookupMixIn, name: str, offset: int = 0
+ self, node: _base_nodes.LookupMixIn, name: str, offset: int = 0
) -> tuple[LocalsDictNodeNG, list[nodes.NodeNG]]:
"""Lookup where the given variable is assigned.
@@ -70,7 +70,7 @@ def scope_lookup(
raise NotImplementedError
def _scope_lookup(
- self, node: node_classes.LookupMixIn, name: str, offset: int = 0
+ self, node: _base_nodes.LookupMixIn, name: str, offset: int = 0
) -> tuple[LocalsDictNodeNG, list[nodes.NodeNG]]:
"""XXX method for interfacing the scope lookup"""
try:
diff --git a/astroid/nodes/scoped_nodes/scoped_nodes.py b/astroid/nodes/scoped_nodes/scoped_nodes.py
index 94f4c53eeb..81a0c0e230 100644
--- a/astroid/nodes/scoped_nodes/scoped_nodes.py
+++ b/astroid/nodes/scoped_nodes/scoped_nodes.py
@@ -16,9 +16,9 @@
import warnings
from collections.abc import Generator, Iterable, Iterator, Sequence
from functools import cached_property, lru_cache
-from typing import TYPE_CHECKING, ClassVar, Literal, NoReturn, TypeVar
+from typing import TYPE_CHECKING, Any, ClassVar, Literal, NoReturn, TypeVar
-from astroid import bases, util
+from astroid import bases, protocols, util
from astroid.const import IS_PYPY, PY38, PY39_PLUS, PYPY_7_3_11_PLUS
from astroid.context import (
CallContext,
@@ -44,10 +44,16 @@
from astroid.nodes.scoped_nodes.mixin import ComprehensionScope, LocalsDictNodeNG
from astroid.nodes.scoped_nodes.utils import builtin_lookup
from astroid.nodes.utils import Position
-from astroid.typing import InferBinaryOp, InferenceResult, SuccessfulInferenceResult
+from astroid.typing import (
+ InferBinaryOp,
+ InferenceErrorInfo,
+ InferenceResult,
+ SuccessfulInferenceResult,
+)
if TYPE_CHECKING:
- from astroid import nodes
+ from astroid import nodes, objects
+ from astroid.nodes._base_nodes import LookupMixIn
ITER_METHODS = ("__iter__", "__getitem__")
@@ -285,7 +291,7 @@ def block_range(self, lineno: int) -> tuple[int, int]:
return self.fromlineno, self.tolineno
def scope_lookup(
- self, node: node_classes.LookupMixIn, name: str, offset: int = 0
+ self, node: LookupMixIn, name: str, offset: int = 0
) -> tuple[LocalsDictNodeNG, list[node_classes.NodeNG]]:
"""Lookup where the given variable is assigned.
@@ -578,6 +584,11 @@ def frame(self: _T, *, future: Literal[None, True] = None) -> _T:
"""
return self
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Iterator[Module]:
+ yield self
+
class GeneratorExp(ComprehensionScope):
"""Class representing an :class:`ast.GeneratorExp` node.
@@ -961,7 +972,7 @@ def infer_call_result(
return self.body.infer(context)
def scope_lookup(
- self, node: node_classes.LookupMixIn, name: str, offset: int = 0
+ self, node: LookupMixIn, name: str, offset: int = 0
) -> tuple[LocalsDictNodeNG, list[NodeNG]]:
"""Lookup where the given names is assigned.
@@ -1025,6 +1036,11 @@ def getattr(
return found_attrs
raise AttributeInferenceError(target=self, attribute=name)
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Iterator[Lambda]:
+ yield self
+
class FunctionDef(
_base_nodes.MultiLineBlockNode,
@@ -1469,6 +1485,44 @@ def is_generator(self) -> bool:
"""
return bool(next(self._get_yield_nodes_skip_lambdas(), False))
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Generator[objects.Property | FunctionDef, None, InferenceErrorInfo]:
+ from astroid import objects # pylint: disable=import-outside-toplevel
+
+ if not self.decorators or not bases._is_property(self):
+ yield self
+ return InferenceErrorInfo(node=self, context=context)
+
+ # When inferring a property, we instantiate a new `objects.Property` object,
+ # which in turn, because it inherits from `FunctionDef`, sets itself in the locals
+ # of the wrapping frame. This means that every time we infer a property, the locals
+ # are mutated with a new instance of the property. To avoid this, we detect this
+ # scenario and avoid passing the `parent` argument to the constructor.
+ parent_frame = self.parent.frame()
+ property_already_in_parent_locals = self.name in parent_frame.locals and any(
+ isinstance(val, objects.Property) for val in parent_frame.locals[self.name]
+ )
+ # We also don't want to pass parent if the definition is within a Try node
+ if isinstance(
+ self.parent,
+ (node_classes.TryExcept, node_classes.TryFinally, node_classes.If),
+ ):
+ property_already_in_parent_locals = True
+
+ prop_func = objects.Property(
+ function=self,
+ name=self.name,
+ lineno=self.lineno,
+ parent=self.parent if not property_already_in_parent_locals else None,
+ col_offset=self.col_offset,
+ )
+ if property_already_in_parent_locals:
+ prop_func.parent = self.parent
+ prop_func.postinit(body=[], args=self.args, doc_node=self.doc_node)
+ yield prop_func
+ return InferenceErrorInfo(node=self, context=context)
+
def infer_yield_result(self, context: InferenceContext | None = None):
"""Infer what the function yields when called
@@ -1600,7 +1654,7 @@ def get_children(self):
yield from self.body
def scope_lookup(
- self, node: node_classes.LookupMixIn, name: str, offset: int = 0
+ self, node: LookupMixIn, name: str, offset: int = 0
) -> tuple[LocalsDictNodeNG, list[nodes.NodeNG]]:
"""Lookup where the given name is assigned."""
if name == "__class__":
@@ -1848,7 +1902,9 @@ def __init__(
for local_name, node in self.implicit_locals():
self.add_local_node(node, local_name)
- infer_binary_op: ClassVar[InferBinaryOp[ClassDef]]
+ infer_binary_op: ClassVar[
+ InferBinaryOp[ClassDef]
+ ] = protocols.instance_class_infer_binary_op
def implicit_parameters(self) -> Literal[1]:
return 1
@@ -2080,7 +2136,7 @@ def infer_call_result(
yield self.instantiate_class()
def scope_lookup(
- self, node: node_classes.LookupMixIn, name: str, offset: int = 0
+ self, node: LookupMixIn, name: str, offset: int = 0
) -> tuple[LocalsDictNodeNG, list[nodes.NodeNG]]:
"""Lookup where the given name is assigned.
@@ -2875,3 +2931,8 @@ def frame(self: _T, *, future: Literal[None, True] = None) -> _T:
:returns: The node itself.
"""
return self
+
+ def _infer(
+ self, context: InferenceContext | None = None, **kwargs: Any
+ ) -> Iterator[ClassDef]:
+ yield self
diff --git a/astroid/protocols.py b/astroid/protocols.py
index e3b89b7ef7..f37c9c3256 100644
--- a/astroid/protocols.py
+++ b/astroid/protocols.py
@@ -12,9 +12,9 @@
import itertools
import operator as operator_mod
from collections.abc import Callable, Generator, Iterator, Sequence
-from typing import Any, TypeVar
+from typing import TYPE_CHECKING, Any, TypeVar
-from astroid import arguments, bases, decorators, helpers, nodes, objects, util
+from astroid import bases, decorators, nodes, util
from astroid.const import Context
from astroid.context import InferenceContext, copy_context
from astroid.exceptions import (
@@ -31,47 +31,11 @@
SuccessfulInferenceResult,
)
-_TupleListNodeT = TypeVar("_TupleListNodeT", nodes.Tuple, nodes.List)
-
-
-def _reflected_name(name) -> str:
- return "__r" + name[2:]
-
-
-def _augmented_name(name) -> str:
- return "__i" + name[2:]
-
+if TYPE_CHECKING:
+ _TupleListNodeT = TypeVar("_TupleListNodeT", nodes.Tuple, nodes.List)
_CONTEXTLIB_MGR = "contextlib.contextmanager"
-BIN_OP_METHOD = {
- "+": "__add__",
- "-": "__sub__",
- "/": "__truediv__",
- "//": "__floordiv__",
- "*": "__mul__",
- "**": "__pow__",
- "%": "__mod__",
- "&": "__and__",
- "|": "__or__",
- "^": "__xor__",
- "<<": "__lshift__",
- ">>": "__rshift__",
- "@": "__matmul__",
-}
-
-REFLECTED_BIN_OP_METHOD = {
- key: _reflected_name(value) for (key, value) in BIN_OP_METHOD.items()
-}
-AUGMENTED_OP_METHOD = {
- key + "=": _augmented_name(value) for (key, value) in BIN_OP_METHOD.items()
-}
-UNARY_OP_METHOD = {
- "+": "__pos__",
- "-": "__neg__",
- "~": "__invert__",
- "not": None, # XXX not '__nonzero__'
-}
_UNARY_OPERATORS: dict[str, Callable[[Any], Any]] = {
"+": operator_mod.pos,
"-": operator_mod.neg,
@@ -93,11 +57,25 @@ def _infer_unary_op(obj: Any, op: str) -> ConstFactoryResult:
return nodes.const_factory(value)
-nodes.Tuple.infer_unary_op = lambda self, op: _infer_unary_op(tuple(self.elts), op)
-nodes.List.infer_unary_op = lambda self, op: _infer_unary_op(self.elts, op)
-nodes.Set.infer_unary_op = lambda self, op: _infer_unary_op(set(self.elts), op)
-nodes.Const.infer_unary_op = lambda self, op: _infer_unary_op(self.value, op)
-nodes.Dict.infer_unary_op = lambda self, op: _infer_unary_op(dict(self.items), op)
+def tuple_infer_unary_op(self, op):
+ return _infer_unary_op(tuple(self.elts), op)
+
+
+def list_infer_unary_op(self, op):
+ return _infer_unary_op(self.elts, op)
+
+
+def set_infer_unary_op(self, op):
+ return _infer_unary_op(set(self.elts), op)
+
+
+def const_infer_unary_op(self, op):
+ return _infer_unary_op(self.value, op)
+
+
+def dict_infer_unary_op(self, op):
+ return _infer_unary_op(dict(self.items), op)
+
# Binary operations
@@ -157,15 +135,14 @@ def const_infer_binary_op(
yield not_implemented
-nodes.Const.infer_binary_op = const_infer_binary_op
-
-
def _multiply_seq_by_int(
self: _TupleListNodeT,
opnode: nodes.AugAssign | nodes.BinOp,
other: nodes.Const,
context: InferenceContext,
) -> _TupleListNodeT:
+ from astroid import helpers # pylint: disable=import-outside-toplevel
+
node = self.__class__(parent=opnode)
filtered_elts = (
helpers.safe_infer(elt, context) or util.Uninferable
@@ -205,6 +182,8 @@ def tl_infer_binary_op(
or list. This refers to the left-hand side of the operation, so:
'tuple() + 1' or '[] + A()'
"""
+ from astroid import helpers # pylint: disable=import-outside-toplevel
+
# For tuples and list the boundnode is no longer the tuple or list instance
context.boundnode = None
not_implemented = nodes.Const(NotImplemented)
@@ -233,13 +212,9 @@ def tl_infer_binary_op(
yield not_implemented
-nodes.Tuple.infer_binary_op = tl_infer_binary_op
-nodes.List.infer_binary_op = tl_infer_binary_op
-
-
@decorators.yes_if_nothing_inferred
def instance_class_infer_binary_op(
- self: bases.Instance | nodes.ClassDef,
+ self: nodes.ClassDef,
opnode: nodes.AugAssign | nodes.BinOp,
operator: str,
other: InferenceResult,
@@ -249,12 +224,8 @@ def instance_class_infer_binary_op(
return method.infer_call_result(self, context)
-bases.Instance.infer_binary_op = instance_class_infer_binary_op
-nodes.ClassDef.infer_binary_op = instance_class_infer_binary_op
-
-
# assignment ##################################################################
-
+# pylint: disable-next=pointless-string-statement
"""The assigned_stmts method is responsible to return the assigned statement
(e.g. not inferred) according to the assignment type.
@@ -337,10 +308,6 @@ def for_assigned_stmts(
}
-nodes.For.assigned_stmts = for_assigned_stmts
-nodes.Comprehension.assigned_stmts = for_assigned_stmts
-
-
def sequence_assigned_stmts(
self: nodes.Tuple | nodes.List,
node: node_classes.AssignedStmtsPossibleNode = None,
@@ -365,10 +332,6 @@ def sequence_assigned_stmts(
)
-nodes.Tuple.assigned_stmts = sequence_assigned_stmts
-nodes.List.assigned_stmts = sequence_assigned_stmts
-
-
def assend_assigned_stmts(
self: nodes.AssignName | nodes.AssignAttr,
node: node_classes.AssignedStmtsPossibleNode = None,
@@ -378,15 +341,13 @@ def assend_assigned_stmts(
return self.parent.assigned_stmts(node=self, context=context)
-nodes.AssignName.assigned_stmts = assend_assigned_stmts
-nodes.AssignAttr.assigned_stmts = assend_assigned_stmts
-
-
def _arguments_infer_argname(
self, name: str | None, context: InferenceContext
) -> Generator[InferenceResult, None, None]:
# arguments information may be missing, in which case we can't do anything
# more
+ from astroid import arguments # pylint: disable=import-outside-toplevel
+
if not (self.arguments or self.vararg or self.kwarg):
yield util.Uninferable
return
@@ -449,6 +410,8 @@ def arguments_assigned_stmts(
context: InferenceContext | None = None,
assign_path: list[int] | None = None,
) -> Any:
+ from astroid import arguments # pylint: disable=import-outside-toplevel
+
try:
node_name = node.name # type: ignore[union-attr]
except AttributeError:
@@ -472,9 +435,6 @@ def arguments_assigned_stmts(
return _arguments_infer_argname(self, node_name, context)
-nodes.Arguments.assigned_stmts = arguments_assigned_stmts
-
-
@decorators.raise_if_nothing_inferred
def assign_assigned_stmts(
self: nodes.AugAssign | nodes.Assign | nodes.AnnAssign,
@@ -510,11 +470,6 @@ def assign_annassigned_stmts(
yield inferred
-nodes.Assign.assigned_stmts = assign_assigned_stmts
-nodes.AnnAssign.assigned_stmts = assign_annassigned_stmts
-nodes.AugAssign.assigned_stmts = assign_assigned_stmts
-
-
def _resolve_assignment_parts(parts, assign_path, context):
"""Recursive function to resolve multiple assignments."""
assign_path = assign_path[:]
@@ -562,6 +517,8 @@ def excepthandler_assigned_stmts(
context: InferenceContext | None = None,
assign_path: list[int] | None = None,
) -> Any:
+ from astroid import objects # pylint: disable=import-outside-toplevel
+
for assigned in node_classes.unpack_infer(self.type):
if isinstance(assigned, nodes.ClassDef):
assigned = objects.ExceptionInstance(assigned)
@@ -575,9 +532,6 @@ def excepthandler_assigned_stmts(
}
-nodes.ExceptHandler.assigned_stmts = excepthandler_assigned_stmts
-
-
def _infer_context_manager(self, mgr, context):
try:
inferred = next(mgr.infer(context=context))
@@ -696,9 +650,6 @@ def __enter__(self):
}
-nodes.With.assigned_stmts = with_assigned_stmts
-
-
@decorators.raise_if_nothing_inferred
def named_expr_assigned_stmts(
self: nodes.NamedExpr,
@@ -718,9 +669,6 @@ def named_expr_assigned_stmts(
)
-nodes.NamedExpr.assigned_stmts = named_expr_assigned_stmts
-
-
@decorators.yes_if_nothing_inferred
def starred_assigned_stmts( # noqa: C901
self: nodes.Starred,
@@ -918,9 +866,6 @@ def _determine_starred_iteration_lookups(
yield util.Uninferable
-nodes.Starred.assigned_stmts = starred_assigned_stmts
-
-
@decorators.yes_if_nothing_inferred
def match_mapping_assigned_stmts(
self: nodes.MatchMapping,
@@ -935,9 +880,6 @@ def match_mapping_assigned_stmts(
yield
-nodes.MatchMapping.assigned_stmts = match_mapping_assigned_stmts
-
-
@decorators.yes_if_nothing_inferred
def match_star_assigned_stmts(
self: nodes.MatchStar,
@@ -952,9 +894,6 @@ def match_star_assigned_stmts(
yield
-nodes.MatchStar.assigned_stmts = match_star_assigned_stmts
-
-
@decorators.yes_if_nothing_inferred
def match_as_assigned_stmts(
self: nodes.MatchAs,
@@ -971,6 +910,3 @@ def match_as_assigned_stmts(
and self.pattern is None
):
yield self.parent.parent.subject
-
-
-nodes.MatchAs.assigned_stmts = match_as_assigned_stmts
diff --git a/doc/api/base_nodes.rst b/doc/api/base_nodes.rst
index 6253ce5ce5..14f7ab1071 100644
--- a/doc/api/base_nodes.rst
+++ b/doc/api/base_nodes.rst
@@ -12,7 +12,7 @@ These are abstract node classes that :ref:`other nodes <nodes>` inherit from.
astroid.nodes._base_nodes.FilterStmtsBaseNode
astroid.nodes._base_nodes.ImportNode
astroid.nodes.LocalsDictNodeNG
- astroid.nodes.node_classes.LookupMixIn
+ astroid.nodes._base_nodes.LookupMixIn
astroid.nodes.NodeNG
astroid.nodes._base_nodes.ParentAssignNode
astroid.nodes.Statement
@@ -33,7 +33,7 @@ These are abstract node classes that :ref:`other nodes <nodes>` inherit from.
.. autoclass:: astroid.nodes.LocalsDictNodeNG
-.. autoclass:: astroid.nodes.node_classes.LookupMixIn
+.. autoclass:: astroid.nodes._base_nodes.LookupMixIn
.. autoclass:: astroid.nodes.NodeNG
|
Remove monkey-patching of methods onto classes
In [this comment](https://github.com/PyCQA/astroid/issues/170#issuecomment-163118573), @PCManticore stated that there was a plan to remove monkey-patching of methods onto classes. inference.py and protocols.py seem to suggest that this hasn't happened.
Is this still a design goal?
It looks to me like this would be a fairly mechanical change. I am assuming that since it hasn't happened yet, I am missing something. Is it simply a "haven't had time" issue?
|
2171
|
pylint-dev/astroid
|
diff --git a/tests/test_inference.py b/tests/test_inference.py
index 96778b89d3..03d0e2c744 100644
--- a/tests/test_inference.py
+++ b/tests/test_inference.py
@@ -41,7 +41,6 @@
InferenceError,
NotFoundError,
)
-from astroid.inference import infer_end as inference_infer_end
from astroid.objects import ExceptionInstance
from . import resources
@@ -71,7 +70,7 @@ def infer_default(self: Any, *args: InferenceContext) -> None:
raise InferenceError
infer_default = decoratorsmod.path_wrapper(infer_default)
- infer_end = decoratorsmod.path_wrapper(inference_infer_end)
+ infer_end = decoratorsmod.path_wrapper(Slice._infer)
with self.assertRaises(InferenceError):
next(infer_default(1))
self.assertEqual(next(infer_end(1)), 1)
diff --git a/tests/test_manager.py b/tests/test_manager.py
index 56b09945ba..6455a6e5d3 100644
--- a/tests/test_manager.py
+++ b/tests/test_manager.py
@@ -409,7 +409,7 @@ def test_borg(self) -> None:
class ClearCacheTest(unittest.TestCase):
def test_clear_cache_clears_other_lru_caches(self) -> None:
lrus = (
- astroid.nodes.node_classes.LookupMixIn.lookup,
+ astroid.nodes._base_nodes.LookupMixIn.lookup,
astroid.modutils._cache_normalize_path_,
util.is_namespace,
astroid.interpreter.objectmodel.ObjectModel.attributes,
diff --git a/tests/test_nodes.py b/tests/test_nodes.py
index 7a4990cddb..41429fc5ab 100644
--- a/tests/test_nodes.py
+++ b/tests/test_nodes.py
@@ -1916,8 +1916,7 @@ def return_from_match(x):
[
node
for node in astroid.nodes.ALL_NODE_CLASSES
- if node.__name__
- not in ["_BaseContainer", "BaseContainer", "NodeNG", "const_factory"]
+ if node.__name__ not in ["BaseContainer", "NodeNG", "const_factory"]
],
)
@pytest.mark.filterwarnings("error")
|
none
|
[
"tests/test_manager.py::ClearCacheTest::test_clear_cache_clears_other_lru_caches"
] |
[
"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_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_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_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_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_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_manager.py::AstroidManagerTest::test_ast_from_class",
"tests/test_manager.py::AstroidManagerTest::test_ast_from_class_attr_error",
"tests/test_manager.py::AstroidManagerTest::test_ast_from_class_with_module",
"tests/test_manager.py::AstroidManagerTest::test_ast_from_file",
"tests/test_manager.py::AstroidManagerTest::test_ast_from_file_astro_builder",
"tests/test_manager.py::AstroidManagerTest::test_ast_from_file_cache",
"tests/test_manager.py::AstroidManagerTest::test_ast_from_file_name_astro_builder_exception",
"tests/test_manager.py::AstroidManagerTest::test_ast_from_module",
"tests/test_manager.py::AstroidManagerTest::test_ast_from_module_cache",
"tests/test_manager.py::AstroidManagerTest::test_ast_from_module_name",
"tests/test_manager.py::AstroidManagerTest::test_ast_from_module_name_astro_builder_exception",
"tests/test_manager.py::AstroidManagerTest::test_ast_from_module_name_egg",
"tests/test_manager.py::AstroidManagerTest::test_ast_from_module_name_not_python_source",
"tests/test_manager.py::AstroidManagerTest::test_ast_from_module_name_pyz",
"tests/test_manager.py::AstroidManagerTest::test_ast_from_module_name_zip",
"tests/test_manager.py::AstroidManagerTest::test_ast_from_namespace_pkg_resources",
"tests/test_manager.py::AstroidManagerTest::test_ast_from_namespace_pkgutil",
"tests/test_manager.py::AstroidManagerTest::test_ast_from_string",
"tests/test_manager.py::AstroidManagerTest::test_do_not_expose_main",
"tests/test_manager.py::AstroidManagerTest::test_failed_import_hooks",
"tests/test_manager.py::AstroidManagerTest::test_file_from_module",
"tests/test_manager.py::AstroidManagerTest::test_file_from_module_name_astro_building_exception",
"tests/test_manager.py::AstroidManagerTest::test_implicit_namespace_package",
"tests/test_manager.py::AstroidManagerTest::test_module_is_not_namespace",
"tests/test_manager.py::AstroidManagerTest::test_module_unexpectedly_missing_path",
"tests/test_manager.py::AstroidManagerTest::test_module_unexpectedly_missing_spec",
"tests/test_manager.py::AstroidManagerTest::test_module_unexpectedly_spec_is_none",
"tests/test_manager.py::AstroidManagerTest::test_namespace_and_file_mismatch",
"tests/test_manager.py::AstroidManagerTest::test_namespace_package_pth_support",
"tests/test_manager.py::AstroidManagerTest::test_nested_namespace_import",
"tests/test_manager.py::AstroidManagerTest::test_raises_exception_for_empty_modname",
"tests/test_manager.py::AstroidManagerTest::test_same_name_import_module",
"tests/test_manager.py::AstroidManagerTest::test_submodule_homonym_with_non_module",
"tests/test_manager.py::AstroidManagerTest::test_zip_import_data",
"tests/test_manager.py::AstroidManagerTest::test_zip_import_data_without_zipimport",
"tests/test_manager.py::IsolatedAstroidManagerTest::test_no_user_warning",
"tests/test_manager.py::BorgAstroidManagerTC::test_borg",
"tests/test_manager.py::ClearCacheTest::test_brain_plugins_reloaded_after_clearing_cache",
"tests/test_manager.py::ClearCacheTest::test_builtins_inference_after_clearing_cache",
"tests/test_manager.py::ClearCacheTest::test_builtins_inference_after_clearing_cache_manually",
"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[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[AssignName]",
"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[AsyncWith]",
"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[BoolOp]",
"tests/test_nodes.py::test_str_repr_no_warnings[Break]",
"tests/test_nodes.py::test_str_repr_no_warnings[Call]",
"tests/test_nodes.py::test_str_repr_no_warnings[ClassDef]",
"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[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[Decorators]",
"tests/test_nodes.py::test_str_repr_no_warnings[DelAttr]",
"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[DictComp]",
"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[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[Global]",
"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[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[Keyword]",
"tests/test_nodes.py::test_str_repr_no_warnings[Lambda]",
"tests/test_nodes.py::test_str_repr_no_warnings[List]",
"tests/test_nodes.py::test_str_repr_no_warnings[ListComp]",
"tests/test_nodes.py::test_str_repr_no_warnings[LocalsDictNodeNG]",
"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[MatchSingleton]",
"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[Name]",
"tests/test_nodes.py::test_str_repr_no_warnings[NamedExpr]",
"tests/test_nodes.py::test_str_repr_no_warnings[Nonlocal]",
"tests/test_nodes.py::test_str_repr_no_warnings[ParamSpec]",
"tests/test_nodes.py::test_str_repr_no_warnings[TypeVarTuple]",
"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[Raise]",
"tests/test_nodes.py::test_str_repr_no_warnings[Return]",
"tests/test_nodes.py::test_str_repr_no_warnings[Set]",
"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[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[TypeAlias]",
"tests/test_nodes.py::test_str_repr_no_warnings[TypeVar]",
"tests/test_nodes.py::test_str_repr_no_warnings[UnaryOp]",
"tests/test_nodes.py::test_str_repr_no_warnings[Unknown]",
"tests/test_nodes.py::test_str_repr_no_warnings[While]",
"tests/test_nodes.py::test_str_repr_no_warnings[With]",
"tests/test_nodes.py::test_str_repr_no_warnings[Yield]",
"tests/test_nodes.py::test_str_repr_no_warnings[YieldFrom]",
"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": 16,
"hunks": 112,
"lines": 3075
}
|
I'm seeing similar 2.5-related issues with Enum subclasses. Particularly, `Enum.__members__.items()`. Pylint complains about `__members__` have not member `items` which is incorrect.
With pylint 2.6.2, and astroid 2.4.2, everything is fine. With astroid 2.5:
(note lazy_object_proxy 1.5.2 is present)
Traceback (most recent call last):
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 582, in _build_master
ws.require(__requires__)
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 899, in require
needed = self.resolve(parse_requirements(requirements))
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 790, in resolve
raise VersionConflict(dist, req).with_context(dependent_req)
pkg_resources.ContextualVersionConflict: (lazy-object-proxy 0.0.0 (/usr/lib64/python3.9/site-packages), Requirement.parse('lazy_object_proxy>=1.4.0'), {'astroid'})
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/bin/pylint-3", line 33, in <module>
sys.exit(load_entry_point('pylint==2.6.2', 'console_scripts', 'pylint')())
File "/usr/lib/python3.9/site-packages/pylint/__init__.py", line 19, in run_pylint
from pylint.lint import Run as PylintRun
File "/usr/lib/python3.9/site-packages/pylint/lint/__init__.py", line 75, in <module>
from pylint.lint.check_parallel import check_parallel
File "/usr/lib/python3.9/site-packages/pylint/lint/check_parallel.py", line 7, in <module>
from pylint import reporters
File "/usr/lib/python3.9/site-packages/pylint/reporters/__init__.py", line 24, in <module>
from pylint import utils
File "/usr/lib/python3.9/site-packages/pylint/utils/__init__.py", line 47, in <module>
from pylint.utils.ast_walker import ASTWalker
File "/usr/lib/python3.9/site-packages/pylint/utils/ast_walker.py", line 6, in <module>
from astroid import nodes
File "/usr/lib/python3.9/site-packages/astroid/__init__.py", line 66, in <module>
from astroid.nodes import *
File "/usr/lib/python3.9/site-packages/astroid/nodes.py", line 23, in <module>
from astroid.node_classes import (
File "/usr/lib/python3.9/site-packages/astroid/node_classes.py", line 44, in <module>
from astroid import bases
File "/usr/lib/python3.9/site-packages/astroid/bases.py", line 36, in <module>
MANAGER = manager.AstroidManager()
File "/usr/lib/python3.9/site-packages/astroid/util.py", line 27, in <lambda>
lambda: importlib.import_module("." + module_name, "astroid")
File "/usr/lib64/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/usr/lib/python3.9/site-packages/astroid/manager.py", line 29, in <module>
from astroid.interpreter._import import spec
File "/usr/lib/python3.9/site-packages/astroid/interpreter/_import/spec.py", line 29, in <module>
from . import util
File "/usr/lib/python3.9/site-packages/astroid/interpreter/_import/util.py", line 4, in <module>
import pkg_resources
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 3257, in <module>
def _initialize_master_working_set():
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 3240, in _call_aside
f(*args, **kwargs)
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 3269, in _initialize_master_working_set
working_set = WorkingSet._build_master()
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 584, in _build_master
return cls._build_from_requirements(__requires__)
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 597, in _build_from_requirements
dists = ws.resolve(reqs, Environment())
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 785, in resolve
raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'lazy_object_proxy>=1.4.0' distribution was not found and is required by astroid
@drfunjohn thanks for your report.
@chiefnoah and @limburgher can you open separate issues with a clear reproducer?
Thanks in advance
Done, thanks! https://github.com/PyCQA/astroid/issues/897
@drfunjohn i identified the faulty commit (cc3bfc5dc94062a582b7b3226598f09d7ec7044e). I am looking for a patch.
Wow, thanks for quick response.
You are welcome but the patch seems tricky...
@drfunjohn i reverted the faulty commit in #901. I am the author of this commit. It was a try to improve the inference of `numpy` objects.
Apologies for the regression you faced.
|
0f97f79c0aa50ed0506c09db729f906450b37652
|
[
"https://github.com/pylint-dev/astroid/commit/ac0d01e5f0fcc5bc58bf31e5d95fd08dfa35a118",
"https://github.com/pylint-dev/astroid/commit/4b1aefcfda6b2de4b86fd6d2b813cc47008cce7a",
"https://github.com/pylint-dev/astroid/commit/6f885833bc27a5f2ac6555d75cdb0786fa74b08a",
"https://github.com/pylint-dev/astroid/commit/aecfb37fcaadff8cb346619bd27bfafd1e347f08",
"https://github.com/pylint-dev/astroid/commit/33c8c193f93e2c6c68d9398893e3a08e2d6f33b7"
] | 2021-02-17T11:37:55
|
I'm seeing similar 2.5-related issues with Enum subclasses. Particularly, `Enum.__members__.items()`. Pylint complains about `__members__` have not member `items` which is incorrect.
With pylint 2.6.2, and astroid 2.4.2, everything is fine. With astroid 2.5:
(note lazy_object_proxy 1.5.2 is present)
Traceback (most recent call last):
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 582, in _build_master
ws.require(__requires__)
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 899, in require
needed = self.resolve(parse_requirements(requirements))
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 790, in resolve
raise VersionConflict(dist, req).with_context(dependent_req)
pkg_resources.ContextualVersionConflict: (lazy-object-proxy 0.0.0 (/usr/lib64/python3.9/site-packages), Requirement.parse('lazy_object_proxy>=1.4.0'), {'astroid'})
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/bin/pylint-3", line 33, in <module>
sys.exit(load_entry_point('pylint==2.6.2', 'console_scripts', 'pylint')())
File "/usr/lib/python3.9/site-packages/pylint/__init__.py", line 19, in run_pylint
from pylint.lint import Run as PylintRun
File "/usr/lib/python3.9/site-packages/pylint/lint/__init__.py", line 75, in <module>
from pylint.lint.check_parallel import check_parallel
File "/usr/lib/python3.9/site-packages/pylint/lint/check_parallel.py", line 7, in <module>
from pylint import reporters
File "/usr/lib/python3.9/site-packages/pylint/reporters/__init__.py", line 24, in <module>
from pylint import utils
File "/usr/lib/python3.9/site-packages/pylint/utils/__init__.py", line 47, in <module>
from pylint.utils.ast_walker import ASTWalker
File "/usr/lib/python3.9/site-packages/pylint/utils/ast_walker.py", line 6, in <module>
from astroid import nodes
File "/usr/lib/python3.9/site-packages/astroid/__init__.py", line 66, in <module>
from astroid.nodes import *
File "/usr/lib/python3.9/site-packages/astroid/nodes.py", line 23, in <module>
from astroid.node_classes import (
File "/usr/lib/python3.9/site-packages/astroid/node_classes.py", line 44, in <module>
from astroid import bases
File "/usr/lib/python3.9/site-packages/astroid/bases.py", line 36, in <module>
MANAGER = manager.AstroidManager()
File "/usr/lib/python3.9/site-packages/astroid/util.py", line 27, in <lambda>
lambda: importlib.import_module("." + module_name, "astroid")
File "/usr/lib64/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/usr/lib/python3.9/site-packages/astroid/manager.py", line 29, in <module>
from astroid.interpreter._import import spec
File "/usr/lib/python3.9/site-packages/astroid/interpreter/_import/spec.py", line 29, in <module>
from . import util
File "/usr/lib/python3.9/site-packages/astroid/interpreter/_import/util.py", line 4, in <module>
import pkg_resources
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 3257, in <module>
def _initialize_master_working_set():
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 3240, in _call_aside
f(*args, **kwargs)
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 3269, in _initialize_master_working_set
working_set = WorkingSet._build_master()
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 584, in _build_master
return cls._build_from_requirements(__requires__)
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 597, in _build_from_requirements
dists = ws.resolve(reqs, Environment())
File "/usr/lib/python3.9/site-packages/pkg_resources/__init__.py", line 785, in resolve
raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'lazy_object_proxy>=1.4.0' distribution was not found and is required by astroid
@drfunjohn thanks for your report.
@chiefnoah and @limburgher can you open separate issues with a clear reproducer?
Thanks in advance
Done, thanks! https://github.com/PyCQA/astroid/issues/897
@drfunjohn i identified the faulty commit (cc3bfc5dc94062a582b7b3226598f09d7ec7044e). I am looking for a patch.
Wow, thanks for quick response.
You are welcome but the patch seems tricky...
|
pylint-dev__astroid-901
|
[
"895"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index 2c454cb8df..519fa249f3 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -2,6 +2,15 @@
astroid's ChangeLog
===================
+What's New in astroid 2.5.1?
+============================
+Release Date: TBA
+
+* The ``context.path`` is reverted to a set because otherwise it leds to false positives
+ for non `numpy` functions.
+
+ Closes #895 #899
+
What's New in astroid 2.5?
============================
Release Date: 2021-02-15
diff --git a/astroid/context.py b/astroid/context.py
index 27d1897f50..b667f8c2cd 100644
--- a/astroid/context.py
+++ b/astroid/context.py
@@ -30,10 +30,8 @@ class InferenceContext:
"extra_context",
)
- maximum_path_visit = 3
-
def __init__(self, path=None, inferred=None):
- self.path = path or dict()
+ self.path = path or set()
"""
:type: set(tuple(NodeNG, optional(str)))
@@ -90,10 +88,10 @@ def push(self, node):
Allows one to see if the given node has already
been looked at for this inference context"""
name = self.lookupname
- if self.path.get((node, name), 0) >= self.maximum_path_visit:
+ if (node, name) in self.path:
return True
- self.path[(node, name)] = self.path.setdefault((node, name), 0) + 1
+ self.path.add((node, name))
return False
def clone(self):
@@ -111,7 +109,7 @@ def clone(self):
@contextlib.contextmanager
def restore_path(self):
- path = dict(self.path)
+ path = set(self.path)
yield
self.path = path
|
Unexpected error from pylint after upgrade to astroid 2.5.
### Steps to reproduce
astroid 2.5
pylint 2.6.0
elasticsearch 7.10.1
python 3.7.3
```
from elasticsearch import Elasticsearch
es = Elasticsearch(["test"])
es.indices.delete(index="test", ignore=[400, 404])
```
1. run pylint
### Current behavior
line 3 >>> E1123: Unexpected keyword argument 'ignore' in method call (unexpected-keyword-arg)
### Expected behavior
astroid 2.4.2: no error from pylint
|
901
|
pylint-dev/astroid
|
diff --git a/tests/unittest_brain_numpy_core_umath.py b/tests/unittest_brain_numpy_core_umath.py
index f384ea2539..593c9f89f9 100644
--- a/tests/unittest_brain_numpy_core_umath.py
+++ b/tests/unittest_brain_numpy_core_umath.py
@@ -226,9 +226,11 @@ def test_numpy_core_umath_functions_return_type(self):
with self.subTest(typ=func_):
inferred_values = list(self._inferred_numpy_func_call(func_))
self.assertTrue(
- len(inferred_values) == 1,
+ len(inferred_values) == 1
+ or len(inferred_values) == 2
+ and inferred_values[-1].pytype() is util.Uninferable,
msg="Too much inferred values ({}) for {:s}".format(
- inferred_values, func_
+ inferred_values[-1].pytype(), func_
),
)
self.assertTrue(
diff --git a/tests/unittest_inference.py b/tests/unittest_inference.py
index 55bbe9e348..edb755c188 100644
--- a/tests/unittest_inference.py
+++ b/tests/unittest_inference.py
@@ -1301,7 +1301,7 @@ def get_context_data(self, **kwargs):
result = node.inferred()
assert len(result) == 2
assert isinstance(result[0], nodes.Dict)
- assert isinstance(result[1], nodes.Dict)
+ assert result[1] is util.Uninferable
def test_python25_no_relative_import(self):
ast = resources.build_file("data/package/absimport.py")
@@ -3686,8 +3686,7 @@ def __getitem__(self, name):
flow = AttributeDict()
flow['app'] = AttributeDict()
flow['app']['config'] = AttributeDict()
- flow['app']['config']['doffing'] = AttributeDict()
- flow['app']['config']['doffing']['thinkto'] = AttributeDict() #@
+ flow['app']['config']['doffing'] = AttributeDict() #@
"""
)
self.assertIsNone(helpers.safe_infer(ast_node.targets[0]))
diff --git a/tests/unittest_regrtest.py b/tests/unittest_regrtest.py
index eeedd35327..042c97f098 100644
--- a/tests/unittest_regrtest.py
+++ b/tests/unittest_regrtest.py
@@ -99,7 +99,7 @@ def test_numpy_crash(self):
astroid = builder.string_build(data, __name__, __file__)
callfunc = astroid.body[1].value.func
inferred = callfunc.inferred()
- self.assertEqual(len(inferred), 1)
+ self.assertEqual(len(inferred), 2)
def test_nameconstant(self):
# used to fail for Python 3.4
|
none
|
[
"tests/unittest_inference.py::InferenceTest::test_no_runtime_error_in_repeat_inference",
"tests/unittest_inference.py::InferenceTest::test_subscript_inference_error"
] |
[
"tests/unittest_inference.py::InferenceUtilsTest::test_path_wrapper",
"tests/unittest_inference.py::InferenceTest::test_With_metaclass_subclasses_arguments_are_classes_not_instances",
"tests/unittest_inference.py::InferenceTest::test_With_metaclass_with_partial_imported_name",
"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_classes_with_metaclass",
"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_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_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_no_infinite_ancestor_loop",
"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_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_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_classes_with_metaclass",
"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::InferenceTest::test_with_metaclass__getitem__",
"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_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_regrtest.py::NonRegressionTests::test_ancestors_missing_from_function",
"tests/unittest_regrtest.py::NonRegressionTests::test_ancestors_patching_class_recursion",
"tests/unittest_regrtest.py::NonRegressionTests::test_ancestors_yes_in_bases",
"tests/unittest_regrtest.py::NonRegressionTests::test_binop_generates_nodes_with_parents",
"tests/unittest_regrtest.py::NonRegressionTests::test_decorator_callchain_issue42",
"tests/unittest_regrtest.py::NonRegressionTests::test_decorator_names_inference_error_leaking",
"tests/unittest_regrtest.py::NonRegressionTests::test_filter_stmts_scoping",
"tests/unittest_regrtest.py::NonRegressionTests::test_living_property",
"tests/unittest_regrtest.py::NonRegressionTests::test_module_path",
"tests/unittest_regrtest.py::NonRegressionTests::test_nameconstant",
"tests/unittest_regrtest.py::NonRegressionTests::test_package_sidepackage",
"tests/unittest_regrtest.py::NonRegressionTests::test_recursion_regression_issue25",
"tests/unittest_regrtest.py::NonRegressionTests::test_recursive_property_method",
"tests/unittest_regrtest.py::NonRegressionTests::test_regression_inference_of_self_in_lambda",
"tests/unittest_regrtest.py::NonRegressionTests::test_ssl_protocol",
"tests/unittest_regrtest.py::NonRegressionTests::test_unicode_in_docstring",
"tests/unittest_regrtest.py::NonRegressionTests::test_uninferable_string_argument_of_namedtuple",
"tests/unittest_regrtest.py::test_ancestor_looking_up_redefined_function",
"tests/unittest_regrtest.py::test_crash_in_dunder_inference_prevented",
"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": 2,
"hunks": 4,
"lines": 19
}
|
dc13d5b66cec53b26b3c04df07f14724588a09a6
|
[
"https://github.com/pylint-dev/astroid/commit/8bd53f0ed71058981cf0bb37ba41511ce77f199b"
] | 2023-12-12T05:18:57
|
pylint-dev__astroid-2345
|
[
"2071"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index 7b49fdf5b3..f0940c60d0 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -12,6 +12,11 @@ Release date: TBA
Refs pylint-dev/pylint#9193
+* Add ``__main__`` as a possible inferred value for ``__name__`` to improve
+ control flow inference around ``if __name__ == "__main__":`` guards.
+
+ Closes #2071
+
What's New in astroid 3.0.2?
============================
diff --git a/astroid/nodes/scoped_nodes/scoped_nodes.py b/astroid/nodes/scoped_nodes/scoped_nodes.py
index e8b1aef4f1..2d492f1b64 100644
--- a/astroid/nodes/scoped_nodes/scoped_nodes.py
+++ b/astroid/nodes/scoped_nodes/scoped_nodes.py
@@ -41,7 +41,15 @@
from astroid.interpreter.dunder_lookup import lookup
from astroid.interpreter.objectmodel import ClassModel, FunctionModel, ModuleModel
from astroid.manager import AstroidManager
-from astroid.nodes import Arguments, Const, NodeNG, Unknown, _base_nodes, node_classes
+from astroid.nodes import (
+ Arguments,
+ Const,
+ NodeNG,
+ Unknown,
+ _base_nodes,
+ const_factory,
+ node_classes,
+)
from astroid.nodes.scoped_nodes.mixin import ComprehensionScope, LocalsDictNodeNG
from astroid.nodes.scoped_nodes.utils import builtin_lookup
from astroid.nodes.utils import Position
@@ -346,6 +354,8 @@ def getattr(
if name in self.special_attributes and not ignore_locals and not name_in_locals:
result = [self.special_attributes.lookup(name)]
+ if name == "__name__":
+ result.append(const_factory("__main__"))
elif not ignore_locals and name_in_locals:
result = self.locals[name]
elif self.package:
|
Should infer more values for `== __name__` (possibly other dunders)
### Steps to reproduce
```python
>>> n = extract_node("if __name__ == '__main__': ...")
>>> n.test.inferred()
[<Const.bool l.None at 0x10baadf90>]
>>> n.test.inferred()[0]
<Const.bool l.None at 0x10c71eb50>
>>> n.test.inferred()[0].value
False
```
### Current behavior
1 inferred value
### Expected behavior
2 inferred values (True, False)
### `python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"` output
2.16.0dev0
### More info
Inspired by pylint-dev/pylint#8167
|
2345
|
pylint-dev/astroid
|
diff --git a/tests/test_scoped_nodes.py b/tests/test_scoped_nodes.py
index 1bc5af78b6..995f0428d9 100644
--- a/tests/test_scoped_nodes.py
+++ b/tests/test_scoped_nodes.py
@@ -79,9 +79,11 @@ def setUp(self) -> None:
class ModuleNodeTest(ModuleLoader, unittest.TestCase):
def test_special_attributes(self) -> None:
- self.assertEqual(len(self.module.getattr("__name__")), 1)
+ self.assertEqual(len(self.module.getattr("__name__")), 2)
self.assertIsInstance(self.module.getattr("__name__")[0], nodes.Const)
self.assertEqual(self.module.getattr("__name__")[0].value, "data.module")
+ self.assertIsInstance(self.module.getattr("__name__")[1], nodes.Const)
+ self.assertEqual(self.module.getattr("__name__")[1].value, "__main__")
self.assertEqual(len(self.module.getattr("__doc__")), 1)
self.assertIsInstance(self.module.getattr("__doc__")[0], nodes.Const)
self.assertEqual(
|
none
|
[
"tests/test_scoped_nodes.py::ModuleNodeTest::test_special_attributes"
] |
[
"tests/test_scoped_nodes.py::ModuleNodeTest::test_comment_before_docstring",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_dict_interface",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_file_stream_api",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_file_stream_in_memory",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_file_stream_physical",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_getattr",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_import_1",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_import_2",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_import_unavailable_module",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_module_getattr",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_multiline_docstring",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_public_names",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name_beyond_top_level",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_singleline_docstring",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_stream_api",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_wildcard_import_names",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_without_docstring",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_abstract_methods_are_not_implicitly_none",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_argnames",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_argnames_lambda",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_decorator_builtin_descriptors",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_default_value",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_dict_interface",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_display_type",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_docstring_special_cases",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_classmethod",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_function",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_method",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_format_args",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_format_args_keyword_only_args",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_four_args",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_func_instance_attr",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_func_is_bound",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_igetattr",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_inference_error",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_is_abstract",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_is_abstract_decorated",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_is_generator",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_is_method",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_lambda_getattr",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_lambda_pytype",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_lambda_qname",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_method_init_subclass",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_multiline_docstring",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_multiline_docstring_async",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_navigation",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_no_returns_is_implicitly_none",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_only_raises_is_not_implicitly_none",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_positional_only_argnames",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_return_annotation_is_not_the_last",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_return_nothing",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_singleline_docstring",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_special_attributes",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_type_builtin_descriptor_subclasses",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_without_docstring",
"tests/test_scoped_nodes.py::ClassNodeTest::test__bases__attribute",
"tests/test_scoped_nodes.py::ClassNodeTest::test__mro__attribute",
"tests/test_scoped_nodes.py::ClassNodeTest::test_add_metaclass",
"tests/test_scoped_nodes.py::ClassNodeTest::test_all_ancestors_need_slots",
"tests/test_scoped_nodes.py::ClassNodeTest::test_ancestors",
"tests/test_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators",
"tests/test_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_frame_is_not_class",
"tests/test_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_assignment_names_are_considered",
"tests/test_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_callfunc_are_considered",
"tests/test_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_same_name_considered",
"tests/test_scoped_nodes.py::ClassNodeTest::test_class_getattr",
"tests/test_scoped_nodes.py::ClassNodeTest::test_class_keywords",
"tests/test_scoped_nodes.py::ClassNodeTest::test_classmethod_attributes",
"tests/test_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_1",
"tests/test_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_2",
"tests/test_scoped_nodes.py::ClassNodeTest::test_dict_interface",
"tests/test_scoped_nodes.py::ClassNodeTest::test_duplicate_bases_namedtuple",
"tests/test_scoped_nodes.py::ClassNodeTest::test_extra_decorators_only_class_level_assignments",
"tests/test_scoped_nodes.py::ClassNodeTest::test_function_with_decorator_lineno",
"tests/test_scoped_nodes.py::ClassNodeTest::test_generator_from_infer_call_result_parent",
"tests/test_scoped_nodes.py::ClassNodeTest::test_getattr_from_grandpa",
"tests/test_scoped_nodes.py::ClassNodeTest::test_getattr_method_transform",
"tests/test_scoped_nodes.py::ClassNodeTest::test_getattr_with_enpty_annassign",
"tests/test_scoped_nodes.py::ClassNodeTest::test_has_dynamic_getattr",
"tests/test_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass",
"tests/test_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass_lookup",
"tests/test_scoped_nodes.py::ClassNodeTest::test_inner_classes",
"tests/test_scoped_nodes.py::ClassNodeTest::test_instance_attr_ancestors",
"tests/test_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas",
"tests/test_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas_2",
"tests/test_scoped_nodes.py::ClassNodeTest::test_instance_getattr",
"tests/test_scoped_nodes.py::ClassNodeTest::test_instance_getattr_with_class_attr",
"tests/test_scoped_nodes.py::ClassNodeTest::test_instance_special_attributes",
"tests/test_scoped_nodes.py::ClassNodeTest::test_kite_graph",
"tests/test_scoped_nodes.py::ClassNodeTest::test_local_attr_ancestors",
"tests/test_scoped_nodes.py::ClassNodeTest::test_local_attr_invalid_mro",
"tests/test_scoped_nodes.py::ClassNodeTest::test_local_attr_mro",
"tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_error",
"tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup",
"tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_inference_errors",
"tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_using_same_class",
"tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_type",
"tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_yes_leak",
"tests/test_scoped_nodes.py::ClassNodeTest::test_methods",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_1",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_2",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_3",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_4",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_5",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_6",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_7",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_1",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_2",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_typing_extensions",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_with_attribute_classes",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_with_factories",
"tests/test_scoped_nodes.py::ClassNodeTest::test_multiline_docstring",
"tests/test_scoped_nodes.py::ClassNodeTest::test_navigation",
"tests/test_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop",
"tests/test_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop_with_redefine",
"tests/test_scoped_nodes.py::ClassNodeTest::test_nonregr_infer_callresult",
"tests/test_scoped_nodes.py::ClassNodeTest::test_singleline_docstring",
"tests/test_scoped_nodes.py::ClassNodeTest::test_slots",
"tests/test_scoped_nodes.py::ClassNodeTest::test_slots_added_dynamically_still_inferred",
"tests/test_scoped_nodes.py::ClassNodeTest::test_slots_empty_list_of_slots",
"tests/test_scoped_nodes.py::ClassNodeTest::test_slots_for_dict_keys",
"tests/test_scoped_nodes.py::ClassNodeTest::test_slots_taken_from_parents",
"tests/test_scoped_nodes.py::ClassNodeTest::test_type",
"tests/test_scoped_nodes.py::ClassNodeTest::test_type_three_arguments",
"tests/test_scoped_nodes.py::ClassNodeTest::test_with_invalid_metaclass",
"tests/test_scoped_nodes.py::ClassNodeTest::test_without_docstring",
"tests/test_scoped_nodes.py::test_issue940_metaclass_subclass_property",
"tests/test_scoped_nodes.py::test_issue940_property_grandchild",
"tests/test_scoped_nodes.py::test_issue940_metaclass_property",
"tests/test_scoped_nodes.py::test_issue940_with_metaclass_class_context_property",
"tests/test_scoped_nodes.py::test_issue940_metaclass_values_funcdef",
"tests/test_scoped_nodes.py::test_issue940_metaclass_derived_funcdef",
"tests/test_scoped_nodes.py::test_issue940_metaclass_funcdef_is_not_datadescriptor",
"tests/test_scoped_nodes.py::test_property_in_body_of_try",
"tests/test_scoped_nodes.py::test_property_in_body_of_if",
"tests/test_scoped_nodes.py::test_issue940_enums_as_a_real_world_usecase",
"tests/test_scoped_nodes.py::test_enums_type_annotation_str_member",
"tests/test_scoped_nodes.py::test_enums_type_annotation_no_value[bool]",
"tests/test_scoped_nodes.py::test_enums_type_annotation_no_value[dict]",
"tests/test_scoped_nodes.py::test_enums_type_annotation_no_value[int]",
"tests/test_scoped_nodes.py::test_enums_type_annotation_no_value[str]",
"tests/test_scoped_nodes.py::test_enums_value2member_map_",
"tests/test_scoped_nodes.py::test_enums_type_annotation_non_str_member[int-42]",
"tests/test_scoped_nodes.py::test_enums_type_annotation_non_str_member[bytes-]",
"tests/test_scoped_nodes.py::test_enums_type_annotations_non_const_member[dict-value0]",
"tests/test_scoped_nodes.py::test_enums_type_annotations_non_const_member[list-value1]",
"tests/test_scoped_nodes.py::test_enums_type_annotations_non_const_member[TypedDict-value2]",
"tests/test_scoped_nodes.py::test_metaclass_cannot_infer_call_yields_an_instance",
"tests/test_scoped_nodes.py::test_posonlyargs_python_38[\\ndef",
"tests/test_scoped_nodes.py::test_posonlyargs_default_value",
"tests/test_scoped_nodes.py::test_ancestor_with_generic",
"tests/test_scoped_nodes.py::test_slots_duplicate_bases_issue_1089",
"tests/test_scoped_nodes.py::TestFrameNodes::test_frame_node",
"tests/test_scoped_nodes.py::TestFrameNodes::test_non_frame_node"
] |
[
"pytest -rA --cov"
] |
pytest
|
{
"files": 2,
"hunks": 3,
"lines": 17
}
|
||
Timing the pylint evaluation of checkers/ folder from pylint repo, I don't see a big difference with and without (explicit raise KeyError inserted) the cache:
with:
```
real 0m57.994s
real 0m58.089s
real 0m57.446s
real 0m57.366s
```
without:
```
real 0m58.913s
real 0m58.693s
real 0m59.070s
real 0m58.799s
```
Would you want to create a PR to remove it?
Yes, will do.
|
06fafc4d023460c682494672b617d456037baf67
|
[
"https://github.com/pylint-dev/astroid/commit/d1b73d13d9fb75005bf3c2eb176aff9818f7762b",
"https://github.com/pylint-dev/astroid/commit/171c48bb80b66b0a6da3eb33d38a1ea8d612de52",
"https://github.com/pylint-dev/astroid/commit/07719871e7ff8b113589cc26c464a862e20bb816",
"https://github.com/pylint-dev/astroid/commit/370b630ec33fe5906cec6b38b271a4b06c5b9685",
"https://github.com/pylint-dev/astroid/commit/38955bf992cd0dda6b95b8d48f282a3f0b4a42bb",
"https://github.com/pylint-dev/astroid/commit/b923101f927bab865cddcdd51c9bb70cc9ce01cb",
"https://github.com/pylint-dev/astroid/commit/04b07357371b7e8aa1de6d32064e1f411b314114",
"https://github.com/pylint-dev/astroid/commit/d8a810fd85bb046c374637706f6e6e89f26c65b2",
"https://github.com/pylint-dev/astroid/commit/cb5b291500f34743119fd4369ee458a2ac5aa7ce",
"https://github.com/pylint-dev/astroid/commit/e054f407304aa3ad59b238c39583d3e960f075f7",
"https://github.com/pylint-dev/astroid/commit/e7354389e1d2cc5ccb7822a5b59314e2bd71d23b",
"https://github.com/pylint-dev/astroid/commit/0fa02331f73c080848c28291e338f60d94bf19fb",
"https://github.com/pylint-dev/astroid/commit/30f249d0077e6963584785c08cfff341ad947dd5",
"https://github.com/pylint-dev/astroid/commit/a79a2a74af4428bd5d4841b15f074b522ce4b969"
] | 2023-04-30T13:52:13
|
Timing the pylint evaluation of checkers/ folder from pylint repo, I don't see a big difference with and without (explicit raise KeyError inserted) the cache:
with:
```
real 0m57.994s
real 0m58.089s
real 0m57.446s
real 0m57.366s
```
without:
```
real 0m58.913s
real 0m58.693s
real 0m59.070s
real 0m58.799s
```
Would you want to create a PR to remove it?
Yes, will do.
|
pylint-dev__astroid-2158
|
[
"1828"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index a760172d10..faccda681d 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -17,6 +17,13 @@ Release date: TBA
* Reduce file system access in ``ast_from_file()``.
+* Fix incorrect cache keys for inference results, thereby correctly inferring types
+ for calls instantiating types dynamically.
+
+ Closes #1828
+ Closes pylint-dev/pylint#7464
+ Closes pylint-dev/pylint#8074
+
* ``nodes.FunctionDef`` no longer inherits from ``nodes.Lambda``.
This is a breaking change but considered a bug fix as the nodes did not share the same
API and were not interchangeable.
diff --git a/astroid/inference_tip.py b/astroid/inference_tip.py
index 5b855c9e77..92cb6b4fe1 100644
--- a/astroid/inference_tip.py
+++ b/astroid/inference_tip.py
@@ -9,6 +9,7 @@
import sys
from collections.abc import Callable, Iterator
+from astroid.context import InferenceContext
from astroid.exceptions import InferenceOverwriteError, UseInferenceDefault
from astroid.nodes import NodeNG
from astroid.typing import InferenceResult, InferFn
@@ -20,7 +21,11 @@
_P = ParamSpec("_P")
-_cache: dict[tuple[InferFn, NodeNG], list[InferenceResult] | None] = {}
+_cache: dict[
+ tuple[InferFn, NodeNG, InferenceContext | None], list[InferenceResult]
+] = {}
+
+_CURRENTLY_INFERRING: set[tuple[InferFn, NodeNG]] = set()
def clear_inference_tip_cache() -> None:
@@ -35,16 +40,25 @@ def _inference_tip_cached(
def inner(*args: _P.args, **kwargs: _P.kwargs) -> Iterator[InferenceResult]:
node = args[0]
- try:
- result = _cache[func, node]
+ context = args[1]
+ partial_cache_key = (func, node)
+ if partial_cache_key in _CURRENTLY_INFERRING:
# If through recursion we end up trying to infer the same
# func + node we raise here.
- if result is None:
- raise UseInferenceDefault()
+ raise UseInferenceDefault
+ try:
+ return _cache[func, node, context]
except KeyError:
- _cache[func, node] = None
- result = _cache[func, node] = list(func(*args, **kwargs))
- assert result
+ # Recursion guard with a partial cache key.
+ # Using the full key causes a recursion error on PyPy.
+ # It's a pragmatic compromise to avoid so much recursive inference
+ # with slightly different contexts while still passing the simple
+ # test cases included with this commit.
+ _CURRENTLY_INFERRING.add(partial_cache_key)
+ result = _cache[func, node, context] = list(func(*args, **kwargs))
+ # Remove recursion guard.
+ _CURRENTLY_INFERRING.remove(partial_cache_key)
+
return iter(result)
return inner
|
Wrong type inferred - inference type cache is missing context
Moving discussion started in https://github.com/PyCQA/pylint/issues/7464 to astroid repo.
### Steps to reproduce
```
import astroid
result1, result2 = astroid.extract_node("""
class Base:
def return_type(self):
return type(self)()
class A(Base):
def method(self):
return self.return_type()
class B(Base):
def method(self):
return self.return_type()
A().method() #@
B().method() #@
""")
print(next(result1.infer()))
print(next(result2.infer()))
```
### Current behavior
Instance of .A
Instance of .A
### Expected behavior
Instance of .A
Instance of .B
### Workaround
Modify inference_tip.py to disable cache in _inference_tip_cached function.
### `python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"` output
2.13.0-dev0
|
2158
|
pylint-dev/astroid
|
diff --git a/tests/brain/test_brain.py b/tests/brain/test_brain.py
index 00a023ddb0..4a016868cb 100644
--- a/tests/brain/test_brain.py
+++ b/tests/brain/test_brain.py
@@ -930,13 +930,7 @@ class A:
assert inferred.value == 42
def test_typing_cast_multiple_inference_calls(self) -> None:
- """Inference of an outer function should not store the result for cast.
-
- https://github.com/pylint-dev/pylint/issues/8074
-
- Possible solution caused RecursionErrors with Python 3.8 and CPython + PyPy.
- https://github.com/pylint-dev/astroid/pull/1982
- """
+ """Inference of an outer function should not store the result for cast."""
ast_nodes = builder.extract_node(
"""
from typing import TypeVar, cast
@@ -954,7 +948,7 @@ def ident(var: T) -> T:
i1 = next(ast_nodes[1].infer())
assert isinstance(i1, nodes.Const)
- assert i1.value == 2 # should be "Hello"!
+ assert i1.value == "Hello"
class ReBrainTest(unittest.TestCase):
diff --git a/tests/test_regrtest.py b/tests/test_regrtest.py
index 31d9e6b84b..59d344b954 100644
--- a/tests/test_regrtest.py
+++ b/tests/test_regrtest.py
@@ -336,6 +336,27 @@ def d(self):
assert isinstance(inferred, Instance)
assert inferred.qname() == ".A"
+ def test_inference_context_consideration(self) -> None:
+ """https://github.com/PyCQA/astroid/issues/1828"""
+ code = """
+ class Base:
+ def return_type(self):
+ return type(self)()
+ class A(Base):
+ def method(self):
+ return self.return_type()
+ class B(Base):
+ def method(self):
+ return self.return_type()
+ A().method() #@
+ B().method() #@
+ """
+ node1, node2 = extract_node(code)
+ inferred1 = next(node1.infer())
+ assert inferred1.qname() == ".A"
+ inferred2 = next(node2.infer())
+ assert inferred2.qname() == ".B"
+
class Whatever:
a = property(lambda x: x, lambda x: x) # type: ignore[misc]
diff --git a/tests/test_scoped_nodes.py b/tests/test_scoped_nodes.py
index b8c55f67d3..86d69624d1 100644
--- a/tests/test_scoped_nodes.py
+++ b/tests/test_scoped_nodes.py
@@ -1771,9 +1771,7 @@ def __init__(self):
"FinalClass",
"ClassB",
"MixinB",
- # We don't recognize what 'cls' is at time of .format() call, only
- # what it is at the end.
- # "strMixin",
+ "strMixin",
"ClassA",
"MixinA",
"intMixin",
|
none
|
[
"tests/brain/test_brain.py::TypingBrain::test_typing_cast_multiple_inference_calls",
"tests/test_regrtest.py::NonRegressionTests::test_inference_context_consideration",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_with_factories"
] |
[
"tests/brain/test_brain.py::CollectionsDequeTests::test_deque",
"tests/brain/test_brain.py::CollectionsDequeTests::test_deque_py35methods",
"tests/brain/test_brain.py::CollectionsDequeTests::test_deque_py39methods",
"tests/brain/test_brain.py::OrderedDictTest::test_ordered_dict_py34method",
"tests/brain/test_brain.py::DefaultDictTest::test_1",
"tests/brain/test_brain.py::ModuleExtenderTest::test_extension_modules",
"tests/brain/test_brain.py::TypeBrain::test_builtin_subscriptable",
"tests/brain/test_brain.py::TypeBrain::test_invalid_type_subscript",
"tests/brain/test_brain.py::TypeBrain::test_type_subscript",
"tests/brain/test_brain.py::CollectionsBrain::test_collections_object_not_subscriptable",
"tests/brain/test_brain.py::CollectionsBrain::test_collections_object_subscriptable",
"tests/brain/test_brain.py::CollectionsBrain::test_collections_object_subscriptable_2",
"tests/brain/test_brain.py::CollectionsBrain::test_collections_object_subscriptable_3",
"tests/brain/test_brain.py::CollectionsBrain::test_collections_object_subscriptable_4",
"tests/brain/test_brain.py::TypingBrain::test_callable_type",
"tests/brain/test_brain.py::TypingBrain::test_collections_generic_alias_slots",
"tests/brain/test_brain.py::TypingBrain::test_has_dunder_args",
"tests/brain/test_brain.py::TypingBrain::test_namedtuple_base",
"tests/brain/test_brain.py::TypingBrain::test_namedtuple_bug_pylint_4383",
"tests/brain/test_brain.py::TypingBrain::test_namedtuple_can_correctly_access_methods",
"tests/brain/test_brain.py::TypingBrain::test_namedtuple_class_form",
"tests/brain/test_brain.py::TypingBrain::test_namedtuple_few_args",
"tests/brain/test_brain.py::TypingBrain::test_namedtuple_few_fields",
"tests/brain/test_brain.py::TypingBrain::test_namedtuple_inference",
"tests/brain/test_brain.py::TypingBrain::test_namedtuple_inference_nonliteral",
"tests/brain/test_brain.py::TypingBrain::test_namedtuple_inferred_as_class",
"tests/brain/test_brain.py::TypingBrain::test_namedtuple_instance_attrs",
"tests/brain/test_brain.py::TypingBrain::test_namedtuple_nested_class",
"tests/brain/test_brain.py::TypingBrain::test_namedtuple_simple",
"tests/brain/test_brain.py::TypingBrain::test_namedtuple_uninferable_member",
"tests/brain/test_brain.py::TypingBrain::test_tuple_type",
"tests/brain/test_brain.py::TypingBrain::test_typed_dict",
"tests/brain/test_brain.py::TypingBrain::test_typing_alias_type",
"tests/brain/test_brain.py::TypingBrain::test_typing_alias_type_2",
"tests/brain/test_brain.py::TypingBrain::test_typing_annotated_subscriptable",
"tests/brain/test_brain.py::TypingBrain::test_typing_cast",
"tests/brain/test_brain.py::TypingBrain::test_typing_cast_attribute",
"tests/brain/test_brain.py::TypingBrain::test_typing_generic_slots",
"tests/brain/test_brain.py::TypingBrain::test_typing_generic_subscriptable",
"tests/brain/test_brain.py::TypingBrain::test_typing_namedtuple_dont_crash_on_no_fields",
"tests/brain/test_brain.py::TypingBrain::test_typing_object_builtin_subscriptable",
"tests/brain/test_brain.py::TypingBrain::test_typing_object_not_subscriptable",
"tests/brain/test_brain.py::TypingBrain::test_typing_object_notsubscriptable_3",
"tests/brain/test_brain.py::TypingBrain::test_typing_object_subscriptable",
"tests/brain/test_brain.py::TypingBrain::test_typing_object_subscriptable_2",
"tests/brain/test_brain.py::TypingBrain::test_typing_type_subscriptable",
"tests/brain/test_brain.py::TypingBrain::test_typing_type_without_tip",
"tests/brain/test_brain.py::TypingBrain::test_typing_types",
"tests/brain/test_brain.py::ReBrainTest::test_re_pattern_subscriptable",
"tests/brain/test_brain.py::ReBrainTest::test_regex_flags",
"tests/brain/test_brain.py::BrainFStrings::test_no_crash_on_const_reconstruction",
"tests/brain/test_brain.py::BrainNamedtupleAnnAssignTest::test_no_crash_on_ann_assign_in_namedtuple",
"tests/brain/test_brain.py::BrainUUIDTest::test_uuid_has_int_member",
"tests/brain/test_brain.py::RandomSampleTest::test_arguments_inferred_successfully",
"tests/brain/test_brain.py::RandomSampleTest::test_inferred_successfully",
"tests/brain/test_brain.py::RandomSampleTest::test_no_crash_on_evaluatedobject",
"tests/brain/test_brain.py::SubprocessTest::test_popen_does_not_have_class_getitem",
"tests/brain/test_brain.py::SubprocessTest::test_subprcess_check_output",
"tests/brain/test_brain.py::SubprocessTest::test_subprocess_args",
"tests/brain/test_brain.py::TestIsinstanceInference::test_type_type",
"tests/brain/test_brain.py::TestIsinstanceInference::test_object_type",
"tests/brain/test_brain.py::TestIsinstanceInference::test_type_object",
"tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_int_true",
"tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_int_false",
"tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_object_true",
"tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_object_true3",
"tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_class_false",
"tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_type_false",
"tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_str_true",
"tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_str_false",
"tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_tuple_argument",
"tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_type_false2",
"tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_object_true2",
"tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_type_true",
"tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_edge_case",
"tests/brain/test_brain.py::TestIsinstanceInference::test_uninferable_bad_type",
"tests/brain/test_brain.py::TestIsinstanceInference::test_uninferable_keywords",
"tests/brain/test_brain.py::TestIsinstanceInference::test_too_many_args",
"tests/brain/test_brain.py::TestIsinstanceInference::test_first_param_is_uninferable",
"tests/brain/test_brain.py::TestIssubclassBrain::test_type_type",
"tests/brain/test_brain.py::TestIssubclassBrain::test_object_type",
"tests/brain/test_brain.py::TestIssubclassBrain::test_type_object",
"tests/brain/test_brain.py::TestIssubclassBrain::test_issubclass_same_class",
"tests/brain/test_brain.py::TestIssubclassBrain::test_issubclass_not_the_same_class",
"tests/brain/test_brain.py::TestIssubclassBrain::test_issubclass_object_true",
"tests/brain/test_brain.py::TestIssubclassBrain::test_issubclass_same_user_defined_class",
"tests/brain/test_brain.py::TestIssubclassBrain::test_issubclass_different_user_defined_classes",
"tests/brain/test_brain.py::TestIssubclassBrain::test_issubclass_type_false",
"tests/brain/test_brain.py::TestIssubclassBrain::test_isinstance_tuple_argument",
"tests/brain/test_brain.py::TestIssubclassBrain::test_isinstance_object_true2",
"tests/brain/test_brain.py::TestIssubclassBrain::test_issubclass_short_circuit",
"tests/brain/test_brain.py::TestIssubclassBrain::test_uninferable_bad_type",
"tests/brain/test_brain.py::TestIssubclassBrain::test_uninferable_keywords",
"tests/brain/test_brain.py::TestIssubclassBrain::test_too_many_args",
"tests/brain/test_brain.py::TestLenBuiltinInference::test_len_list",
"tests/brain/test_brain.py::TestLenBuiltinInference::test_len_tuple",
"tests/brain/test_brain.py::TestLenBuiltinInference::test_len_var",
"tests/brain/test_brain.py::TestLenBuiltinInference::test_len_dict",
"tests/brain/test_brain.py::TestLenBuiltinInference::test_len_set",
"tests/brain/test_brain.py::TestLenBuiltinInference::test_len_object",
"tests/brain/test_brain.py::TestLenBuiltinInference::test_len_class_with_metaclass",
"tests/brain/test_brain.py::TestLenBuiltinInference::test_len_object_failure",
"tests/brain/test_brain.py::TestLenBuiltinInference::test_len_string",
"tests/brain/test_brain.py::TestLenBuiltinInference::test_len_generator_failure",
"tests/brain/test_brain.py::TestLenBuiltinInference::test_len_failure_missing_variable",
"tests/brain/test_brain.py::TestLenBuiltinInference::test_len_bytes",
"tests/brain/test_brain.py::TestLenBuiltinInference::test_int_subclass_result",
"tests/brain/test_brain.py::TestLenBuiltinInference::test_len_builtin_inference_attribute_error_str",
"tests/brain/test_brain.py::TestLenBuiltinInference::test_len_builtin_inference_recursion_error_self_referential_attribute",
"tests/brain/test_brain.py::test_infer_str",
"tests/brain/test_brain.py::test_infer_int",
"tests/brain/test_brain.py::test_infer_dict_from_keys",
"tests/brain/test_brain.py::TestFunctoolsPartial::test_infer_partial",
"tests/brain/test_brain.py::TestFunctoolsPartial::test_invalid_functools_partial_calls",
"tests/brain/test_brain.py::TestFunctoolsPartial::test_inferred_partial_function_calls",
"tests/brain/test_brain.py::TestFunctoolsPartial::test_partial_assignment",
"tests/brain/test_brain.py::TestFunctoolsPartial::test_partial_does_not_affect_scope",
"tests/brain/test_brain.py::TestFunctoolsPartial::test_multiple_partial_args",
"tests/brain/test_brain.py::test_http_client_brain",
"tests/brain/test_brain.py::test_http_status_brain",
"tests/brain/test_brain.py::test_http_status_brain_iterable",
"tests/brain/test_brain.py::test_oserror_model",
"tests/brain/test_brain.py::test_crypt_brain",
"tests/brain/test_brain.py::test_str_and_bytes['hey'.encode()-Const-]",
"tests/brain/test_brain.py::test_str_and_bytes[b'hey'.decode()-Const-]",
"tests/brain/test_brain.py::test_str_and_bytes['hey'.encode().decode()-Const-]",
"tests/brain/test_brain.py::test_no_recursionerror_on_self_referential_length_check",
"tests/brain/test_brain.py::test_inference_on_outer_referential_length_check",
"tests/brain/test_brain.py::test_no_attributeerror_on_self_referential_length_check",
"tests/test_regrtest.py::NonRegressionTests::test_ancestors_missing_from_function",
"tests/test_regrtest.py::NonRegressionTests::test_ancestors_patching_class_recursion",
"tests/test_regrtest.py::NonRegressionTests::test_ancestors_yes_in_bases",
"tests/test_regrtest.py::NonRegressionTests::test_binop_generates_nodes_with_parents",
"tests/test_regrtest.py::NonRegressionTests::test_decorator_callchain_issue42",
"tests/test_regrtest.py::NonRegressionTests::test_decorator_names_inference_error_leaking",
"tests/test_regrtest.py::NonRegressionTests::test_filter_stmts_nested_if",
"tests/test_regrtest.py::NonRegressionTests::test_filter_stmts_scoping",
"tests/test_regrtest.py::NonRegressionTests::test_living_property",
"tests/test_regrtest.py::NonRegressionTests::test_module_path",
"tests/test_regrtest.py::NonRegressionTests::test_nameconstant",
"tests/test_regrtest.py::NonRegressionTests::test_package_sidepackage",
"tests/test_regrtest.py::NonRegressionTests::test_recursion_regression_issue25",
"tests/test_regrtest.py::NonRegressionTests::test_recursive_property_method",
"tests/test_regrtest.py::NonRegressionTests::test_regression_inference_of_self_in_lambda",
"tests/test_regrtest.py::NonRegressionTests::test_unicode_in_docstring",
"tests/test_regrtest.py::NonRegressionTests::test_uninferable_string_argument_of_namedtuple",
"tests/test_regrtest.py::test_ancestor_looking_up_redefined_function",
"tests/test_regrtest.py::test_crash_in_dunder_inference_prevented",
"tests/test_regrtest.py::test_regression_crash_classmethod",
"tests/test_regrtest.py::test_max_inferred_for_complicated_class_hierarchy",
"tests/test_regrtest.py::test_recursion_during_inference",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_comment_before_docstring",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_dict_interface",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_file_stream_api",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_file_stream_in_memory",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_file_stream_physical",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_getattr",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_import_1",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_import_2",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_module_getattr",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_multiline_docstring",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_public_names",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name_beyond_top_level",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_singleline_docstring",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_special_attributes",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_stream_api",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_wildcard_import_names",
"tests/test_scoped_nodes.py::ModuleNodeTest::test_without_docstring",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_abstract_methods_are_not_implicitly_none",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_argnames",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_decorator_builtin_descriptors",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_default_value",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_dict_interface",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_display_type",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_docstring_special_cases",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_classmethod",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_function",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_method",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_format_args",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_format_args_keyword_only_args",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_four_args",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_func_instance_attr",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_func_is_bound",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_igetattr",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_inference_error",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_is_abstract",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_is_abstract_decorated",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_is_generator",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_is_method",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_lambda_getattr",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_lambda_pytype",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_lambda_qname",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_method_init_subclass",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_multiline_docstring",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_multiline_docstring_async",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_navigation",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_no_returns_is_implicitly_none",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_only_raises_is_not_implicitly_none",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_positional_only_argnames",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_return_annotation_is_not_the_last",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_return_nothing",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_singleline_docstring",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_special_attributes",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_type_builtin_descriptor_subclasses",
"tests/test_scoped_nodes.py::FunctionNodeTest::test_without_docstring",
"tests/test_scoped_nodes.py::ClassNodeTest::test__bases__attribute",
"tests/test_scoped_nodes.py::ClassNodeTest::test__mro__attribute",
"tests/test_scoped_nodes.py::ClassNodeTest::test_add_metaclass",
"tests/test_scoped_nodes.py::ClassNodeTest::test_all_ancestors_need_slots",
"tests/test_scoped_nodes.py::ClassNodeTest::test_ancestors",
"tests/test_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators",
"tests/test_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_frame_is_not_class",
"tests/test_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_assignment_names_are_considered",
"tests/test_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_callfunc_are_considered",
"tests/test_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_same_name_considered",
"tests/test_scoped_nodes.py::ClassNodeTest::test_class_getattr",
"tests/test_scoped_nodes.py::ClassNodeTest::test_class_keywords",
"tests/test_scoped_nodes.py::ClassNodeTest::test_classmethod_attributes",
"tests/test_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_1",
"tests/test_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_2",
"tests/test_scoped_nodes.py::ClassNodeTest::test_dict_interface",
"tests/test_scoped_nodes.py::ClassNodeTest::test_duplicate_bases_namedtuple",
"tests/test_scoped_nodes.py::ClassNodeTest::test_extra_decorators_only_class_level_assignments",
"tests/test_scoped_nodes.py::ClassNodeTest::test_function_with_decorator_lineno",
"tests/test_scoped_nodes.py::ClassNodeTest::test_generator_from_infer_call_result_parent",
"tests/test_scoped_nodes.py::ClassNodeTest::test_getattr_from_grandpa",
"tests/test_scoped_nodes.py::ClassNodeTest::test_getattr_method_transform",
"tests/test_scoped_nodes.py::ClassNodeTest::test_getattr_with_enpty_annassign",
"tests/test_scoped_nodes.py::ClassNodeTest::test_has_dynamic_getattr",
"tests/test_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass",
"tests/test_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass_lookup",
"tests/test_scoped_nodes.py::ClassNodeTest::test_inner_classes",
"tests/test_scoped_nodes.py::ClassNodeTest::test_instance_attr_ancestors",
"tests/test_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas",
"tests/test_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas_2",
"tests/test_scoped_nodes.py::ClassNodeTest::test_instance_getattr",
"tests/test_scoped_nodes.py::ClassNodeTest::test_instance_getattr_with_class_attr",
"tests/test_scoped_nodes.py::ClassNodeTest::test_instance_special_attributes",
"tests/test_scoped_nodes.py::ClassNodeTest::test_kite_graph",
"tests/test_scoped_nodes.py::ClassNodeTest::test_local_attr_ancestors",
"tests/test_scoped_nodes.py::ClassNodeTest::test_local_attr_invalid_mro",
"tests/test_scoped_nodes.py::ClassNodeTest::test_local_attr_mro",
"tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_error",
"tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup",
"tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_inference_errors",
"tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_using_same_class",
"tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_type",
"tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_yes_leak",
"tests/test_scoped_nodes.py::ClassNodeTest::test_methods",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_1",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_2",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_3",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_4",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_5",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_6",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_7",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_1",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_2",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_typing_extensions",
"tests/test_scoped_nodes.py::ClassNodeTest::test_mro_with_attribute_classes",
"tests/test_scoped_nodes.py::ClassNodeTest::test_multiline_docstring",
"tests/test_scoped_nodes.py::ClassNodeTest::test_navigation",
"tests/test_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop",
"tests/test_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop_with_redefine",
"tests/test_scoped_nodes.py::ClassNodeTest::test_nonregr_infer_callresult",
"tests/test_scoped_nodes.py::ClassNodeTest::test_singleline_docstring",
"tests/test_scoped_nodes.py::ClassNodeTest::test_slots",
"tests/test_scoped_nodes.py::ClassNodeTest::test_slots_added_dynamically_still_inferred",
"tests/test_scoped_nodes.py::ClassNodeTest::test_slots_empty_list_of_slots",
"tests/test_scoped_nodes.py::ClassNodeTest::test_slots_for_dict_keys",
"tests/test_scoped_nodes.py::ClassNodeTest::test_slots_taken_from_parents",
"tests/test_scoped_nodes.py::ClassNodeTest::test_type",
"tests/test_scoped_nodes.py::ClassNodeTest::test_type_three_arguments",
"tests/test_scoped_nodes.py::ClassNodeTest::test_with_invalid_metaclass",
"tests/test_scoped_nodes.py::ClassNodeTest::test_without_docstring",
"tests/test_scoped_nodes.py::test_issue940_metaclass_subclass_property",
"tests/test_scoped_nodes.py::test_issue940_property_grandchild",
"tests/test_scoped_nodes.py::test_issue940_metaclass_property",
"tests/test_scoped_nodes.py::test_issue940_with_metaclass_class_context_property",
"tests/test_scoped_nodes.py::test_issue940_metaclass_values_funcdef",
"tests/test_scoped_nodes.py::test_issue940_metaclass_derived_funcdef",
"tests/test_scoped_nodes.py::test_issue940_metaclass_funcdef_is_not_datadescriptor",
"tests/test_scoped_nodes.py::test_property_in_body_of_try",
"tests/test_scoped_nodes.py::test_property_in_body_of_if",
"tests/test_scoped_nodes.py::test_issue940_enums_as_a_real_world_usecase",
"tests/test_scoped_nodes.py::test_enums_type_annotation_str_member",
"tests/test_scoped_nodes.py::test_enums_type_annotation_no_value[bool]",
"tests/test_scoped_nodes.py::test_enums_type_annotation_no_value[dict]",
"tests/test_scoped_nodes.py::test_enums_type_annotation_no_value[int]",
"tests/test_scoped_nodes.py::test_enums_type_annotation_no_value[str]",
"tests/test_scoped_nodes.py::test_enums_value2member_map_",
"tests/test_scoped_nodes.py::test_enums_type_annotation_non_str_member[int-42]",
"tests/test_scoped_nodes.py::test_enums_type_annotation_non_str_member[bytes-]",
"tests/test_scoped_nodes.py::test_enums_type_annotations_non_const_member[dict-value0]",
"tests/test_scoped_nodes.py::test_enums_type_annotations_non_const_member[list-value1]",
"tests/test_scoped_nodes.py::test_enums_type_annotations_non_const_member[TypedDict-value2]",
"tests/test_scoped_nodes.py::test_metaclass_cannot_infer_call_yields_an_instance",
"tests/test_scoped_nodes.py::test_posonlyargs_python_38[\\ndef",
"tests/test_scoped_nodes.py::test_posonlyargs_default_value",
"tests/test_scoped_nodes.py::test_ancestor_with_generic",
"tests/test_scoped_nodes.py::test_slots_duplicate_bases_issue_1089",
"tests/test_scoped_nodes.py::TestFrameNodes::test_frame_node",
"tests/test_scoped_nodes.py::TestFrameNodes::test_non_frame_node",
"tests/brain/test_brain.py::TestLenBuiltinInference::test_int_subclass_argument"
] |
[
"pytest -rA"
] |
pytest
|
{
"files": 2,
"hunks": 4,
"lines": 37
}
|
It appears that this is caused by `InferenceContext` maintaining a strong reference to the mutable set that is shared between clones, see this simplified example:
```python
class Context:
def __init__(self, path=None):
self.path = path or set()
def clone(self):
return Context(path=self.path)
a = Context()
a.path.add('hello')
b = a.clone()
b.path.add('world')
print(a.path, b.path)
# (set(['world', 'hello']), set(['world', 'hello']))
print(a.path is b.path)
# True
```
|
cd8b6a43192724128af68605ef22aabf3254f495
|
[
"https://github.com/pylint-dev/astroid/commit/ed77a1ba3d762497005f2c5f3d6a4839135ce341",
"https://github.com/pylint-dev/astroid/commit/c4bf1579a4bcd97dd03c52093462b6b657515b3c",
"https://github.com/pylint-dev/astroid/commit/f581d935509be60f1b4ef3c3b3dcbfa60c2946e9",
"https://github.com/pylint-dev/astroid/commit/2bc5fcf2d3723e515498f81ec73da04fb1e8eb23",
"https://github.com/pylint-dev/astroid/commit/0e5cd49838b893c74105d0853e5019db8ec3340e",
"https://github.com/pylint-dev/astroid/commit/165e8d97fd2ba12271d3254848f8a928d980e7af"
] | 2021-03-29T12:55:48
|
pylint-dev__astroid-927
|
[
"926"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index 12fae5ceab..05d9256b7e 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -14,6 +14,11 @@ Release Date: TBA
Closes PyCQA/pylint#3970
Closes PyCQA/pylint#3595
+* Fix some spurious cycles detected in ``context.path`` leading to more cases
+ that can now be inferred
+
+ Closes #926
+
What's New in astroid 2.5.6?
============================
diff --git a/astroid/context.py b/astroid/context.py
index 18220ec228..d7bf81bf17 100644
--- a/astroid/context.py
+++ b/astroid/context.py
@@ -102,7 +102,7 @@ def clone(self):
starts with the same context but diverge as each side is inferred
so the InferenceContext will need be cloned"""
# XXX copy lookupname/callcontext ?
- clone = InferenceContext(self.path, inferred=self.inferred)
+ clone = InferenceContext(self.path.copy(), inferred=self.inferred.copy())
clone.callcontext = self.callcontext
clone.boundnode = self.boundnode
clone.extra_context = self.extra_context
|
infer_stmts cannot infer multiple uses of the same AssignName
Given multiple assignments to the same target which both reference the same AssignName, infer_stmts fails for subsequent attempts after the first.
### Steps to reproduce
This appears to be a minimum working example, removing any part removes the effect:
```python
fails = astroid.extract_node("""
pair = [1, 2]
ex = pair[0]
if 1 + 1 == 2:
ex = pair[1]
ex
""")
print(list(fails.infer()))
# [<Const.int l.2 at 0x...>, Uninferable]
```
For some context, I originally saw this with attributes on an imported module, i.e.
```python
import mod
ex = mod.One()
# later ... or in some branch
ex = mod.Two()
```
### Current behavior
See above.
### Expected behavior
Inlining the variable or switching to a different name works fine:
```python
works = astroid.extract_node("""
# pair = [1, 2]
ex = [1, 2][0]
if 1 + 1 == 2:
ex = [1, 2][1]
ex
""")
print(list(works.infer()))
# [<Const.int l.3 at 0x...>, <Const.int l.5 at 0x...>]
works = astroid.extract_node("""
first = [1, 2]
second = [1, 2]
ex = first[0]
if 1 + 1 == 2:
ex = second[1]
ex
""")
print(list(works.infer()))
# [<Const.int l.2 at 0x...>, <Const.int l.3 at 0x...>]
```
I would expect that the first failing example would work similarly. This (only) worked
in astroid 2.5 and appears to have been "broken" by the revert of cc3bfc5 in 03d15b0 (astroid 2.5.1 and above).
### ``python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"`` output
```
$ python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"
2.5-dev
$ git rev-parse HEAD
03d15b0f32f7d7c9b2cb062b9321e531bd954344
```
|
927
|
pylint-dev/astroid
|
diff --git a/tests/unittest_brain_numpy_core_umath.py b/tests/unittest_brain_numpy_core_umath.py
index 12c1e3bbbc..5559bdd581 100644
--- a/tests/unittest_brain_numpy_core_umath.py
+++ b/tests/unittest_brain_numpy_core_umath.py
@@ -14,7 +14,7 @@
except ImportError:
HAS_NUMPY = False
-from astroid import bases, builder, nodes, util
+from astroid import bases, builder, nodes
@unittest.skipUnless(HAS_NUMPY, "This test requires the numpy library.")
@@ -220,9 +220,7 @@ def test_numpy_core_umath_functions_return_type(self):
with self.subTest(typ=func_):
inferred_values = list(self._inferred_numpy_func_call(func_))
self.assertTrue(
- len(inferred_values) == 1
- or len(inferred_values) == 2
- and inferred_values[-1].pytype() is util.Uninferable,
+ len(inferred_values) == 1,
msg="Too much inferred values ({}) for {:s}".format(
inferred_values[-1].pytype(), func_
),
diff --git a/tests/unittest_inference.py b/tests/unittest_inference.py
index ce15e1efd1..ba1637ceb3 100644
--- a/tests/unittest_inference.py
+++ b/tests/unittest_inference.py
@@ -1704,7 +1704,8 @@ def __init__(self):
"""
ast = extract_node(code, __name__)
expr = ast.func.expr
- self.assertIs(next(expr.infer()), util.Uninferable)
+ with pytest.raises(exceptions.InferenceError):
+ next(expr.infer())
def test_tuple_builtin_inference(self):
code = """
@@ -6032,5 +6033,37 @@ def test_infer_list_of_uninferables_does_not_crash():
assert not inferred.elts
+# https://github.com/PyCQA/astroid/issues/926
+def test_issue926_infer_stmts_referencing_same_name_is_not_uninferable():
+ code = """
+ pair = [1, 2]
+ ex = pair[0]
+ if 1 + 1 == 2:
+ ex = pair[1]
+ ex
+ """
+ node = extract_node(code)
+ inferred = list(node.infer())
+ assert len(inferred) == 2
+ assert isinstance(inferred[0], nodes.Const)
+ assert inferred[0].value == 1
+ assert isinstance(inferred[1], nodes.Const)
+ assert inferred[1].value == 2
+
+
+# https://github.com/PyCQA/astroid/issues/926
+def test_issue926_binop_referencing_same_name_is_not_uninferable():
+ code = """
+ pair = [1, 2]
+ ex = pair[0] + pair[1]
+ ex
+ """
+ node = extract_node(code)
+ inferred = list(node.infer())
+ assert len(inferred) == 1
+ assert isinstance(inferred[0], nodes.Const)
+ assert inferred[0].value == 3
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/unittest_regrtest.py b/tests/unittest_regrtest.py
index 29febfb8f6..acabde135e 100644
--- a/tests/unittest_regrtest.py
+++ b/tests/unittest_regrtest.py
@@ -99,7 +99,7 @@ def test_numpy_crash(self):
astroid = builder.string_build(data, __name__, __file__)
callfunc = astroid.body[1].value.func
inferred = callfunc.inferred()
- self.assertEqual(len(inferred), 2)
+ self.assertEqual(len(inferred), 1)
def test_nameconstant(self):
# used to fail for Python 3.4
|
none
|
[
"tests/unittest_inference.py::InferenceTest::test_stop_iteration_leak",
"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_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_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_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_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_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_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_regrtest.py::NonRegressionTests::test_ancestors_missing_from_function",
"tests/unittest_regrtest.py::NonRegressionTests::test_ancestors_patching_class_recursion",
"tests/unittest_regrtest.py::NonRegressionTests::test_ancestors_yes_in_bases",
"tests/unittest_regrtest.py::NonRegressionTests::test_binop_generates_nodes_with_parents",
"tests/unittest_regrtest.py::NonRegressionTests::test_decorator_callchain_issue42",
"tests/unittest_regrtest.py::NonRegressionTests::test_decorator_names_inference_error_leaking",
"tests/unittest_regrtest.py::NonRegressionTests::test_filter_stmts_scoping",
"tests/unittest_regrtest.py::NonRegressionTests::test_living_property",
"tests/unittest_regrtest.py::NonRegressionTests::test_module_path",
"tests/unittest_regrtest.py::NonRegressionTests::test_nameconstant",
"tests/unittest_regrtest.py::NonRegressionTests::test_package_sidepackage",
"tests/unittest_regrtest.py::NonRegressionTests::test_recursion_regression_issue25",
"tests/unittest_regrtest.py::NonRegressionTests::test_recursive_property_method",
"tests/unittest_regrtest.py::NonRegressionTests::test_regression_inference_of_self_in_lambda",
"tests/unittest_regrtest.py::NonRegressionTests::test_ssl_protocol",
"tests/unittest_regrtest.py::NonRegressionTests::test_unicode_in_docstring",
"tests/unittest_regrtest.py::NonRegressionTests::test_uninferable_string_argument_of_namedtuple",
"tests/unittest_regrtest.py::test_ancestor_looking_up_redefined_function",
"tests/unittest_regrtest.py::test_crash_in_dunder_inference_prevented",
"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"
] |
pytest
|
{
"files": 2,
"hunks": 2,
"lines": 7
}
|
|
@federicobond thanks for this suggestion!
|
d19758108727e1fd11e343d857d060d4f80655d1
|
[
"https://github.com/pylint-dev/astroid/commit/5d706d40ce55157b01636791e18d7a00e3fe5d49"
] | 2021-04-12T04:26:06
|
@federicobond thanks for this suggestion!
|
pylint-dev__astroid-943
|
[
"898"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index 63e9816d51..4343be3fee 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -23,6 +23,11 @@ Release Date: TBA
Closes #926
+* Add ``kind`` field to ``Const`` nodes, matching the structure of the built-in ast Const.
+ The kind field is "u" if the literal is a u-prefixed string, and ``None`` otherwise.
+
+ Closes #898
+
What's New in astroid 2.5.6?
============================
diff --git a/astroid/node_classes.py b/astroid/node_classes.py
index 7faf681275..f8d0b23c52 100644
--- a/astroid/node_classes.py
+++ b/astroid/node_classes.py
@@ -2557,7 +2557,7 @@ class Const(mixins.NoChildrenMixin, NodeNG, bases.Instance):
_other_fields = ("value",)
- def __init__(self, value, lineno=None, col_offset=None, parent=None):
+ def __init__(self, value, lineno=None, col_offset=None, parent=None, kind=None):
"""
:param value: The value that the constant represents.
:type value: object
@@ -2571,12 +2571,12 @@ def __init__(self, value, lineno=None, col_offset=None, parent=None):
:param parent: The parent node in the syntax tree.
:type parent: NodeNG or None
- """
- self.value = value
- """The value that the constant represents.
- :type: object
+ :param kind: The string prefix. "u" for u-prefixed strings and ``None`` otherwise. Python 3.8+ only.
+ :type kind: str or None
"""
+ self.value = value
+ self.kind = kind
super().__init__(lineno, col_offset, parent)
diff --git a/astroid/rebuilder.py b/astroid/rebuilder.py
index bb6a23b852..2532b61d1f 100644
--- a/astroid/rebuilder.py
+++ b/astroid/rebuilder.py
@@ -425,6 +425,7 @@ def visit_const(self, node, parent):
getattr(node, "lineno", None),
getattr(node, "col_offset", None),
parent,
+ getattr(node, "kind", None),
)
def visit_continue(self, node, parent):
@@ -814,6 +815,7 @@ def visit_constant(self, node, parent):
getattr(node, "lineno", None),
getattr(node, "col_offset", None),
parent,
+ getattr(node, "kind", None),
)
# Not used in Python 3.8+.
|
Add kind field to Const
Python 3.8 added the optional `kind` field to `ast.Constant`. This is used to store the string prefix, like `u` for `u"foo"`. `astroid.Const` should include this field too.
|
943
|
pylint-dev/astroid
|
diff --git a/tests/unittest_nodes.py b/tests/unittest_nodes.py
index 4ce73be9b8..14f713a51b 100644
--- a/tests/unittest_nodes.py
+++ b/tests/unittest_nodes.py
@@ -542,6 +542,19 @@ def test_str(self):
def test_unicode(self):
self._test("a")
+ @pytest.mark.skipif(
+ not PY38, reason="kind attribute for ast.Constant was added in 3.8"
+ )
+ def test_str_kind(self):
+ node = builder.extract_node(
+ """
+ const = u"foo"
+ """
+ )
+ assert isinstance(node.value, nodes.Const)
+ assert node.value.value == "foo"
+ assert node.value.kind, "u"
+
def test_copy(self):
"""
Make sure copying a Const object doesn't result in infinite recursion
|
none
|
[
"tests/unittest_nodes.py::ConstNodeTest::test_str_kind"
] |
[
"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::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_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_unicode",
"tests/unittest_nodes.py::NameNodeTest::test_assign_to_True",
"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_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 --pyargs tests"
] |
pytest
|
{
"files": 3,
"hunks": 5,
"lines": 17
}
|
I think the same issue applies to `list`, `set` and `bytearray`. I think we can deal with all these at the same time.
|
a39bbcea62f918668cf12aa269e2a5d145e76df9
|
[
"https://github.com/pylint-dev/astroid/commit/a3cbcaacfa47fc4532bb0e5e9425eb769dbd9882",
"https://github.com/pylint-dev/astroid/commit/a9131b4f9705d9e0ac5ced4ae6742e5eb0659d1c",
"https://github.com/pylint-dev/astroid/commit/9002d778bea0a8216664bb736f78684249bc144e",
"https://github.com/pylint-dev/astroid/commit/53b1f6b3320bbe752f96987be6926a9806c60ef1",
"https://github.com/pylint-dev/astroid/commit/fbbd289ab3e889033c2c21275dc75ac12b6ddfcd",
"https://github.com/pylint-dev/astroid/commit/9c94763426c71516a5fd9e3167b1633bf9587c05",
"https://github.com/pylint-dev/astroid/commit/31911dc5d6cec85ba2703a895d7a5f3c695707cc",
"https://github.com/pylint-dev/astroid/commit/e886697ca9a47c729a5f026b649a6704f3626778",
"https://github.com/pylint-dev/astroid/commit/26c776d6580871659e3ecc6ecbdc2eddfd25729d",
"https://github.com/pylint-dev/astroid/commit/f0dd608181a6f5f0629736b69d44469683362164",
"https://github.com/pylint-dev/astroid/commit/dd48a2be906ea4181834f42ba515408859604329",
"https://github.com/pylint-dev/astroid/commit/3bc8e132c71c72412575a3b79f88880e03ea36f7",
"https://github.com/pylint-dev/astroid/commit/f5e8e2ce037826386274a98ffe99d2fcdcfd9390",
"https://github.com/pylint-dev/astroid/commit/6fc23a9c5948dadeaf6890425c4a70c64aa7f513",
"https://github.com/pylint-dev/astroid/commit/51e540139a82b95233eb0a85a703a67795ef5ab2"
] | 2022-05-03T20:33:08
|
I think the same issue applies to `list`, `set` and `bytearray`. I think we can deal with all these at the same time.
|
pylint-dev__astroid-1540
|
[
"1403"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index a418b1b7af..cf1004721e 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -20,6 +20,10 @@ Release date: TBA
* Rename ``ModuleSpec`` -> ``module_type`` constructor parameter to match attribute
name and improve typing. Use ``type`` instead.
+* Infer the return value of the ``.copy()`` method on ``dict``, ``list``, ``set``,
+ and ``frozenset``.
+
+ Closes #1403
What's New in astroid 2.11.6?
=============================
diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py
index 5d7040a4e1..125e0858c8 100644
--- a/astroid/brain/brain_builtin_inference.py
+++ b/astroid/brain/brain_builtin_inference.py
@@ -4,8 +4,9 @@
"""Astroid hooks for various builtins."""
+import itertools
from functools import partial
-from typing import Optional
+from typing import Iterator, Optional
from astroid import arguments, helpers, inference_tip, nodes, objects, util
from astroid.builder import AstroidBuilder
@@ -892,6 +893,22 @@ def _build_dict_with_elements(elements):
return _build_dict_with_elements([])
+def _infer_copy_method(
+ node: nodes.Call, context: Optional[InferenceContext] = None
+) -> Iterator[nodes.NodeNG]:
+ assert isinstance(node.func, nodes.Attribute)
+ inferred_orig, inferred_copy = itertools.tee(node.func.expr.infer(context=context))
+ if all(
+ isinstance(
+ inferred_node, (nodes.Dict, nodes.List, nodes.Set, objects.FrozenSet)
+ )
+ for inferred_node in inferred_orig
+ ):
+ return inferred_copy
+
+ raise UseInferenceDefault()
+
+
# Builtins inference
register_builtin_transform(infer_bool, "bool")
register_builtin_transform(infer_super, "super")
@@ -920,3 +937,10 @@ def _build_dict_with_elements(elements):
inference_tip(_infer_object__new__decorator),
_infer_object__new__decorator_check,
)
+
+AstroidManager().register_transform(
+ nodes.Call,
+ inference_tip(_infer_copy_method),
+ lambda node: isinstance(node.func, nodes.Attribute)
+ and node.func.attrname == "copy",
+)
|
dict.copy() result is not inferred as dict
### Steps to reproduce
Run this code:
```python
import astroid
code = """
x = dict()
y = x.copy()
"""
ast = astroid.parse(code)
for name in ('x', 'y'):
node = ast.locals[name][0]
print(name, node.inferred())
```
### Current behavior
x [<Dict.dict l.2 at 0x7fffe852e110>]
y [Uninferable]
### Expected behavior
I expect `y` to be inferred as `dict` too.
### `python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"` output
2.4.2
|
1540
|
pylint-dev/astroid
|
diff --git a/tests/unittest_inference.py b/tests/unittest_inference.py
index 4069d0f320..5b6f09b283 100644
--- a/tests/unittest_inference.py
+++ b/tests/unittest_inference.py
@@ -2051,6 +2051,37 @@ def test_dict_invalid_args(self) -> None:
self.assertIsInstance(inferred, Instance)
self.assertEqual(inferred.qname(), "builtins.dict")
+ def test_copy_method_inference(self) -> None:
+ code = """
+ a_dict = {"b": 1, "c": 2}
+ b_dict = a_dict.copy()
+ b_dict #@
+
+ a_list = [1, 2, 3]
+ b_list = a_list.copy()
+ b_list #@
+
+ a_set = set([1, 2, 3])
+ b_set = a_set.copy()
+ b_set #@
+
+ a_frozenset = frozenset([1, 2, 3])
+ b_frozenset = a_frozenset.copy()
+ b_frozenset #@
+
+ a_unknown = unknown()
+ b_unknown = a_unknown.copy()
+ b_unknown #@
+ """
+ ast = extract_node(code, __name__)
+ self.assertInferDict(ast[0], {"b": 1, "c": 2})
+ self.assertInferList(ast[1], [1, 2, 3])
+ self.assertInferSet(ast[2], [1, 2, 3])
+ self.assertInferFrozenSet(ast[3], [1, 2, 3])
+
+ inferred_unknown = next(ast[4].infer())
+ assert inferred_unknown == util.Uninferable
+
def test_str_methods(self) -> None:
code = """
' '.decode() #@
|
none
|
[
"tests/unittest_inference.py::InferenceTest::test_copy_method_inference"
] |
[
"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_self_in_list",
"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_inner_value_redefined_by_subclass_with_mro",
"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::InferenceTest::test_uninferable_type_subscript",
"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::TestBool::test_class_subscript",
"tests/unittest_inference.py::TestType::test_type",
"tests/unittest_inference.py::ArgumentsTest::test_args",
"tests/unittest_inference.py::ArgumentsTest::test_args_overwritten",
"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_compare[<-False]",
"tests/unittest_inference.py::test_compare[<=-True]",
"tests/unittest_inference.py::test_compare[==-True]",
"tests/unittest_inference.py::test_compare[>=-True]",
"tests/unittest_inference.py::test_compare[>-False]",
"tests/unittest_inference.py::test_compare[!=-False]",
"tests/unittest_inference.py::test_compare_membership[in-True]",
"tests/unittest_inference.py::test_compare_membership[not",
"tests/unittest_inference.py::test_compare_lesseq_types[1-1-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[1-1.1-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[1.1-1-False]",
"tests/unittest_inference.py::test_compare_lesseq_types[1.0-1.0-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[abc-def-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[abc--False]",
"tests/unittest_inference.py::test_compare_lesseq_types[lhs6-rhs6-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[lhs7-rhs7-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[lhs8-rhs8-False]",
"tests/unittest_inference.py::test_compare_lesseq_types[True-True-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[True-False-False]",
"tests/unittest_inference.py::test_compare_lesseq_types[False-1-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[(1+0j)-(2+0j)-result12]",
"tests/unittest_inference.py::test_compare_lesseq_types[0.0--0.0-True]",
"tests/unittest_inference.py::test_compare_lesseq_types[0-1-result14]",
"tests/unittest_inference.py::test_compare_lesseq_types[\\x00-\\x01-True]",
"tests/unittest_inference.py::test_compare_chained",
"tests/unittest_inference.py::test_compare_inferred_members",
"tests/unittest_inference.py::test_compare_instance_members",
"tests/unittest_inference.py::test_compare_uninferable_member",
"tests/unittest_inference.py::test_compare_chained_comparisons_shortcircuit_on_false",
"tests/unittest_inference.py::test_compare_chained_comparisons_continue_on_true",
"tests/unittest_inference.py::test_compare_ifexp_constant",
"tests/unittest_inference.py::test_compare_typeerror",
"tests/unittest_inference.py::test_compare_multiple_possibilites",
"tests/unittest_inference.py::test_compare_ambiguous_multiple_possibilites",
"tests/unittest_inference.py::test_compare_nonliteral",
"tests/unittest_inference.py::test_compare_unknown",
"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_property_docstring",
"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_inference.py::test_pylint_issue_4692_attribute_inference_error_in_infer_import_from",
"tests/unittest_inference.py::test_issue_1090_infer_yield_type_base_class",
"tests/unittest_inference.py::test_namespace_package",
"tests/unittest_inference.py::test_namespace_package_same_name",
"tests/unittest_inference.py::test_relative_imports_init_package",
"tests/unittest_inference.py::test_inference_of_items_on_module_dict",
"tests/unittest_inference.py::test_recursion_on_inference_tip",
"tests/unittest_inference.py::test_function_def_cached_generator",
"tests/unittest_inference.py::InferenceTest::test_descriptor_are_callable",
"tests/unittest_inference.py::InferenceTest::test_function_metaclasses",
"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_compare_identity[is-True]",
"tests/unittest_inference.py::test_compare_identity[is",
"tests/unittest_inference.py::test_compare_dynamic",
"tests/unittest_inference.py::test_compare_known_false_branch",
"tests/unittest_inference.py::test_recursion_error_self_reference_type_call"
] |
[
"pytest -rA tests"
] |
pytest
|
{
"files": 2,
"hunks": 4,
"lines": 30
}
|
82b94253ac4165d8a49854e2685da63cea01f2e6
|
[
"https://github.com/pylint-dev/astroid/commit/b0a88e4503b16ddeb306eabf4fe1313d223f15ec",
"https://github.com/pylint-dev/astroid/commit/c1edabc2d13cd989e08847a77bca7f53e28f3d91",
"https://github.com/pylint-dev/astroid/commit/cf76d1a0839b49b95b01e9f07a75fb65ae3237fe"
] | 2021-10-09T08:16:46
|
pylint-dev__astroid-1209
|
[
"1208"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index b0a2db8880..9088e7bbc4 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -14,6 +14,11 @@ Release date: TBA
* Add support for wrapt 1.13
+* Fixes handling of nested partial functions
+
+ Closes pyCQA/pylint#2462
+ Closes #1208
+
What's New in astroid 2.8.2?
============================
diff --git a/astroid/objects.py b/astroid/objects.py
index 4241c170e9..ba2e41780f 100644
--- a/astroid/objects.py
+++ b/astroid/objects.py
@@ -265,10 +265,20 @@ def __init__(
# A typical FunctionDef automatically adds its name to the parent scope,
# but a partial should not, so defer setting parent until after init
self.parent = parent
- self.filled_positionals = len(call.positional_arguments[1:])
self.filled_args = call.positional_arguments[1:]
self.filled_keywords = call.keyword_arguments
+ wrapped_function = call.positional_arguments[0]
+ inferred_wrapped_function = next(wrapped_function.infer())
+ if isinstance(inferred_wrapped_function, PartialFunction):
+ self.filled_args = inferred_wrapped_function.filled_args + self.filled_args
+ self.filled_keywords = {
+ **inferred_wrapped_function.filled_keywords,
+ **self.filled_keywords,
+ }
+
+ self.filled_positionals = len(self.filled_args)
+
def infer_call_result(self, caller=None, context=None):
if context:
current_passed_keywords = {
|
Nested partial functions lose track of previously-filled args/kwargs
### Steps to reproduce
Cause of issue [#2462](https://github.com/PyCQA/pylint/issues/2462) for `pylint`
### Current behavior
```python
node = astroid.extract_node(
"""
from functools import partial
def test(a, b, c):
return a + b + c
test1 = partial(test, 1)
test2 = partial(test1, 2)
test2(3)
"""
call_site = astroid.arguments.CallSite.from_call(node)
called_func = next(node.func.infer())
called_args = called_func.filled_args + call_site.positional_arguments
```
The `called_args` above will contain args for `2` and `3`, but not `1`, because the second call to `partial` overwrites the first, dropping `1` from the list of `filled_args`.
### Expected behavior
All args/kwargs locked in by calls to `partial` should be present in the final function. I've written a test similar to the code example above and have implemented a fix, so I'll open a PR shortly.
### `python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"` output
`2.6.6`
|
1209
|
pylint-dev/astroid
|
diff --git a/tests/unittest_brain.py b/tests/unittest_brain.py
index e3362c925a..722e163180 100644
--- a/tests/unittest_brain.py
+++ b/tests/unittest_brain.py
@@ -2986,6 +2986,34 @@ def scope():
assert set(mod_scope) == {"test", "scope", "partial"}
assert set(scope) == {"test2"}
+ def test_multiple_partial_args(self) -> None:
+ "Make sure partials remember locked-in args."
+ ast_node = astroid.extract_node(
+ """
+ from functools import partial
+ def test(a, b, c, d, e=5):
+ return a + b + c + d + e
+ test1 = partial(test, 1)
+ test2 = partial(test1, 2)
+ test3 = partial(test2, 3)
+ test3(4, e=6) #@
+ """
+ )
+ expected_args = [1, 2, 3, 4]
+ expected_keywords = {"e": 6}
+
+ call_site = astroid.arguments.CallSite.from_call(ast_node)
+ called_func = next(ast_node.func.infer())
+ called_args = called_func.filled_args + call_site.positional_arguments
+ called_keywords = {**called_func.filled_keywords, **call_site.keyword_arguments}
+ assert len(called_args) == len(expected_args)
+ assert [arg.value for arg in called_args] == expected_args
+ assert len(called_keywords) == len(expected_keywords)
+
+ for keyword, value in expected_keywords.items():
+ assert keyword in called_keywords
+ assert called_keywords[keyword].value == value
+
def test_http_client_brain() -> None:
node = astroid.extract_node(
|
none
|
[
"tests/unittest_brain.py::TestFunctoolsPartial::test_multiple_partial_args"
] |
[
"tests/unittest_brain.py::HashlibTest::test_hashlib",
"tests/unittest_brain.py::HashlibTest::test_hashlib_py36",
"tests/unittest_brain.py::CollectionsDequeTests::test_deque",
"tests/unittest_brain.py::CollectionsDequeTests::test_deque_py35methods",
"tests/unittest_brain.py::CollectionsDequeTests::test_deque_py39methods",
"tests/unittest_brain.py::OrderedDictTest::test_ordered_dict_py34method",
"tests/unittest_brain.py::NamedTupleTest::test_invalid_label_does_not_crash_inference",
"tests/unittest_brain.py::NamedTupleTest::test_invalid_typename_does_not_crash_inference",
"tests/unittest_brain.py::NamedTupleTest::test_keyword_typename_does_not_crash_inference",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_access_class_fields",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_advanced_inference",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_base",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_bases_are_actually_names_not_nodes",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_func_form",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_func_form_args_and_kwargs",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_inference",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_inference_failure",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_instance_attrs",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_rename_duplicates",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_rename_keywords",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_rename_uninferable",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_uninferable_fields",
"tests/unittest_brain.py::NamedTupleTest::test_no_rename_duplicates_does_not_crash_inference",
"tests/unittest_brain.py::NamedTupleTest::test_no_rename_keywords_does_not_crash_inference",
"tests/unittest_brain.py::NamedTupleTest::test_no_rename_nonident_does_not_crash_inference",
"tests/unittest_brain.py::NamedTupleTest::test_no_rename_underscore_does_not_crash_inference",
"tests/unittest_brain.py::NamedTupleTest::test_pathological_str_does_not_crash_inference",
"tests/unittest_brain.py::NamedTupleTest::test_typeerror_does_not_crash_inference",
"tests/unittest_brain.py::DefaultDictTest::test_1",
"tests/unittest_brain.py::ModuleExtenderTest::test_extension_modules",
"tests/unittest_brain.py::MultiprocessingBrainTest::test_module_name",
"tests/unittest_brain.py::MultiprocessingBrainTest::test_multiprocessing_manager",
"tests/unittest_brain.py::MultiprocessingBrainTest::test_multiprocessing_module_attributes",
"tests/unittest_brain.py::ThreadingBrainTest::test_boundedsemaphore",
"tests/unittest_brain.py::ThreadingBrainTest::test_lock",
"tests/unittest_brain.py::ThreadingBrainTest::test_rlock",
"tests/unittest_brain.py::ThreadingBrainTest::test_semaphore",
"tests/unittest_brain.py::EnumBrainTest::test_dont_crash_on_for_loops_in_body",
"tests/unittest_brain.py::EnumBrainTest::test_enum_func_form_has_dunder_members",
"tests/unittest_brain.py::EnumBrainTest::test_enum_func_form_is_class_not_instance",
"tests/unittest_brain.py::EnumBrainTest::test_enum_func_form_iterable",
"tests/unittest_brain.py::EnumBrainTest::test_enum_func_form_subscriptable",
"tests/unittest_brain.py::EnumBrainTest::test_enum_multiple_base_classes",
"tests/unittest_brain.py::EnumBrainTest::test_enum_name_and_value_members_override_dynamicclassattr",
"tests/unittest_brain.py::EnumBrainTest::test_enum_name_is_str_on_self",
"tests/unittest_brain.py::EnumBrainTest::test_enum_starred_is_skipped",
"tests/unittest_brain.py::EnumBrainTest::test_enum_subclass_different_modules",
"tests/unittest_brain.py::EnumBrainTest::test_enum_subclass_member_method",
"tests/unittest_brain.py::EnumBrainTest::test_enum_subclass_member_name",
"tests/unittest_brain.py::EnumBrainTest::test_enum_subclass_member_value",
"tests/unittest_brain.py::EnumBrainTest::test_enum_tuple_list_values",
"tests/unittest_brain.py::EnumBrainTest::test_ignores_with_nodes_from_body_of_enum",
"tests/unittest_brain.py::EnumBrainTest::test_infer_enum_value_as_the_right_type",
"tests/unittest_brain.py::EnumBrainTest::test_int_enum",
"tests/unittest_brain.py::EnumBrainTest::test_looks_like_enum_false_positive",
"tests/unittest_brain.py::EnumBrainTest::test_mingled_single_and_double_quotes_does_not_crash",
"tests/unittest_brain.py::EnumBrainTest::test_simple_enum",
"tests/unittest_brain.py::EnumBrainTest::test_special_characters_does_not_crash",
"tests/unittest_brain.py::EnumBrainTest::test_user_enum_false_positive",
"tests/unittest_brain.py::PytestBrainTest::test_pytest",
"tests/unittest_brain.py::TypeBrain::test_builtin_subscriptable",
"tests/unittest_brain.py::TypeBrain::test_invalid_type_subscript",
"tests/unittest_brain.py::TypeBrain::test_type_subscript",
"tests/unittest_brain.py::CollectionsBrain::test_collections_object_not_subscriptable",
"tests/unittest_brain.py::CollectionsBrain::test_collections_object_subscriptable",
"tests/unittest_brain.py::CollectionsBrain::test_collections_object_subscriptable_2",
"tests/unittest_brain.py::CollectionsBrain::test_collections_object_subscriptable_3",
"tests/unittest_brain.py::CollectionsBrain::test_collections_object_subscriptable_4",
"tests/unittest_brain.py::TypingBrain::test_callable_type",
"tests/unittest_brain.py::TypingBrain::test_has_dunder_args",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_base",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_bug_pylint_4383",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_can_correctly_access_methods",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_class_form",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_few_args",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_few_fields",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_inference",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_inference_nonliteral",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_inferred_as_class",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_instance_attrs",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_nested_class",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_simple",
"tests/unittest_brain.py::TypingBrain::test_tuple_type",
"tests/unittest_brain.py::TypingBrain::test_typed_dict",
"tests/unittest_brain.py::TypingBrain::test_typing_alias_type",
"tests/unittest_brain.py::TypingBrain::test_typing_alias_type_2",
"tests/unittest_brain.py::TypingBrain::test_typing_annotated_subscriptable",
"tests/unittest_brain.py::TypingBrain::test_typing_cast",
"tests/unittest_brain.py::TypingBrain::test_typing_cast_attribute",
"tests/unittest_brain.py::TypingBrain::test_typing_generic_slots",
"tests/unittest_brain.py::TypingBrain::test_typing_generic_subscriptable",
"tests/unittest_brain.py::TypingBrain::test_typing_namedtuple_dont_crash_on_no_fields",
"tests/unittest_brain.py::TypingBrain::test_typing_object_builtin_subscriptable",
"tests/unittest_brain.py::TypingBrain::test_typing_object_not_subscriptable",
"tests/unittest_brain.py::TypingBrain::test_typing_object_notsubscriptable_3",
"tests/unittest_brain.py::TypingBrain::test_typing_object_subscriptable",
"tests/unittest_brain.py::TypingBrain::test_typing_object_subscriptable_2",
"tests/unittest_brain.py::TypingBrain::test_typing_type_subscriptable",
"tests/unittest_brain.py::TypingBrain::test_typing_types",
"tests/unittest_brain.py::ReBrainTest::test_re_pattern_subscriptable",
"tests/unittest_brain.py::ReBrainTest::test_regex_flags",
"tests/unittest_brain.py::BrainFStrings::test_no_crash_on_const_reconstruction",
"tests/unittest_brain.py::BrainNamedtupleAnnAssignTest::test_no_crash_on_ann_assign_in_namedtuple",
"tests/unittest_brain.py::BrainUUIDTest::test_uuid_has_int_member",
"tests/unittest_brain.py::RandomSampleTest::test_inferred_successfully",
"tests/unittest_brain.py::RandomSampleTest::test_no_crash_on_evaluatedobject",
"tests/unittest_brain.py::SubprocessTest::test_popen_does_not_have_class_getitem",
"tests/unittest_brain.py::SubprocessTest::test_subprcess_check_output",
"tests/unittest_brain.py::SubprocessTest::test_subprocess_args",
"tests/unittest_brain.py::TestIsinstanceInference::test_type_type",
"tests/unittest_brain.py::TestIsinstanceInference::test_object_type",
"tests/unittest_brain.py::TestIsinstanceInference::test_type_object",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_int_true",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_int_false",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_object_true",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_object_true3",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_class_false",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_type_false",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_str_true",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_str_false",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_tuple_argument",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_type_false2",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_object_true2",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_type_true",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_edge_case",
"tests/unittest_brain.py::TestIsinstanceInference::test_uninferable_bad_type",
"tests/unittest_brain.py::TestIsinstanceInference::test_uninferable_keywords",
"tests/unittest_brain.py::TestIsinstanceInference::test_too_many_args",
"tests/unittest_brain.py::TestIsinstanceInference::test_first_param_is_uninferable",
"tests/unittest_brain.py::TestIssubclassBrain::test_type_type",
"tests/unittest_brain.py::TestIssubclassBrain::test_object_type",
"tests/unittest_brain.py::TestIssubclassBrain::test_type_object",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_same_class",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_not_the_same_class",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_object_true",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_same_user_defined_class",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_different_user_defined_classes",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_type_false",
"tests/unittest_brain.py::TestIssubclassBrain::test_isinstance_tuple_argument",
"tests/unittest_brain.py::TestIssubclassBrain::test_isinstance_object_true2",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_short_circuit",
"tests/unittest_brain.py::TestIssubclassBrain::test_uninferable_bad_type",
"tests/unittest_brain.py::TestIssubclassBrain::test_uninferable_keywords",
"tests/unittest_brain.py::TestIssubclassBrain::test_too_many_args",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_list",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_tuple",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_var",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_dict",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_set",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_object",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_class_with_metaclass",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_object_failure",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_string",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_generator_failure",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_failure_missing_variable",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_bytes",
"tests/unittest_brain.py::TestLenBuiltinInference::test_int_subclass_result",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_builtin_inference_attribute_error_str",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_builtin_inference_recursion_error_self_referential_attribute",
"tests/unittest_brain.py::test_infer_str",
"tests/unittest_brain.py::test_infer_int",
"tests/unittest_brain.py::test_infer_dict_from_keys",
"tests/unittest_brain.py::TestFunctoolsPartial::test_invalid_functools_partial_calls",
"tests/unittest_brain.py::TestFunctoolsPartial::test_inferred_partial_function_calls",
"tests/unittest_brain.py::TestFunctoolsPartial::test_partial_assignment",
"tests/unittest_brain.py::TestFunctoolsPartial::test_partial_does_not_affect_scope",
"tests/unittest_brain.py::test_http_client_brain",
"tests/unittest_brain.py::test_http_status_brain",
"tests/unittest_brain.py::test_oserror_model",
"tests/unittest_brain.py::test_crypt_brain",
"tests/unittest_brain.py::test_str_and_bytes['hey'.encode()-Const-]",
"tests/unittest_brain.py::test_str_and_bytes[b'hey'.decode()-Const-]",
"tests/unittest_brain.py::test_str_and_bytes['hey'.encode().decode()-Const-]",
"tests/unittest_brain.py::test_no_recursionerror_on_self_referential_length_check",
"tests/unittest_brain.py::TestLenBuiltinInference::test_int_subclass_argument"
] |
[
". venv/bin/activate && pytest -rA"
] |
pytest
|
{
"files": 2,
"hunks": 2,
"lines": 17
}
|
||
Possible duplicate of #1008
This problem is due to the fact `_infer_context_manager` takes caller function, using its current context, instead of the original callers context. This may be fixed for example by adding data to `Generator` instance, by `infer_call_result` that signifies its possible value types.
I'm not familiar with the codebase, it seems to me that that this is not the correct approach, but, the correct approach is to pass this data inside the `context` structure. But it's not clear to me how to do that.
|
c9c498348174b38ce35bfe001353c8ebea262802
|
[
"https://github.com/pylint-dev/astroid/commit/5ba74b0ba63b8e5fb403a0fff251064cd45315b1",
"https://github.com/pylint-dev/astroid/commit/be4e22dfc9e665f1660488e682718d3da378745b",
"https://github.com/pylint-dev/astroid/commit/74ea8d2d5414d2f3835ee1fe3c9ef3432e1a4e4d",
"https://github.com/pylint-dev/astroid/commit/a31dbe1e843f8fe43ca2f67c93ec532d526eecea",
"https://github.com/pylint-dev/astroid/commit/2900086fd52c51fbd79511243f9fc39c7d6a0005",
"https://github.com/pylint-dev/astroid/commit/f02b4f246d5a6cf4f5ef27fe957d4dd28ac5ec12",
"https://github.com/pylint-dev/astroid/commit/2abc72b62982a64713ea94e697cce0143aff9ba6",
"https://github.com/pylint-dev/astroid/commit/8c100465ebc565681d9b78b0632ebf4795c580dc",
"https://github.com/pylint-dev/astroid/commit/604c42344a565bd5fe7bbd36120f2e6d4b267faa",
"https://github.com/pylint-dev/astroid/commit/41ab75ac0669087e9bf8885157357739c4721411",
"https://github.com/pylint-dev/astroid/commit/25f4093144f2b220a4de2c5afd528278fc5d8f81",
"https://github.com/pylint-dev/astroid/commit/5197d35035b1d0fb13da255260276a06bba54895",
"https://github.com/pylint-dev/astroid/commit/0bce5fea411c965b693e1ac08913eb2f53d6f0b6",
"https://github.com/pylint-dev/astroid/commit/9377803a1e7ed21405aca58b6059b0cc395f8b30"
] | 2021-07-10T10:44:32
|
pylint-dev__astroid-1092
|
[
"1090"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index 98110ede8e..ed9739bb5b 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -12,6 +12,11 @@ What's New in astroid 2.6.3?
============================
Release date: TBA
+
+* Fix a bad inferenece type for yield values inside of a derived class.
+
+ Closes PyCQA/astroid#1090
+
* Fix a crash when the node is a 'Module' in the brain builtin inference
Closes PyCQA/pylint#4671
diff --git a/astroid/bases.py b/astroid/bases.py
index 7f375f8994..e44ee70bd4 100644
--- a/astroid/bases.py
+++ b/astroid/bases.py
@@ -26,7 +26,7 @@
import collections
from astroid import context as contextmod
-from astroid import util
+from astroid import decorators, util
from astroid.const import BUILTINS, PY310_PLUS
from astroid.exceptions import (
AstroidTypeError,
@@ -543,9 +543,14 @@ class Generator(BaseInstance):
special_attributes = util.lazy_descriptor(objectmodel.GeneratorModel)
- def __init__(self, parent=None):
+ def __init__(self, parent=None, generator_initial_context=None):
super().__init__()
self.parent = parent
+ self._call_context = contextmod.copy_context(generator_initial_context)
+
+ @decorators.cached
+ def infer_yield_types(self):
+ yield from self.parent.infer_yield_result(self._call_context)
def callable(self):
return False
diff --git a/astroid/protocols.py b/astroid/protocols.py
index 228000ab18..4e2dc6312e 100644
--- a/astroid/protocols.py
+++ b/astroid/protocols.py
@@ -489,22 +489,8 @@ def _infer_context_manager(self, mgr, context):
# It doesn't interest us.
raise InferenceError(node=func)
- # Get the first yield point. If it has multiple yields,
- # then a RuntimeError will be raised.
+ yield next(inferred.infer_yield_types())
- possible_yield_points = func.nodes_of_class(nodes.Yield)
- # Ignore yields in nested functions
- yield_point = next(
- (node for node in possible_yield_points if node.scope() == func), None
- )
- if yield_point:
- if not yield_point.value:
- const = nodes.Const(None)
- const.parent = yield_point
- const.lineno = yield_point.lineno
- yield const
- else:
- yield from yield_point.value.infer(context=context)
elif isinstance(inferred, bases.Instance):
try:
enter = next(inferred.igetattr("__enter__", context=context))
diff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py
index 09ed3910de..5fa890d94e 100644
--- a/astroid/scoped_nodes.py
+++ b/astroid/scoped_nodes.py
@@ -1708,6 +1708,21 @@ def is_generator(self):
"""
return bool(next(self._get_yield_nodes_skip_lambdas(), False))
+ def infer_yield_result(self, context=None):
+ """Infer what the function yields when called
+
+ :returns: What the function yields
+ :rtype: iterable(NodeNG or Uninferable) or None
+ """
+ for yield_ in self.nodes_of_class(node_classes.Yield):
+ if yield_.value is None:
+ const = node_classes.Const(None)
+ const.parent = yield_
+ const.lineno = yield_.lineno
+ yield const
+ elif yield_.scope() == self:
+ yield from yield_.value.infer(context=context)
+
def infer_call_result(self, caller=None, context=None):
"""Infer what the function returns when called.
@@ -1719,7 +1734,7 @@ def infer_call_result(self, caller=None, context=None):
generator_cls = bases.AsyncGenerator
else:
generator_cls = bases.Generator
- result = generator_cls(self)
+ result = generator_cls(self, generator_initial_context=context)
yield result
return
# This is really a gigantic hack to work around metaclass generators
|
Yield self is inferred to be of a mistaken type
### Steps to reproduce
1. Run the following
```
import astroid
print(list(astroid.parse('''
import contextlib
class A:
@contextlib.contextmanager
def get(self):
yield self
class B(A):
def play():
pass
with B().get() as b:
b.play()
''').ilookup('b')))
```
### Current behavior
```Prints [<Instance of .A at 0x...>]```
### Expected behavior
```Prints [<Instance of .B at 0x...>]```
### `python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"` output
2.6.2
|
1092
|
pylint-dev/astroid
|
diff --git a/tests/unittest_inference.py b/tests/unittest_inference.py
index 1fe83dc8c7..afc24dc28e 100644
--- a/tests/unittest_inference.py
+++ b/tests/unittest_inference.py
@@ -6154,5 +6154,26 @@ def test_issue926_binop_referencing_same_name_is_not_uninferable():
assert inferred[0].value == 3
+def test_issue_1090_infer_yield_type_base_class():
+ code = """
+import contextlib
+
+class A:
+ @contextlib.contextmanager
+ def get(self):
+ yield self
+
+class B(A):
+ def play():
+ pass
+
+with B().get() as b:
+ b
+b
+ """
+ node = extract_node(code)
+ assert next(node.infer()).pytype() == ".B"
+
+
if __name__ == "__main__":
unittest.main()
|
none
|
[
"tests/unittest_inference.py::test_issue_1090_infer_yield_type_base_class"
] |
[
"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_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": 4,
"hunks": 6,
"lines": 47
}
|
|
> but I thought we wanted these to be accessible on all nodes, just initialised as None.
Yeah, that was the idea initially.
> `AttributeError` on both of the last lines.
For now a workaround would be to use `hasattr(node, "end_lineno")`. Not pretty but it should do. That should unblock https://github.com/PyCQA/pylint/pull/5343.
--
We could try to address it in #1262. The issue are these lines here
https://github.com/PyCQA/astroid/blob/775c8f7acb97e50cd643b6e1a20042aa8cfa98a3/astroid/nodes/scoped_nodes.py#L472-L475
combined with the missing `super().__init__()` call.
I noticed just now that the `lineno` for `Module` is set to `0`. The type annotation thus doesn't make sense.
https://github.com/PyCQA/astroid/blob/775c8f7acb97e50cd643b6e1a20042aa8cfa98a3/astroid/nodes/scoped_nodes.py#L387-L396
There could also be an argument that it should be `lineno = 1` instead. As all are `1-indexed`.
|
e840a7c54d3d8b5be2db1e66f34a5368c64fc3f7
|
[
"https://github.com/pylint-dev/astroid/commit/dbe50556d926d02ac3dca62dc778679597ed3afc",
"https://github.com/pylint-dev/astroid/commit/77ba9a31916f896ebc32a87caff87d3d7165ea6d",
"https://github.com/pylint-dev/astroid/commit/dd491d09cd57cdf2f62a6694c3b93c75dcfb184a",
"https://github.com/pylint-dev/astroid/commit/d2a206e612c0f5d7d03b2655caa1d90633eb1916",
"https://github.com/pylint-dev/astroid/commit/835b266a180102fc7fec42484e335a0a2f81fc72",
"https://github.com/pylint-dev/astroid/commit/da985f3a6fa0326a0f192d85bfd51fed873d9a5f",
"https://github.com/pylint-dev/astroid/commit/71f0ae44796c4367779abbd46d9f8d2314ae5fd9",
"https://github.com/pylint-dev/astroid/commit/21ece44aeec473d43bd36ad7c33fa634bf68d586",
"https://github.com/pylint-dev/astroid/commit/002fdc1242ab2a58bbff7a184b1362005123ff40",
"https://github.com/pylint-dev/astroid/commit/e4c31d7f493114868002ebfbd98c7c522073d286",
"https://github.com/pylint-dev/astroid/commit/54bb3dd706926e05ba6c126ecf454a54e1bfeb72",
"https://github.com/pylint-dev/astroid/commit/757205a276d3d374ab4f1c8c38802637fabb83f9",
"https://github.com/pylint-dev/astroid/commit/2700a1347c3d110c1d75d1701e3761c9d905c3e9"
] | 2021-11-19T16:46:31
|
pylint-dev__astroid-1262
|
[
"1273"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index 3b026ba905..9641cf0441 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -18,6 +18,9 @@ Release date: TBA
Closes #1260
+* Fix ``Module`` nodes not having a ``col_offset``, ``end_lineno``, and ``end_col_offset``
+ attributes.
+
* Fix typing and update explanation for ``Arguments.args`` being ``None``.
* Fix crash if a variable named ``type`` is subscripted in a generator expression.
diff --git a/astroid/nodes/scoped_nodes.py b/astroid/nodes/scoped_nodes.py
index 0c745a4fca..96a034c868 100644
--- a/astroid/nodes/scoped_nodes.py
+++ b/astroid/nodes/scoped_nodes.py
@@ -389,10 +389,8 @@ class Module(LocalsDictNodeNG):
:type: int or None
"""
- lineno = 0
+ lineno: Literal[0] = 0
"""The line that this node appears on in the source code.
-
- :type: int or None
"""
# attributes below are set by the builder module or by raw factories
@@ -469,7 +467,6 @@ class Module(LocalsDictNodeNG):
)
_other_other_fields = ("locals", "globals")
- lineno: None
col_offset: None
end_lineno: None
end_col_offset: None
@@ -512,7 +509,6 @@ def __init__(
self.file = file
self.path = path
self.package = package
- self.parent = parent
self.pure_python = pure_python
self.locals = self.globals = {}
"""A map of the name of a local variable to the node defining the local.
@@ -526,6 +522,8 @@ def __init__(
"""
self.future_imports = set()
+ super().__init__(lineno=0, parent=parent)
+
# pylint: enable=redefined-builtin
def postinit(self, body=None):
|
``nodes.Module`` don't have a ``end_lineno`` and ``end_col_offset``
### Steps to reproduce
```python
import astroid
code = """
print("a module")
"""
module = astroid.parse(code)
print(module.end_lineno)
print(module.end_col_offset)
```
### Current behavior
`AttributeError` on both of the last lines.
### Expected behavior
@cdce8p Let me know if I misunderstood you, but I thought we wanted these to be accessible on all nodes, just initialised as `None`.
If that was not the case, I would make the case to do so as it allows you to do `node.end_lineno` without running in to `AttributeError`'s.
### Version
Latest `main`.
|
1262
|
pylint-dev/astroid
|
diff --git a/tests/unittest_nodes_lineno.py b/tests/unittest_nodes_lineno.py
index 75d664dc48..73cf0207cc 100644
--- a/tests/unittest_nodes_lineno.py
+++ b/tests/unittest_nodes_lineno.py
@@ -2,6 +2,7 @@
import pytest
+import astroid
from astroid import builder, nodes
from astroid.const import PY38_PLUS, PY39_PLUS, PY310_PLUS
@@ -1221,3 +1222,14 @@ class X(Parent, var=42):
assert (c1.body[0].lineno, c1.body[0].col_offset) == (4, 4)
assert (c1.body[0].end_lineno, c1.body[0].end_col_offset) == (4, 8)
# fmt: on
+
+ @staticmethod
+ def test_end_lineno_module() -> None:
+ """Tests for Module"""
+ code = """print()"""
+ module = astroid.parse(code)
+ assert isinstance(module, nodes.Module)
+ assert module.lineno == 0
+ assert module.col_offset is None
+ assert module.end_lineno is None
+ assert module.end_col_offset is None
|
none
|
[
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_module"
] |
[
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_container",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_name",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_attribute",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_call",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_assignment",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_mix_stmts",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_mix_nodes",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_ops",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_if",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_for",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_const",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_function",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_dict",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_try",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_subscript",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_import",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_with",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_while",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_string",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_comprehension",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_class"
] |
[
"pytest -rA tests"
] |
pytest
|
{
"files": 2,
"hunks": 5,
"lines": 11
}
|
|
#1276 is actually working on this, but we ran into issues with the different `ast` parsers on different versions and implementations of Python.
Note that the line numbers are not correct on some versions which is why the PR stalled a bit.
Are you on a version lower than python 3.8 @tristanlatr ?
I'm trying to write code that is python 3.6+ compatible.
OK, to summarize python 3.8 has better lineno/column and we're focusing on python 3.8+ because fixing the information coming from the ast takes a long time. Also python 3.6+ is EOL now. That said I've seen [this comment](https://github.com/PyCQA/astroid/pull/1276#discussion_r783337011) you made and if it works we could merge.
Until #1276 is merged, my workaround is the following:
```python
astroid.rebuilder.TreeRebuilder._get_doc = lambda _,o:(o, None)
```
Then parse docstrings statements manually.
|
56f5f055e4847e9fc2b74162ccad8f2a11db3bfc
|
[
"https://github.com/pylint-dev/astroid/commit/06c6cb3490b9b2a9bded08f901842b099d746975",
"https://github.com/pylint-dev/astroid/commit/1183453b22f0c915ae9f6c2dffffa68a096bf5b9",
"https://github.com/pylint-dev/astroid/commit/0b6c2556e57667783cc336a1b239fe2b243b6c18",
"https://github.com/pylint-dev/astroid/commit/a437d854132e8568e52c4a772bd50eed31189052",
"https://github.com/pylint-dev/astroid/commit/ae28749fe0fcba6cc0f90b3c7cd40eaeaf465fe0",
"https://github.com/pylint-dev/astroid/commit/f308dc96a5968612463cef9ef41cba34120b7af0",
"https://github.com/pylint-dev/astroid/commit/cc59a2c5557c77df0dfd858c546fa222159a35c2",
"https://github.com/pylint-dev/astroid/commit/2b49307df00e810f43f74a33a8195f568bc4feb6",
"https://github.com/pylint-dev/astroid/commit/e926ad38aed434aff243affda57634f4ab386341",
"https://github.com/pylint-dev/astroid/commit/861bf47e5db48c49d705c34932e9cebf35182c60",
"https://github.com/pylint-dev/astroid/commit/5bb2942c6643d4e36bbd18ac0e1ec9dbe1829fb4",
"https://github.com/pylint-dev/astroid/commit/cefbe623c7be9d49903c0d3c8f0130fd6697b201",
"https://github.com/pylint-dev/astroid/commit/922575a6208419cf91ee17f2b51cccd4917edfe0",
"https://github.com/pylint-dev/astroid/commit/05772550f24a9718a85b0d8d37b59289c1d5cb31",
"https://github.com/pylint-dev/astroid/commit/1138b00ac5e8eb4e8a1c946557ee7fe55516bdb7",
"https://github.com/pylint-dev/astroid/commit/5150ef05e15cd2a1fe766cdbde1b866184bbaa39",
"https://github.com/pylint-dev/astroid/commit/a0b314cd6ea88fae539a4e95fd72bcf42b0359b2",
"https://github.com/pylint-dev/astroid/commit/7514c6abfb84217ada712d114464f2b59a430212",
"https://github.com/pylint-dev/astroid/commit/94df31110fe0bcfe11786b26ec31940c3d629b57",
"https://github.com/pylint-dev/astroid/commit/ec28a0def38caa6395c61bcee32a26aa01f47761",
"https://github.com/pylint-dev/astroid/commit/d905e517bcb1a7edd72657914f90a334cf9a0204",
"https://github.com/pylint-dev/astroid/commit/f699dae04f9f702f84094210cb5da7dc0f2ad047",
"https://github.com/pylint-dev/astroid/commit/dfb39c76abafe61712caa266be71956a3bbd26f7",
"https://github.com/pylint-dev/astroid/commit/e5195d0403d7bfd58e1fa71f1f9024c97089330c",
"https://github.com/pylint-dev/astroid/commit/a058c717100772e57c05678b855bac23e03182b4",
"https://github.com/pylint-dev/astroid/commit/f9cd4b3ad89fe47cc225ad0c5d60513773f1a829",
"https://github.com/pylint-dev/astroid/commit/f31c38074ae18e20d343a71d338e5f046a2ed176",
"https://github.com/pylint-dev/astroid/commit/e61409f68ec297434a49ad83c7688facba301d99",
"https://github.com/pylint-dev/astroid/commit/e1a8e25d079776c3fbbbcc8ddc825be155ba6c0a",
"https://github.com/pylint-dev/astroid/commit/c21d5549bfaf9004140f97712300f09817bc773b",
"https://github.com/pylint-dev/astroid/commit/f8e59b091e2344faa21aa26ed7f1dbcdf8371c56",
"https://github.com/pylint-dev/astroid/commit/0ed7e0880d1033a6e25ce7cb64307fa7d34b5b0f",
"https://github.com/pylint-dev/astroid/commit/d64323e56e626b67596bb47b6ad76b53a0c9b774",
"https://github.com/pylint-dev/astroid/commit/6d33464c89f132ffec49e93b6ed4101bc939f6bf",
"https://github.com/pylint-dev/astroid/commit/8e429ef4668e80f10587ece383baf5ec757a3c52",
"https://github.com/pylint-dev/astroid/commit/7079a96a66ca917605342cb3617671a7bcee9c3e",
"https://github.com/pylint-dev/astroid/commit/5028f74e03b749548686ead6124ec7f17e29f8b1",
"https://github.com/pylint-dev/astroid/commit/a1774e0050acd12ff92eb626f38e45294619cb95",
"https://github.com/pylint-dev/astroid/commit/74af4f59f79e66cdea26072689712125a57e204c",
"https://github.com/pylint-dev/astroid/commit/5709d81659694087425eb098658be79998400e84",
"https://github.com/pylint-dev/astroid/commit/5f9e132115cf74b1c3351f36dedf177cf20e547b",
"https://github.com/pylint-dev/astroid/commit/b4d3806b4ae20211fada2d91afd66e1c86b705d8",
"https://github.com/pylint-dev/astroid/commit/529e79474376b5e0171d6bb5dd2afeb93a45d773",
"https://github.com/pylint-dev/astroid/commit/331b36ae9df62720b9bf27dabf991719c55d93d5",
"https://github.com/pylint-dev/astroid/commit/94846c3c9e90d9e6d6160e85c7fcdd2556d32338",
"https://github.com/pylint-dev/astroid/commit/456ecc6715d1c9b28b10ea7f4f15530bb521bf54",
"https://github.com/pylint-dev/astroid/commit/8cb685d000409f91d38268d595a009b591a1d94a",
"https://github.com/pylint-dev/astroid/commit/761ce6f93aa4a197fe3ec54116b1f94f72566344",
"https://github.com/pylint-dev/astroid/commit/89b0a411b224487045b52565f532334722422c6a",
"https://github.com/pylint-dev/astroid/commit/e5cdda559be31700548e1b8e715d62c5e8e9d5f4",
"https://github.com/pylint-dev/astroid/commit/0d847a12841276c590f3041f29419e7459fcae93",
"https://github.com/pylint-dev/astroid/commit/263431894bf94239563af0233893bf780031e28e",
"https://github.com/pylint-dev/astroid/commit/dc265ad03395ebd4f4250c59fef9243b967f0bbb",
"https://github.com/pylint-dev/astroid/commit/da92f1c901efda111fba3ebf25730f04d254da07",
"https://github.com/pylint-dev/astroid/commit/43d2d400d207a053a805c59f6e48c1f527fb4b02",
"https://github.com/pylint-dev/astroid/commit/1a593ca0eef51581fc03b98eea19ab10a5e1d53f",
"https://github.com/pylint-dev/astroid/commit/5e2324e5713e3c98eaf3b7800341a5d54d67610f",
"https://github.com/pylint-dev/astroid/commit/bc6f0e82986b43df5a35d58369f0c708da9f75ac",
"https://github.com/pylint-dev/astroid/commit/c43eb9cc38353a4095cd3f642576123286bd0d43",
"https://github.com/pylint-dev/astroid/commit/847a2fa399ebf29269c2775722bb6f44071ddcba",
"https://github.com/pylint-dev/astroid/commit/d3f7b8b3353657717a2ea5d99bc3f41d950fb7d6",
"https://github.com/pylint-dev/astroid/commit/450720540e731184603d0649150a56b2dcfc0f6c",
"https://github.com/pylint-dev/astroid/commit/c5f918156994e84667254a9608d3481ec386ec69",
"https://github.com/pylint-dev/astroid/commit/fe86d0dde19f6bca39d8d86502f6975e7a8fc83a"
] | 2021-11-26T13:53:07
|
pylint-dev__astroid-1276
|
[
"1340"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index 670628b8da..ea4c1e3319 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -6,6 +6,8 @@ What's New in astroid 2.11.0?
=============================
Release date: TBA
+* Add new (optional) ``doc_node`` attribute to ``nodes.Module``, ``nodes.ClassDef``,
+ and ``nodes.FunctionDef``.
What's New in astroid 2.10.1?
@@ -13,7 +15,6 @@ What's New in astroid 2.10.1?
Release date: TBA
-
What's New in astroid 2.10.0?
=============================
Release date: 2022-02-27
diff --git a/astroid/const.py b/astroid/const.py
index 93bf19e13a..74b97cfb7c 100644
--- a/astroid/const.py
+++ b/astroid/const.py
@@ -1,4 +1,5 @@
import enum
+import platform
import sys
PY36 = sys.version_info[:2] == (3, 6)
@@ -11,6 +12,8 @@
WIN32 = sys.platform == "win32"
+IMPLEMENTATION_PYPY = platform.python_implementation() == "PyPy"
+
class Context(enum.Enum):
Load = 1
diff --git a/astroid/nodes/scoped_nodes/scoped_nodes.py b/astroid/nodes/scoped_nodes/scoped_nodes.py
index 182ec8f4a1..a8dcf3549f 100644
--- a/astroid/nodes/scoped_nodes/scoped_nodes.py
+++ b/astroid/nodes/scoped_nodes/scoped_nodes.py
@@ -386,7 +386,7 @@ class Module(LocalsDictNodeNG):
<Module l.0 at 0x7f23b2e4eda0>
"""
- _astroid_fields = ("body",)
+ _astroid_fields = ("doc_node", "body")
fromlineno: Literal[0] = 0
"""The first line that this node appears on in the source code."""
@@ -479,10 +479,14 @@ def __init__(
"""A map of the name of a global variable to the node defining the global."""
self.locals = self.globals = {}
+ """A map of the name of a local variable to the node defining the local."""
self.body: Optional[List[node_classes.NodeNG]] = []
"""The contents of the module."""
+ self.doc_node: Optional[Const] = None
+ """The doc node associated with this node."""
+
self.future_imports: Set[str] = set()
"""The imports from ``__future__``."""
@@ -490,13 +494,15 @@ def __init__(
# pylint: enable=redefined-builtin
- def postinit(self, body=None):
+ def postinit(self, body=None, *, doc_node: Optional[Const] = None):
"""Do some setup after initialisation.
:param body: The contents of the module.
:type body: list(NodeNG) or None
+ :param doc_node: The doc node associated with this node.
"""
self.body = body
+ self.doc_node = doc_node
def _get_stream(self):
if self.file_bytes is not None:
@@ -1463,7 +1469,7 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
<FunctionDef.my_func l.2 at 0x7f23b2e71e10>
"""
- _astroid_fields = ("decorators", "args", "returns", "body")
+ _astroid_fields = ("decorators", "args", "returns", "doc_node", "body")
_multi_line_block_fields = ("body",)
returns = None
decorators: Optional[node_classes.Decorators] = None
@@ -1549,6 +1555,9 @@ def __init__(
:type doc: str or None
"""
+ self.doc_node: Optional[Const] = None
+ """The doc node associated with this node."""
+
self.instance_attrs = {}
super().__init__(
lineno=lineno,
@@ -1572,6 +1581,7 @@ def postinit(
type_comment_args=None,
*,
position: Optional[Position] = None,
+ doc_node: Optional[Const] = None,
):
"""Do some setup after initialisation.
@@ -1589,6 +1599,8 @@ def postinit(
The args type annotation passed via a type comment.
:params position:
Position of function keyword(s) and name.
+ :param doc_node:
+ The doc node associated with this node.
"""
self.args = args
self.body = body
@@ -1597,6 +1609,7 @@ def postinit(
self.type_comment_returns = type_comment_returns
self.type_comment_args = type_comment_args
self.position = position
+ self.doc_node = doc_node
@decorators_mod.cachedproperty
def extra_decorators(self) -> List[node_classes.Call]:
@@ -2098,6 +2111,7 @@ def get_wrapping_class(node):
return klass
+# pylint: disable=too-many-instance-attributes
class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement):
"""Class representing an :class:`ast.ClassDef` node.
@@ -2115,7 +2129,7 @@ def my_meth(self, arg):
# by a raw factories
# a dictionary of class instances attributes
- _astroid_fields = ("decorators", "bases", "keywords", "body") # name
+ _astroid_fields = ("decorators", "bases", "keywords", "doc_node", "body") # name
decorators = None
"""The decorators that are applied to this class.
@@ -2217,6 +2231,9 @@ def __init__(
:type doc: str or None
"""
+ self.doc_node: Optional[Const] = None
+ """The doc node associated with this node."""
+
self.is_dataclass: bool = False
"""Whether this class is a dataclass."""
@@ -2258,6 +2275,7 @@ def postinit(
keywords=None,
*,
position: Optional[Position] = None,
+ doc_node: Optional[Const] = None,
):
"""Do some setup after initialisation.
@@ -2280,6 +2298,8 @@ def postinit(
:type keywords: list(Keyword) or None
:param position: Position of class keyword and name.
+
+ :param doc_node: The doc node associated with this node.
"""
if keywords is not None:
self.keywords = keywords
@@ -2291,6 +2311,7 @@ def postinit(
if metaclass is not None:
self._metaclass = metaclass
self.position = position
+ self.doc_node = doc_node
def _newstyle_impl(self, context=None):
if context is None:
diff --git a/astroid/rebuilder.py b/astroid/rebuilder.py
index 7a025e8fac..141494ea72 100644
--- a/astroid/rebuilder.py
+++ b/astroid/rebuilder.py
@@ -33,6 +33,7 @@
import sys
import token
+import tokenize
from io import StringIO
from tokenize import TokenInfo, generate_tokens
from typing import (
@@ -42,6 +43,7 @@
Generator,
List,
Optional,
+ Set,
Tuple,
Type,
TypeVar,
@@ -52,7 +54,7 @@
from astroid import nodes
from astroid._ast import ParserModule, get_parser_module, parse_function_type_comment
-from astroid.const import PY36, PY38, PY38_PLUS, Context
+from astroid.const import IMPLEMENTATION_PYPY, PY36, PY38, PY38_PLUS, Context
from astroid.manager import AstroidManager
from astroid.nodes import NodeNG
from astroid.nodes.utils import Position
@@ -86,6 +88,7 @@
T_Function = TypeVar("T_Function", nodes.FunctionDef, nodes.AsyncFunctionDef)
T_For = TypeVar("T_For", nodes.For, nodes.AsyncFor)
T_With = TypeVar("T_With", nodes.With, nodes.AsyncWith)
+NodesWithDocsType = Union[nodes.Module, nodes.ClassDef, nodes.FunctionDef]
# noinspection PyMethodMayBeStatic
@@ -113,7 +116,10 @@ def __init__(
self._parser_module = parser_module
self._module = self._parser_module.module
- def _get_doc(self, node: T_Doc) -> Tuple[T_Doc, Optional[str]]:
+ def _get_doc(
+ self, node: T_Doc
+ ) -> Tuple[T_Doc, Optional["ast.Constant | ast.Str"], Optional[str]]:
+ """Return the doc ast node and the actual docstring."""
try:
if node.body and isinstance(node.body[0], self._module.Expr):
first_value = node.body[0].value
@@ -122,12 +128,17 @@ def _get_doc(self, node: T_Doc) -> Tuple[T_Doc, Optional[str]]:
and isinstance(first_value, self._module.Constant)
and isinstance(first_value.value, str)
):
+ doc_ast_node = first_value
doc = first_value.value if PY38_PLUS else first_value.s
node.body = node.body[1:]
- return node, doc
+ # The ast parser of python < 3.8 sets col_offset of multi-line strings to -1
+ # as it is unable to determine the value correctly. We reset this to None.
+ if doc_ast_node.col_offset == -1:
+ doc_ast_node.col_offset = None
+ return node, doc_ast_node, doc
except IndexError:
pass # ast built from scratch
- return node, None
+ return node, None, None
def _get_context(
self,
@@ -198,12 +209,68 @@ def _get_position_info(
# pylint: disable=undefined-loop-variable
return Position(
- lineno=node.lineno - 1 + start_token.start[0],
+ lineno=node.lineno + start_token.start[0] - 1,
col_offset=start_token.start[1],
- end_lineno=node.lineno - 1 + t.end[0],
+ end_lineno=node.lineno + t.end[0] - 1,
end_col_offset=t.end[1],
)
+ def _fix_doc_node_position(self, node: NodesWithDocsType) -> None:
+ """Fix start and end position of doc nodes for Python < 3.8."""
+ if not self._data or not node.doc_node or node.lineno is None:
+ return
+ if PY38_PLUS:
+ return
+
+ lineno = node.lineno or 1 # lineno of modules is 0
+ end_range: Optional[int] = node.doc_node.lineno
+ if IMPLEMENTATION_PYPY:
+ end_range = None
+ # pylint: disable-next=unsubscriptable-object
+ data = "\n".join(self._data[lineno - 1 : end_range])
+
+ found_start, found_end = False, False
+ open_brackets = 0
+ skip_token: Set[int] = {token.NEWLINE, token.INDENT}
+ if PY36:
+ skip_token.update((tokenize.NL, tokenize.COMMENT))
+ else:
+ # token.NL and token.COMMENT were added in 3.7
+ skip_token.update((token.NL, token.COMMENT))
+
+ if isinstance(node, nodes.Module):
+ found_end = True
+
+ for t in generate_tokens(StringIO(data).readline):
+ if found_end is False:
+ if (
+ found_start is False
+ and t.type == token.NAME
+ and t.string in {"def", "class"}
+ ):
+ found_start = True
+ elif found_start is True and t.type == token.OP:
+ if t.exact_type == token.COLON and open_brackets == 0:
+ found_end = True
+ elif t.exact_type == token.LPAR:
+ open_brackets += 1
+ elif t.exact_type == token.RPAR:
+ open_brackets -= 1
+ continue
+ if t.type in skip_token:
+ continue
+ if t.type == token.STRING:
+ break
+ return
+ else:
+ return
+
+ # pylint: disable=undefined-loop-variable
+ node.doc_node.lineno = lineno + t.start[0] - 1
+ node.doc_node.col_offset = t.start[1]
+ node.doc_node.end_lineno = lineno + t.end[0] - 1
+ node.doc_node.end_col_offset = t.end[1]
+
def visit_module(
self, node: "ast.Module", modname: str, modpath: str, package: bool
) -> nodes.Module:
@@ -211,7 +278,7 @@ def visit_module(
Note: Method not called by 'visit'
"""
- node, doc = self._get_doc(node)
+ node, doc_ast_node, doc = self._get_doc(node)
newnode = nodes.Module(
name=modname,
doc=doc,
@@ -220,7 +287,11 @@ def visit_module(
package=package,
parent=None,
)
- newnode.postinit([self.visit(child, newnode) for child in node.body])
+ newnode.postinit(
+ [self.visit(child, newnode) for child in node.body],
+ doc_node=self.visit(doc_ast_node, newnode),
+ )
+ self._fix_doc_node_position(newnode)
return newnode
if sys.version_info >= (3, 10):
@@ -1242,7 +1313,7 @@ def visit_classdef(
self, node: "ast.ClassDef", parent: NodeNG, newstyle: bool = True
) -> nodes.ClassDef:
"""visit a ClassDef node to become astroid"""
- node, doc = self._get_doc(node)
+ node, doc_ast_node, doc = self._get_doc(node)
if sys.version_info >= (3, 8):
newnode = nodes.ClassDef(
name=node.name,
@@ -1275,7 +1346,9 @@ def visit_classdef(
if kwd.arg != "metaclass"
],
position=self._get_position_info(node, newnode),
+ doc_node=self.visit(doc_ast_node, newnode),
)
+ self._fix_doc_node_position(newnode)
return newnode
def visit_continue(self, node: "ast.Continue", parent: NodeNG) -> nodes.Continue:
@@ -1580,7 +1653,7 @@ def _visit_functiondef(
) -> T_Function:
"""visit an FunctionDef node to become astroid"""
self._global_names.append({})
- node, doc = self._get_doc(node)
+ node, doc_ast_node, doc = self._get_doc(node)
lineno = node.lineno
if PY38_PLUS and node.decorator_list:
@@ -1624,7 +1697,9 @@ def _visit_functiondef(
type_comment_returns=type_comment_returns,
type_comment_args=type_comment_args,
position=self._get_position_info(node, newnode),
+ doc_node=self.visit(doc_ast_node, newnode),
)
+ self._fix_doc_node_position(newnode)
self._global_names.pop()
return newnode
|
Impossible to get correct line number for the docstrings
# Current behavior:
Removing the first `ast.Expr` from the tree to populate `.doc` property makes it impossible to get correct line number for the docstirng.
We ca start a module docstring at the line 3:
```
#!/usr/bin/env python3
"""module docstring"""
...
```
Maybe there is a workaround that I did find, but it looks like the constant node information is lost.
The core of the issue lies down in the `TreeRebuilder._get_doc()` method.
https://github.com/PyCQA/astroid/blob/82bf77d54393a52ecd07d50a791f5e1a63369f11/astroid/rebuilder.py#L122
# Expected behavior:
The expected behaviour, in my opinion is not to remove the `Expr` node from the container such that users can use correct line numbers and report docstring warnings with better accuracy.
Astroid version: 2.9.3
|
1276
|
pylint-dev/astroid
|
diff --git a/tests/unittest_nodes.py b/tests/unittest_nodes.py
index 1ac896fc02..a7735c5c6e 100644
--- a/tests/unittest_nodes.py
+++ b/tests/unittest_nodes.py
@@ -1596,23 +1596,32 @@ class SomeClass:
def test_get_doc() -> None:
- node = astroid.extract_node(
- """
+ code = textwrap.dedent(
+ """\
def func():
"Docstring"
return 1
"""
)
+ node: nodes.FunctionDef = astroid.extract_node(code) # type: ignore[assignment]
assert node.doc == "Docstring"
-
- node = astroid.extract_node(
- """
+ assert isinstance(node.doc_node, nodes.Const)
+ assert node.doc_node.value == "Docstring"
+ assert node.doc_node.lineno == 2
+ assert node.doc_node.col_offset == 4
+ assert node.doc_node.end_lineno == 2
+ assert node.doc_node.end_col_offset == 15
+
+ code = textwrap.dedent(
+ """\
def func():
...
return 1
"""
)
+ node = astroid.extract_node(code)
assert node.doc is None
+ assert node.doc_node is None
@test_utils.require_version(minver="3.8")
diff --git a/tests/unittest_scoped_nodes.py b/tests/unittest_scoped_nodes.py
index 9a156781dc..6a95385cec 100644
--- a/tests/unittest_scoped_nodes.py
+++ b/tests/unittest_scoped_nodes.py
@@ -295,6 +295,69 @@ def test_stream_api(self) -> None:
with open(path, "rb") as file_io:
self.assertEqual(stream.read(), file_io.read())
+ @staticmethod
+ def test_singleline_docstring() -> None:
+ data = textwrap.dedent(
+ """\
+ '''Hello World'''
+ foo = 1
+ """
+ )
+ module = builder.parse(data, __name__)
+ assert isinstance(module.doc_node, nodes.Const)
+ assert module.doc_node.lineno == 1
+ assert module.doc_node.col_offset == 0
+ assert module.doc_node.end_lineno == 1
+ assert module.doc_node.end_col_offset == 17
+
+ @staticmethod
+ def test_multiline_docstring() -> None:
+ data = textwrap.dedent(
+ """\
+ '''Hello World
+
+ Also on this line.
+ '''
+ foo = 1
+ """
+ )
+ module = builder.parse(data, __name__)
+
+ assert isinstance(module.doc_node, nodes.Const)
+ assert module.doc_node.lineno == 1
+ assert module.doc_node.col_offset == 0
+ assert module.doc_node.end_lineno == 4
+ assert module.doc_node.end_col_offset == 3
+
+ @staticmethod
+ def test_comment_before_docstring() -> None:
+ data = textwrap.dedent(
+ """\
+ # Some comment
+ '''This is
+
+ a multiline docstring.
+ '''
+ """
+ )
+ module = builder.parse(data, __name__)
+
+ assert isinstance(module.doc_node, nodes.Const)
+ assert module.doc_node.lineno == 2
+ assert module.doc_node.col_offset == 0
+ assert module.doc_node.end_lineno == 5
+ assert module.doc_node.end_col_offset == 3
+
+ @staticmethod
+ def test_without_docstring() -> None:
+ data = textwrap.dedent(
+ """\
+ foo = 1
+ """
+ )
+ module = builder.parse(data, __name__)
+ assert module.doc_node is None
+
class FunctionNodeTest(ModuleLoader, unittest.TestCase):
def test_special_attributes(self) -> None:
@@ -752,6 +815,118 @@ def test(cls):
self.assertIsInstance(inferred, nodes.ClassDef)
self.assertEqual(inferred.name, "MyClass")
+ @staticmethod
+ def test_singleline_docstring() -> None:
+ code = textwrap.dedent(
+ """\
+ def foo():
+ '''Hello World'''
+ bar = 1
+ """
+ )
+ func: nodes.FunctionDef = builder.extract_node(code) # type: ignore[assignment]
+
+ assert isinstance(func.doc_node, nodes.Const)
+ assert func.doc_node.lineno == 2
+ assert func.doc_node.col_offset == 4
+ assert func.doc_node.end_lineno == 2
+ assert func.doc_node.end_col_offset == 21
+
+ @staticmethod
+ def test_multiline_docstring() -> None:
+ code = textwrap.dedent(
+ """\
+ def foo():
+ '''Hello World
+
+ Also on this line.
+ '''
+ bar = 1
+ """
+ )
+ func: nodes.FunctionDef = builder.extract_node(code) # type: ignore[assignment]
+
+ assert isinstance(func.doc_node, nodes.Const)
+ assert func.doc_node.lineno == 2
+ assert func.doc_node.col_offset == 4
+ assert func.doc_node.end_lineno == 5
+ assert func.doc_node.end_col_offset == 7
+
+ @staticmethod
+ def test_multiline_docstring_async() -> None:
+ code = textwrap.dedent(
+ """\
+ async def foo(var: tuple = ()):
+ '''Hello
+
+ World
+ '''
+ """
+ )
+ func: nodes.FunctionDef = builder.extract_node(code) # type: ignore[assignment]
+
+ assert isinstance(func.doc_node, nodes.Const)
+ assert func.doc_node.lineno == 2
+ assert func.doc_node.col_offset == 4
+ assert func.doc_node.end_lineno == 5
+ assert func.doc_node.end_col_offset == 7
+
+ @staticmethod
+ def test_docstring_special_cases() -> None:
+ code = textwrap.dedent(
+ """\
+ def f1(var: tuple = ()): #@
+ 'Hello World'
+
+ def f2() -> "just some comment with an open bracket(": #@
+ 'Hello World'
+
+ def f3() -> "Another comment with a colon: ": #@
+ 'Hello World'
+
+ def f4(): #@
+ # It should work with comments too
+ 'Hello World'
+ """
+ )
+ ast_nodes: List[nodes.FunctionDef] = builder.extract_node(code) # type: ignore[assignment]
+ assert len(ast_nodes) == 4
+
+ assert isinstance(ast_nodes[0].doc_node, nodes.Const)
+ assert ast_nodes[0].doc_node.lineno == 2
+ assert ast_nodes[0].doc_node.col_offset == 4
+ assert ast_nodes[0].doc_node.end_lineno == 2
+ assert ast_nodes[0].doc_node.end_col_offset == 17
+
+ assert isinstance(ast_nodes[1].doc_node, nodes.Const)
+ assert ast_nodes[1].doc_node.lineno == 5
+ assert ast_nodes[1].doc_node.col_offset == 4
+ assert ast_nodes[1].doc_node.end_lineno == 5
+ assert ast_nodes[1].doc_node.end_col_offset == 17
+
+ assert isinstance(ast_nodes[2].doc_node, nodes.Const)
+ assert ast_nodes[2].doc_node.lineno == 8
+ assert ast_nodes[2].doc_node.col_offset == 4
+ assert ast_nodes[2].doc_node.end_lineno == 8
+ assert ast_nodes[2].doc_node.end_col_offset == 17
+
+ assert isinstance(ast_nodes[3].doc_node, nodes.Const)
+ assert ast_nodes[3].doc_node.lineno == 12
+ assert ast_nodes[3].doc_node.col_offset == 4
+ assert ast_nodes[3].doc_node.end_lineno == 12
+ assert ast_nodes[3].doc_node.end_col_offset == 17
+
+ @staticmethod
+ def test_without_docstring() -> None:
+ code = textwrap.dedent(
+ """\
+ def foo():
+ bar = 1
+ """
+ )
+ func: nodes.FunctionDef = builder.extract_node(code) # type: ignore[assignment]
+ assert func.doc_node is None
+
class ClassNodeTest(ModuleLoader, unittest.TestCase):
def test_dict_interface(self) -> None:
@@ -2088,6 +2263,52 @@ def update(self):
# Should not crash
builder.parse(data)
+ @staticmethod
+ def test_singleline_docstring() -> None:
+ code = textwrap.dedent(
+ """\
+ class Foo:
+ '''Hello World'''
+ bar = 1
+ """
+ )
+ node: nodes.ClassDef = builder.extract_node(code) # type: ignore[assignment]
+ assert isinstance(node.doc_node, nodes.Const)
+ assert node.doc_node.lineno == 2
+ assert node.doc_node.col_offset == 4
+ assert node.doc_node.end_lineno == 2
+ assert node.doc_node.end_col_offset == 21
+
+ @staticmethod
+ def test_multiline_docstring() -> None:
+ code = textwrap.dedent(
+ """\
+ class Foo:
+ '''Hello World
+
+ Also on this line.
+ '''
+ bar = 1
+ """
+ )
+ node: nodes.ClassDef = builder.extract_node(code) # type: ignore[assignment]
+ assert isinstance(node.doc_node, nodes.Const)
+ assert node.doc_node.lineno == 2
+ assert node.doc_node.col_offset == 4
+ assert node.doc_node.end_lineno == 5
+ assert node.doc_node.end_col_offset == 7
+
+ @staticmethod
+ def test_without_docstring() -> None:
+ code = textwrap.dedent(
+ """\
+ class Foo:
+ bar = 1
+ """
+ )
+ node: nodes.ClassDef = builder.extract_node(code) # type: ignore[assignment]
+ assert node.doc_node is None
+
def test_issue940_metaclass_subclass_property() -> None:
node = builder.extract_node(
|
none
|
[
"tests/unittest_nodes.py::test_get_doc",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_comment_before_docstring",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_multiline_docstring",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_singleline_docstring",
"tests/unittest_scoped_nodes.py::ModuleNodeTest::test_without_docstring",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_docstring_special_cases",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_multiline_docstring",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_multiline_docstring_async",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_singleline_docstring",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_without_docstring",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_multiline_docstring",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_singleline_docstring",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_without_docstring"
] |
[
"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_as_string_unknown",
"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_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",
"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_abstract_methods_are_not_implicitly_none",
"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_no_returns_is_implicitly_none",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_only_raises_is_not_implicitly_none",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_positional_only_argnames",
"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_typing_extensions",
"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_scoped_nodes.py::test_slots_duplicate_bases_issue_1089",
"tests/unittest_scoped_nodes.py::TestFrameNodes::test_frame_node",
"tests/unittest_scoped_nodes.py::TestFrameNodes::test_non_frame_node"
] |
[
"pytest -rA tests/"
] |
pytest
|
{
"files": 4,
"hunks": 31,
"lines": 130
}
|
|
Thanks! Going to add `KeyError` to the caught exceptions.
Btw, this does sound like we could base a `pylint` checker on this? If `str.format()` returns `Uninferable` it's likely that something is wrong?
I don't think so, because this example from the pylint primer is fine, right? It's unpacking something dynamic, but I assume there's a justification for depending on team_slug being in there.
|
aa5a0d92e640ee5f3fa9a8ba3ba058a7b594ca44
|
[
"https://github.com/pylint-dev/astroid/commit/3876869109a10198d39317d931b48deddd7dc497"
] | 2022-06-11T10:33:20
|
pylint-dev__astroid-1614
|
[
"1613"
] |
python
|
diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py
index 68445e731c..00253f243b 100644
--- a/astroid/brain/brain_builtin_inference.py
+++ b/astroid/brain/brain_builtin_inference.py
@@ -946,7 +946,7 @@ def _infer_str_format_call(
try:
formatted_string = format_template.format(*pos_values, **keyword_values)
- except IndexError:
+ except (IndexError, KeyError):
# If there is an IndexError there are too few arguments to interpolate
return iter([util.Uninferable])
|
Crash when inferring `str.format` call involving unpacking kwargs
When parsing the following file:
<!--
If sharing the code is not an option, please state so,
but providing only the stacktrace would still be helpful.
-->
```python
class A:
def render(self, audit_log_entry: AuditLogEntry):
return "joined team {team_slug}".format(**audit_log_entry.data)
```
pylint crashed with a ``AstroidError`` and with the following stacktrace:
```
Traceback (most recent call last):
File "/Users/.../astroid/astroid/inference_tip.py", line 38, in _inference_tip_cached
result = _cache[func, node]
KeyError: (<function _infer_str_format_call at 0x1064a96c0>, <Call l.3 at 0x106c452d0>)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/.../pylint/pylint/lint/pylinter.py", line 731, in _check_file
check_astroid_module(ast_node)
File "/Users/.../pylint/pylint/lint/pylinter.py", line 950, in check_astroid_module
retval = self._check_astroid_module(
File "/Users/.../pylint/pylint/lint/pylinter.py", line 1000, in _check_astroid_module
walker.walk(node)
File "/Users/.../pylint/pylint/utils/ast_walker.py", line 93, in walk
self.walk(child)
File "/Users/.../pylint/pylint/utils/ast_walker.py", line 93, in walk
self.walk(child)
File "/Users/.../pylint/pylint/utils/ast_walker.py", line 90, in walk
callback(astroid)
File "/Users/.../pylint/pylint/checkers/classes/special_methods_checker.py", line 170, in visit_functiondef
inferred = _safe_infer_call_result(node, node)
File "/Users/.../pylint/pylint/checkers/classes/special_methods_checker.py", line 31, in _safe_infer_call_result
value = next(inferit)
File "/Users/.../astroid/astroid/nodes/scoped_nodes/scoped_nodes.py", line 1752, in infer_call_result
yield from returnnode.value.infer(context)
File "/Users/.../astroid/astroid/nodes/node_ng.py", line 159, in infer
results = list(self._explicit_inference(self, context, **kwargs))
File "/Users/.../astroid/astroid/inference_tip.py", line 45, in _inference_tip_cached
result = _cache[func, node] = list(func(*args, **kwargs))
File "/Users/.../astroid/astroid/brain/brain_builtin_inference.py", line 948, in _infer_str_format_call
formatted_string = format_template.format(*pos_values, **keyword_values)
KeyError: 'team_slug'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/.../pylint/pylint/lint/pylinter.py", line 688, in _check_files
self._check_file(get_ast, check_astroid_module, file)
File "/Users/.../pylint/pylint/lint/pylinter.py", line 733, in _check_file
raise astroid.AstroidError from e
astroid.exceptions.AstroidError
```
***
cc @DanielNoord in #1602
found by pylint primer 🚀
|
1614
|
pylint-dev/astroid
|
diff --git a/tests/unittest_brain_builtin.py b/tests/unittest_brain_builtin.py
index a659c4fdf2..54e7d2190d 100644
--- a/tests/unittest_brain_builtin.py
+++ b/tests/unittest_brain_builtin.py
@@ -93,6 +93,9 @@ def test_string_format(self, format_string: str) -> None:
"My name is {}, I'm {}".format(Unknown, 12)
""",
""""I am {}".format()""",
+ """
+ "My name is {fname}, I'm {age}".format(fsname = "Daniel", age = 12)
+ """,
],
)
def test_string_format_uninferable(self, format_string: str) -> None:
|
none
|
[
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_uninferable[\\n"
] |
[
"tests/unittest_brain_builtin.py::BuiltinsTest::test_infer_property",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[empty-indexes]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[numbered-indexes]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[named-indexes]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[numbered-indexes-from-positional]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[named-indexes-from-keyword]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[mixed-indexes-from-mixed]",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_uninferable[\"I",
"tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_with_specs"
] |
[
"pytest -rA tests/"
] |
pytest
|
{
"files": 1,
"hunks": 1,
"lines": 2
}
|
|
@cdce8p Just thinking out loud: can we also use a type guard to define `cached_property`? Would `mypy` pick up on that?
> @cdce8p Just thinking out loud: can we also use a type guard to define `cached_property`? Would `mypy` pick up on that?
Not completely sure what you want to do with that.
On other thing, I just saw that we don't set the `python-version` for mypy. If we do that, we probably need to do some more workarounds to tell mypy `cachedproperty` is equal to `cached_property`. Adding `TYPE_CHECKING` could work
```py
if sys.version_info >= (3, 8) or TYPE_CHECKING:
from functools import cached_property
else:
from astroid.decorators import cachedproperty as cached_property
```
|
da745538c7236028a22cdf0405f6829fcf6886bc
|
[
"https://github.com/pylint-dev/astroid/commit/43e3dde23b5a8a985d7a4fe54c33c835768cee9c",
"https://github.com/pylint-dev/astroid/commit/d0167fd7b1c7da8a8160f301fe90d5e91a66178e",
"https://github.com/pylint-dev/astroid/commit/7c4c4951de3f188dcf2a0e677a1f65ae77aa0e50",
"https://github.com/pylint-dev/astroid/commit/4c470f06a8877cfa561db5f3235af2e72c98d567",
"https://github.com/pylint-dev/astroid/commit/94446255066690f402bccb02a14ae53065d55c58",
"https://github.com/pylint-dev/astroid/commit/2c16141b1279d3edbfe89a4db798bdf21012d7ec",
"https://github.com/pylint-dev/astroid/commit/f40b99fdae92bc5f0204a0e214486a5735657905",
"https://github.com/pylint-dev/astroid/commit/603d5b9ec701ceeab1bcc25a2fc0813706401a78"
] | 2022-03-01T18:24:29
|
@cdce8p Just thinking out loud: can we also use a type guard to define `cached_property`? Would `mypy` pick up on that?
> @cdce8p Just thinking out loud: can we also use a type guard to define `cached_property`? Would `mypy` pick up on that?
Not completely sure what you want to do with that.
On other thing, I just saw that we don't set the `python-version` for mypy. If we do that, we probably need to do some more workarounds to tell mypy `cachedproperty` is equal to `cached_property`. Adding `TYPE_CHECKING` could work
```py
if sys.version_info >= (3, 8) or TYPE_CHECKING:
from functools import cached_property
else:
from astroid.decorators import cachedproperty as cached_property
```
|
pylint-dev__astroid-1417
|
[
"1410"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index e5be140ade..ec61695daf 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -9,6 +9,11 @@ Release date: TBA
* Add new (optional) ``doc_node`` attribute to ``nodes.Module``, ``nodes.ClassDef``,
and ``nodes.FunctionDef``.
+* Replace custom ``cachedproperty`` with ``functools.cached_property`` and deprecate it
+ for Python 3.8+.
+
+ Closes #1410
+
What's New in astroid 2.10.1?
=============================
diff --git a/astroid/decorators.py b/astroid/decorators.py
index aff91e0c89..ef2e102a83 100644
--- a/astroid/decorators.py
+++ b/astroid/decorators.py
@@ -52,6 +52,8 @@ def cached(func, instance, args, kwargs):
return result
+# TODO: Remove when support for 3.7 is dropped
+# TODO: astroid 3.0 -> move class behind sys.version_info < (3, 8) guard
class cachedproperty:
"""Provides a cached property equivalent to the stacking of
@cached and @property, but more efficient.
@@ -70,6 +72,12 @@ class cachedproperty:
__slots__ = ("wrapped",)
def __init__(self, wrapped):
+ if sys.version_info >= (3, 8):
+ warnings.warn(
+ "cachedproperty has been deprecated and will be removed in astroid 3.0 for Python 3.8+. "
+ "Use functools.cached_property instead.",
+ DeprecationWarning,
+ )
try:
wrapped.__name__
except AttributeError as exc:
diff --git a/astroid/mixins.py b/astroid/mixins.py
index deefd59726..91c628f202 100644
--- a/astroid/mixins.py
+++ b/astroid/mixins.py
@@ -18,6 +18,7 @@
"""This module contains some mixins for the different nodes.
"""
import itertools
+import sys
from typing import TYPE_CHECKING, Optional
from astroid import decorators
@@ -26,11 +27,16 @@
if TYPE_CHECKING:
from astroid import nodes
+if sys.version_info >= (3, 8) or TYPE_CHECKING:
+ from functools import cached_property
+else:
+ from astroid.decorators import cachedproperty as cached_property
+
class BlockRangeMixIn:
"""override block range"""
- @decorators.cachedproperty
+ @cached_property
def blockstart_tolineno(self):
return self.lineno
@@ -135,7 +141,7 @@ class MultiLineBlockMixin:
Assign nodes, etc.
"""
- @decorators.cachedproperty
+ @cached_property
def _multi_line_blocks(self):
return tuple(getattr(self, field) for field in self._multi_line_block_fields)
diff --git a/astroid/nodes/node_classes.py b/astroid/nodes/node_classes.py
index a8d4c1e1b0..6214e42f37 100644
--- a/astroid/nodes/node_classes.py
+++ b/astroid/nodes/node_classes.py
@@ -80,6 +80,12 @@
from astroid import nodes
from astroid.nodes import LocalsDictNodeNG
+if sys.version_info >= (3, 8) or TYPE_CHECKING:
+ # pylint: disable-next=ungrouped-imports
+ from functools import cached_property
+else:
+ from astroid.decorators import cachedproperty as cached_property
+
def _is_const(value):
return isinstance(value, tuple(CONST_CLS))
@@ -824,7 +830,7 @@ def _infer_name(self, frame, name):
return name
return None
- @decorators.cachedproperty
+ @cached_property
def fromlineno(self):
"""The first line that this node appears on in the source code.
@@ -833,7 +839,7 @@ def fromlineno(self):
lineno = super().fromlineno
return max(lineno, self.parent.fromlineno or 0)
- @decorators.cachedproperty
+ @cached_property
def arguments(self):
"""Get all the arguments for this node, including positional only and positional and keyword"""
return list(itertools.chain((self.posonlyargs or ()), self.args or ()))
@@ -2601,7 +2607,7 @@ def postinit(
if body is not None:
self.body = body
- @decorators.cachedproperty
+ @cached_property
def blockstart_tolineno(self):
"""The line on which the beginning of this block ends.
@@ -2734,7 +2740,7 @@ def postinit(
See astroid/protocols.py for actual implementation.
"""
- @decorators.cachedproperty
+ @cached_property
def blockstart_tolineno(self):
"""The line on which the beginning of this block ends.
@@ -3093,7 +3099,7 @@ def postinit(
if isinstance(self.parent, If) and self in self.parent.orelse:
self.is_orelse = True
- @decorators.cachedproperty
+ @cached_property
def blockstart_tolineno(self):
"""The line on which the beginning of this block ends.
@@ -3762,7 +3768,7 @@ def _wrap_attribute(self, attr):
return const
return attr
- @decorators.cachedproperty
+ @cached_property
def _proxied(self):
builtins = AstroidManager().builtins_module
return builtins.getattr("slice")[0]
@@ -4384,7 +4390,7 @@ def postinit(
if orelse is not None:
self.orelse = orelse
- @decorators.cachedproperty
+ @cached_property
def blockstart_tolineno(self):
"""The line on which the beginning of this block ends.
@@ -4500,7 +4506,7 @@ def postinit(
See astroid/protocols.py for actual implementation.
"""
- @decorators.cachedproperty
+ @cached_property
def blockstart_tolineno(self):
"""The line on which the beginning of this block ends.
diff --git a/astroid/nodes/node_ng.py b/astroid/nodes/node_ng.py
index 73d12a37f7..290a029403 100644
--- a/astroid/nodes/node_ng.py
+++ b/astroid/nodes/node_ng.py
@@ -38,6 +38,12 @@
else:
from typing_extensions import Literal
+if sys.version_info >= (3, 8) or TYPE_CHECKING:
+ # pylint: disable-next=ungrouped-imports
+ from functools import cached_property
+else:
+ # pylint: disable-next=ungrouped-imports
+ from astroid.decorators import cachedproperty as cached_property
# Types for 'NodeNG.nodes_of_class()'
T_Nodes = TypeVar("T_Nodes", bound="NodeNG")
@@ -435,14 +441,14 @@ def previous_sibling(self):
# these are lazy because they're relatively expensive to compute for every
# single node, and they rarely get looked at
- @decorators.cachedproperty
+ @cached_property
def fromlineno(self) -> Optional[int]:
"""The first line that this node appears on in the source code."""
if self.lineno is None:
return self._fixed_source_line()
return self.lineno
- @decorators.cachedproperty
+ @cached_property
def tolineno(self) -> Optional[int]:
"""The last line that this node appears on in the source code."""
if self.end_lineno is not None:
diff --git a/astroid/nodes/scoped_nodes/scoped_nodes.py b/astroid/nodes/scoped_nodes/scoped_nodes.py
index a8dcf3549f..cdaf8c3928 100644
--- a/astroid/nodes/scoped_nodes/scoped_nodes.py
+++ b/astroid/nodes/scoped_nodes/scoped_nodes.py
@@ -52,7 +52,7 @@
import sys
import typing
import warnings
-from typing import Dict, List, Optional, Set, TypeVar, Union, overload
+from typing import TYPE_CHECKING, Dict, List, Optional, Set, TypeVar, Union, overload
from astroid import bases
from astroid import decorators as decorators_mod
@@ -93,6 +93,12 @@
else:
from typing_extensions import Literal
+if sys.version_info >= (3, 8) or TYPE_CHECKING:
+ from functools import cached_property
+else:
+ # pylint: disable-next=ungrouped-imports
+ from astroid.decorators import cachedproperty as cached_property
+
ITER_METHODS = ("__iter__", "__getitem__")
EXCEPTION_BASE_CLASSES = frozenset({"Exception", "BaseException"})
@@ -1611,7 +1617,7 @@ def postinit(
self.position = position
self.doc_node = doc_node
- @decorators_mod.cachedproperty
+ @cached_property
def extra_decorators(self) -> List[node_classes.Call]:
"""The extra decorators that this function can have.
@@ -1652,7 +1658,7 @@ def extra_decorators(self) -> List[node_classes.Call]:
decorators.append(assign.value)
return decorators
- @decorators_mod.cachedproperty
+ @cached_property
def type(
self,
): # pylint: disable=invalid-overridden-method,too-many-return-statements
@@ -1726,7 +1732,7 @@ def type(
pass
return type_name
- @decorators_mod.cachedproperty
+ @cached_property
def fromlineno(self) -> Optional[int]:
"""The first line that this node appears on in the source code."""
# lineno is the line number of the first decorator, we want the def
@@ -1739,7 +1745,7 @@ def fromlineno(self) -> Optional[int]:
return lineno
- @decorators_mod.cachedproperty
+ @cached_property
def blockstart_tolineno(self):
"""The line on which the beginning of this block ends.
@@ -2337,7 +2343,7 @@ def _newstyle_impl(self, context=None):
doc=("Whether this is a new style class or not\n\n" ":type: bool or None"),
)
- @decorators_mod.cachedproperty
+ @cached_property
def fromlineno(self) -> Optional[int]:
"""The first line that this node appears on in the source code."""
if not PY38_PLUS:
@@ -2352,7 +2358,7 @@ def fromlineno(self) -> Optional[int]:
return lineno
return super().fromlineno
- @decorators_mod.cachedproperty
+ @cached_property
def blockstart_tolineno(self):
"""The line on which the beginning of this block ends.
diff --git a/astroid/objects.py b/astroid/objects.py
index 76ade71deb..56fbcd7a2d 100644
--- a/astroid/objects.py
+++ b/astroid/objects.py
@@ -22,8 +22,10 @@
Call(func=Name('frozenset'), args=Tuple(...))
"""
+import sys
+from typing import TYPE_CHECKING
-from astroid import bases, decorators, util
+from astroid import bases, util
from astroid.exceptions import (
AttributeInferenceError,
InferenceError,
@@ -35,6 +37,11 @@
objectmodel = util.lazy_import("interpreter.objectmodel")
+if sys.version_info >= (3, 8) or TYPE_CHECKING:
+ from functools import cached_property
+else:
+ from astroid.decorators import cachedproperty as cached_property
+
class FrozenSet(node_classes.BaseContainer):
"""class representing a FrozenSet composite node"""
@@ -45,7 +52,7 @@ def pytype(self):
def _infer(self, context=None):
yield self
- @decorators.cachedproperty
+ @cached_property
def _proxied(self): # pylint: disable=method-hidden
ast_builtins = AstroidManager().builtins_module
return ast_builtins.getattr("frozenset")[0]
@@ -114,7 +121,7 @@ def super_mro(self):
index = mro.index(self.mro_pointer)
return mro[index + 1 :]
- @decorators.cachedproperty
+ @cached_property
def _proxied(self):
ast_builtins = AstroidManager().builtins_module
return ast_builtins.getattr("super")[0]
@@ -218,7 +225,7 @@ class ExceptionInstance(bases.Instance):
the case of .args.
"""
- @decorators.cachedproperty
+ @cached_property
def special_attributes(self):
qname = self.qname()
instance = objectmodel.BUILTIN_EXCEPTIONS.get(
|
Replace `cachedproperty` with `functools.cached_property` (>= 3.8)
I thought about this PR recently again. Typing `cachedproperty` might not work, but it can be replaced with `functools.cached_property`. We only need to `sys` guard it for `< 3.8`. This should work
```py
if sys.version_info >= (3, 8):
from functools import cached_property
else:
from astroid.decorators import cachedproperty as cached_property
```
Additionally, the deprecation warning can be limited to `>= 3.8`.
_Originally posted by @cdce8p in https://github.com/PyCQA/astroid/issues/1243#issuecomment-1052834322_
|
1417
|
pylint-dev/astroid
|
diff --git a/tests/unittest_decorators.py b/tests/unittest_decorators.py
index 4672f870a6..0700f570de 100644
--- a/tests/unittest_decorators.py
+++ b/tests/unittest_decorators.py
@@ -1,7 +1,8 @@
import pytest
from _pytest.recwarn import WarningsRecorder
-from astroid.decorators import deprecate_default_argument_values
+from astroid.const import PY38_PLUS
+from astroid.decorators import cachedproperty, deprecate_default_argument_values
class SomeClass:
@@ -97,3 +98,18 @@ def test_deprecated_default_argument_values_ok(recwarn: WarningsRecorder) -> Non
instance = SomeClass(name="some_name")
instance.func(name="", var=42)
assert len(recwarn) == 0
+
+
+@pytest.mark.skipif(not PY38_PLUS, reason="Requires Python 3.8 or higher")
+def test_deprecation_warning_on_cachedproperty() -> None:
+ """Check the DeprecationWarning on cachedproperty."""
+
+ with pytest.warns(DeprecationWarning) as records:
+
+ class MyClass: # pylint: disable=unused-variable
+ @cachedproperty
+ def my_property(self):
+ return 1
+
+ assert len(records) == 1
+ assert "functools.cached_property" in records[0].message.args[0]
|
none
|
[
"tests/unittest_decorators.py::test_deprecation_warning_on_cachedproperty"
] |
[
"tests/unittest_decorators.py::TestDeprecationDecorators::test_deprecated_default_argument_values_one_arg",
"tests/unittest_decorators.py::TestDeprecationDecorators::test_deprecated_default_argument_values_two_args",
"tests/unittest_decorators.py::TestDeprecationDecorators::test_deprecated_default_argument_values_ok"
] |
[
". venv/bin/activate && pytest -rA tests/"
] |
pytest
|
{
"files": 7,
"hunks": 30,
"lines": 90
}
|
abf9d0e4e63d1098436602804548d07a0909ece1
|
[
"https://github.com/pylint-dev/astroid/commit/7d044a4fa2c1ae509164d0e318136089be36aabf",
"https://github.com/pylint-dev/astroid/commit/225039dd8e4036afeb7db7e918e6f82d121bcfd4",
"https://github.com/pylint-dev/astroid/commit/f9c2900c4e2d4c0b0032ea8c42878afcaa2c19e6",
"https://github.com/pylint-dev/astroid/commit/af7170532077c241b24109cd74bb8fc2cc98564f",
"https://github.com/pylint-dev/astroid/commit/d5870a1bbef5c9f40a5eab2a7c66e71ac61c54e2",
"https://github.com/pylint-dev/astroid/commit/e408020eebc84462333a1fa8b5672e31315163bf",
"https://github.com/pylint-dev/astroid/commit/42e62497633c8b9ebd06eeb4a1fcdc35b21e1c2d"
] | 2021-01-24T11:26:24
|
pylint-dev__astroid-885
|
[
"855"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index 02852c6978..9ff42a6e77 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -2,14 +2,18 @@
astroid's ChangeLog
===================
+What's New in astroid 2.5.0?
+============================
+Release Date: TBA
+
+* Enrich the ``brain_collection`` module so that ``__class_getitem__`` method is added to `deque` for
+ ``python`` version above 3.9.
+
* The ``context.path`` is now a ``dict`` and the ``context.push`` method
returns ``True`` if the node has been visited a certain amount of times.
Close #669
-What's New in astroid 2.5.0?
-============================
-Release Date: TBA
* Adds a brain for type object so that it is possible to write `type[int]` in annotation.
Fixes PyCQA/pylint#4001
diff --git a/astroid/brain/brain_collections.py b/astroid/brain/brain_collections.py
index 6594e0c7ac..229969c5b0 100644
--- a/astroid/brain/brain_collections.py
+++ b/astroid/brain/brain_collections.py
@@ -4,6 +4,7 @@
# Copyright (c) 2017 Derek Gustafson <degustaf@gmail.com>
# Copyright (c) 2018 Ioana Tagirta <ioana.tagirta@gmail.com>
# Copyright (c) 2019 Hugo van Kemenade <hugovk@users.noreply.github.com>
+# Copyright (c) 2021 Julien Palard <julien@palard.fr>
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER
@@ -12,6 +13,9 @@
import astroid
+PY39 = sys.version_info >= (3, 9)
+
+
def _collections_transform():
return astroid.parse(
"""
@@ -61,6 +65,10 @@ def __iadd__(self, other): pass
def __mul__(self, other): pass
def __imul__(self, other): pass
def __rmul__(self, other): pass"""
+ if PY39:
+ base_deque_class += """
+ @classmethod
+ def __class_getitem__(self, item): pass"""
return base_deque_class
|
deque misses __class_getitem__
In `brain_collections.py`, deque misses its `__class_getitem__`, implemented in Python 3.9.
Should it be added with a test version, so astroid "knows" that it's not present in Python 3.8 but is in Python 3.9?
Related to: https://github.com/PyCQA/pylint/issues/3951
|
885
|
pylint-dev/astroid
|
diff --git a/tests/unittest_brain.py b/tests/unittest_brain.py
index e6ff69289a..1c004a06cf 100644
--- a/tests/unittest_brain.py
+++ b/tests/unittest_brain.py
@@ -141,6 +141,17 @@ def test_deque_py35methods(self):
self.assertIn("insert", inferred.locals)
self.assertIn("index", inferred.locals)
+ @test_utils.require_version(maxver="3.8")
+ def test_deque_not_py39methods(self):
+ inferred = self._inferred_queue_instance()
+ with self.assertRaises(astroid.exceptions.AttributeInferenceError):
+ inferred.getattr("__class_getitem__")
+
+ @test_utils.require_version(minver="3.9")
+ def test_deque_py39methods(self):
+ inferred = self._inferred_queue_instance()
+ self.assertTrue(inferred.getattr("__class_getitem__"))
+
class OrderedDictTest(unittest.TestCase):
def _inferred_ordered_dict_instance(self):
|
none
|
[
"tests/unittest_brain.py::CollectionsDequeTests::test_deque_py39methods"
] |
[
"tests/unittest_brain.py::HashlibTest::test_hashlib",
"tests/unittest_brain.py::HashlibTest::test_hashlib_py36",
"tests/unittest_brain.py::CollectionsDequeTests::test_deque",
"tests/unittest_brain.py::CollectionsDequeTests::test_deque_py35methods",
"tests/unittest_brain.py::OrderedDictTest::test_ordered_dict_py34method",
"tests/unittest_brain.py::NamedTupleTest::test_invalid_label_does_not_crash_inference",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_access_class_fields",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_advanced_inference",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_base",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_bases_are_actually_names_not_nodes",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_func_form",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_func_form_args_and_kwargs",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_inference",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_inference_failure",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_instance_attrs",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_rename_duplicates",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_rename_keywords",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_rename_uninferable",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_uninferable_fields",
"tests/unittest_brain.py::DefaultDictTest::test_1",
"tests/unittest_brain.py::ModuleExtenderTest::testExtensionModules",
"tests/unittest_brain.py::SixBrainTest::test_attribute_access",
"tests/unittest_brain.py::SixBrainTest::test_from_imports",
"tests/unittest_brain.py::SixBrainTest::test_from_submodule_imports",
"tests/unittest_brain.py::MultiprocessingBrainTest::test_module_name",
"tests/unittest_brain.py::MultiprocessingBrainTest::test_multiprocessing_manager",
"tests/unittest_brain.py::MultiprocessingBrainTest::test_multiprocessing_module_attributes",
"tests/unittest_brain.py::ThreadingBrainTest::test_boundedsemaphore",
"tests/unittest_brain.py::ThreadingBrainTest::test_lock",
"tests/unittest_brain.py::ThreadingBrainTest::test_rlock",
"tests/unittest_brain.py::ThreadingBrainTest::test_semaphore",
"tests/unittest_brain.py::EnumBrainTest::test_dont_crash_on_for_loops_in_body",
"tests/unittest_brain.py::EnumBrainTest::test_enum_func_form_has_dunder_members",
"tests/unittest_brain.py::EnumBrainTest::test_enum_func_form_is_class_not_instance",
"tests/unittest_brain.py::EnumBrainTest::test_enum_func_form_iterable",
"tests/unittest_brain.py::EnumBrainTest::test_enum_func_form_subscriptable",
"tests/unittest_brain.py::EnumBrainTest::test_enum_multiple_base_classes",
"tests/unittest_brain.py::EnumBrainTest::test_enum_starred_is_skipped",
"tests/unittest_brain.py::EnumBrainTest::test_enum_tuple_list_values",
"tests/unittest_brain.py::EnumBrainTest::test_ignores_with_nodes_from_body_of_enum",
"tests/unittest_brain.py::EnumBrainTest::test_infer_enum_value_as_the_right_type",
"tests/unittest_brain.py::EnumBrainTest::test_int_enum",
"tests/unittest_brain.py::EnumBrainTest::test_looks_like_enum_false_positive",
"tests/unittest_brain.py::EnumBrainTest::test_mingled_single_and_double_quotes_does_not_crash",
"tests/unittest_brain.py::EnumBrainTest::test_simple_enum",
"tests/unittest_brain.py::EnumBrainTest::test_special_characters_does_not_crash",
"tests/unittest_brain.py::PytestBrainTest::test_pytest",
"tests/unittest_brain.py::TypeBrain::test_invalid_type_subscript",
"tests/unittest_brain.py::TypeBrain::test_type_subscript",
"tests/unittest_brain.py::TypingBrain::test_has_dunder_args",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_base",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_can_correctly_access_methods",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_class_form",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_few_args",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_few_fields",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_inference",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_inference_nonliteral",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_instance_attrs",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_simple",
"tests/unittest_brain.py::TypingBrain::test_typing_namedtuple_dont_crash_on_no_fields",
"tests/unittest_brain.py::TypingBrain::test_typing_types",
"tests/unittest_brain.py::ReBrainTest::test_regex_flags",
"tests/unittest_brain.py::BrainFStrings::test_no_crash_on_const_reconstruction",
"tests/unittest_brain.py::BrainNamedtupleAnnAssignTest::test_no_crash_on_ann_assign_in_namedtuple",
"tests/unittest_brain.py::BrainUUIDTest::test_uuid_has_int_member",
"tests/unittest_brain.py::RandomSampleTest::test_inferred_successfully",
"tests/unittest_brain.py::SubprocessTest::test_popen_does_not_have_class_getitem",
"tests/unittest_brain.py::SubprocessTest::test_subprcess_check_output",
"tests/unittest_brain.py::SubprocessTest::test_subprocess_args",
"tests/unittest_brain.py::TestIsinstanceInference::test_type_type",
"tests/unittest_brain.py::TestIsinstanceInference::test_object_type",
"tests/unittest_brain.py::TestIsinstanceInference::test_type_object",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_int_true",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_int_false",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_object_true",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_object_true3",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_class_false",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_type_false",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_str_true",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_str_false",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_tuple_argument",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_type_false2",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_object_true2",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_type_true",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_edge_case",
"tests/unittest_brain.py::TestIsinstanceInference::test_uninferable_bad_type",
"tests/unittest_brain.py::TestIsinstanceInference::test_uninferable_keywords",
"tests/unittest_brain.py::TestIsinstanceInference::test_too_many_args",
"tests/unittest_brain.py::TestIsinstanceInference::test_first_param_is_uninferable",
"tests/unittest_brain.py::TestIssubclassBrain::test_type_type",
"tests/unittest_brain.py::TestIssubclassBrain::test_object_type",
"tests/unittest_brain.py::TestIssubclassBrain::test_type_object",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_same_class",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_not_the_same_class",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_object_true",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_same_user_defined_class",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_different_user_defined_classes",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_type_false",
"tests/unittest_brain.py::TestIssubclassBrain::test_isinstance_tuple_argument",
"tests/unittest_brain.py::TestIssubclassBrain::test_isinstance_object_true2",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_short_circuit",
"tests/unittest_brain.py::TestIssubclassBrain::test_uninferable_bad_type",
"tests/unittest_brain.py::TestIssubclassBrain::test_uninferable_keywords",
"tests/unittest_brain.py::TestIssubclassBrain::test_too_many_args",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_list",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_tuple",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_var",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_dict",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_set",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_object",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_class_with_metaclass",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_object_failure",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_string",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_generator_failure",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_failure_missing_variable",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_bytes",
"tests/unittest_brain.py::TestLenBuiltinInference::test_int_subclass_result",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_builtin_inference_attribute_error_str",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_builtin_inference_recursion_error_self_referential_attribute",
"tests/unittest_brain.py::test_infer_str",
"tests/unittest_brain.py::test_infer_int",
"tests/unittest_brain.py::test_infer_dict_from_keys",
"tests/unittest_brain.py::TestFunctoolsPartial::test_invalid_functools_partial_calls",
"tests/unittest_brain.py::TestFunctoolsPartial::test_inferred_partial_function_calls",
"tests/unittest_brain.py::test_http_client_brain",
"tests/unittest_brain.py::test_http_status_brain",
"tests/unittest_brain.py::test_oserror_model",
"tests/unittest_brain.py::test_crypt_brain",
"tests/unittest_brain.py::test_dataclasses",
"tests/unittest_brain.py::test_str_and_bytes['hey'.encode()-Const-]",
"tests/unittest_brain.py::test_str_and_bytes[b'hey'.decode()-Const-]",
"tests/unittest_brain.py::test_str_and_bytes['hey'.encode().decode()-Const-]",
"tests/unittest_brain.py::test_no_recursionerror_on_self_referential_length_check",
"tests/unittest_brain.py::TestLenBuiltinInference::test_int_subclass_argument"
] |
[
"pytest -rA tests"
] |
pytest
|
{
"files": 2,
"hunks": 4,
"lines": 18
}
|
||
This is caused by our local plugin.
Has probably nothing to do with upstream.
This is caused by a bad refactor from us, we deprecated `astroid.node_classes` and `astroid.scoped_nodes` in favor of `astroid.nodes` but nothing should break before astroid 3.0.
@Pierre-Sassoulas I see.
Also Statement is not available in astroid.nodes it is in astroid.nodes.node_classes
Was the Statement also deprecated? Or called something else now?
It seems we're not using it ourselves or not by using `astroid.nodes` API so we did not realize it was not importable easily. But it should, I'm going to add it.
|
40ea1a3b8e52bbfed43deb1725cde461f4bd8a96
|
[
"https://github.com/pylint-dev/astroid/commit/83064a191c949e535f7a22e950be215a240c5b30",
"https://github.com/pylint-dev/astroid/commit/502536f6e654907eb00c1d28d58200bb666c1c2d"
] | 2021-09-04T15:03:02
|
This is caused by our local plugin.
Has probably nothing to do with upstream.
This is caused by a bad refactor from us, we deprecated `astroid.node_classes` and `astroid.scoped_nodes` in favor of `astroid.nodes` but nothing should break before astroid 3.0.
@Pierre-Sassoulas I see.
Also Statement is not available in astroid.nodes it is in astroid.nodes.node_classes
Was the Statement also deprecated? Or called something else now?
It seems we're not using it ourselves or not by using `astroid.nodes` API so we did not realize it was not importable easily. But it should, I'm going to add it.
|
pylint-dev__astroid-1164
|
[
"1162"
] |
python
|
diff --git a/astroid/nodes/__init__.py b/astroid/nodes/__init__.py
index 06bf60d77d..26254a0d06 100644
--- a/astroid/nodes/__init__.py
+++ b/astroid/nodes/__init__.py
@@ -89,6 +89,7 @@
Set,
Slice,
Starred,
+ Statement,
Subscript,
TryExcept,
TryFinally,
@@ -116,6 +117,7 @@
SetComp,
builtin_lookup,
function_to_method,
+ get_wrapping_class,
)
_BaseContainer = BaseContainer # TODO Remove for astroid 3.0
@@ -254,6 +256,7 @@
"FunctionDef",
"function_to_method",
"GeneratorExp",
+ "get_wrapping_class",
"Global",
"If",
"IfExp",
@@ -287,6 +290,7 @@
"SetComp",
"Slice",
"Starred",
+ "Statement",
"Subscript",
"TryExcept",
"TryFinally",
|
ImportError: cannot import name 'Statement' from 'astroid.node_classes'
### Steps to reproduce
1. run pylint <some_file>
### Current behavior
```python
exception: Traceback (most recent call last):
File "/usr/lib/python3.9/runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/lib/python3.9/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "/home/user/folder/check_mk/.venv/lib/python3.9/site-packages/pylint/__main__.py", line 9, in <module>
pylint.run_pylint()
File "/home/user/folder/check_mk/.venv/lib/python3.9/site-packages/pylint/__init__.py", line 24, in run_pylint
PylintRun(sys.argv[1:])
File "/home/user/folder/check_mk/.venv/lib/python3.9/site-packages/pylint/lint/run.py", line 331, in __init__
linter.load_plugin_modules(plugins)
File "/home/user/folder/check_mk/.venv/lib/python3.9/site-packages/pylint/lint/pylinter.py", line 551, in load_plugin_modules
module = astroid.modutils.load_module_from_name(modname)
File "/home/user/folder/check_mk/.venv/lib/python3.9/site-packages/astroid/modutils.py", line 218, in load_module_from_name
return importlib.import_module(dotted_name)
File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 855, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/home/user/folder/check_mk/tests/testlib/pylint_checker_cmk_module_layers.py", line 14, in <module>
from astroid.node_classes import Import, ImportFrom, Statement # type: ignore[import]
ImportError: cannot import name 'Statement' from 'astroid.node_classes' (/home/user/folder/check_mk/.venv/lib/python3.9/site-packages/astroid/node_classes.py)
```
### Expected behavior
No exception
### `python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"` output
2.7.3
pylint 2.10.2
astroid 2.7.3
Python 3.9.5 (default, May 11 2021, 08:20:37)
|
1164
|
pylint-dev/astroid
|
diff --git a/tests/unittest_brain_ctypes.py b/tests/unittest_brain_ctypes.py
index eecc981396..87d648bdc6 100644
--- a/tests/unittest_brain_ctypes.py
+++ b/tests/unittest_brain_ctypes.py
@@ -2,8 +2,7 @@
import pytest
-from astroid import extract_node
-from astroid.nodes.node_classes import Const
+from astroid import extract_node, nodes
pytestmark = pytest.mark.skipif(
hasattr(sys, "pypy_version_info"),
@@ -72,7 +71,7 @@ def test_ctypes_redefined_types_members(c_type, builtin_type, type_code):
"""
node = extract_node(src)
node_inf = node.inferred()[0]
- assert isinstance(node_inf, Const)
+ assert isinstance(node_inf, nodes.Const)
assert node_inf.value == type_code
@@ -102,5 +101,5 @@ def test_other_ctypes_member_untouched():
"""
node = extract_node(src)
node_inf = node.inferred()[0]
- assert isinstance(node_inf, Const)
+ assert isinstance(node_inf, nodes.Const)
assert node_inf.value == 6
diff --git a/tests/unittest_lookup.py b/tests/unittest_lookup.py
index c2a273d83b..fcd33a42b4 100644
--- a/tests/unittest_lookup.py
+++ b/tests/unittest_lookup.py
@@ -24,7 +24,6 @@
InferenceError,
NameInferenceError,
)
-from astroid.nodes.scoped_nodes import builtin_lookup
from . import resources
@@ -389,8 +388,8 @@ def initialize(linter):
self.assertEqual(len(path.lookup("__path__")[1]), 1)
def test_builtin_lookup(self):
- self.assertEqual(builtin_lookup("__dict__")[1], ())
- intstmts = builtin_lookup("int")[1]
+ self.assertEqual(nodes.builtin_lookup("__dict__")[1], ())
+ intstmts = nodes.builtin_lookup("int")[1]
self.assertEqual(len(intstmts), 1)
self.assertIsInstance(intstmts[0], nodes.ClassDef)
self.assertEqual(intstmts[0].name, "int")
@@ -411,7 +410,10 @@ class foo:
def test(self):
pass
"""
- member = builder.extract_node(code, __name__).targets[0]
+
+ node = builder.extract_node(code, __name__)
+ assert isinstance(node, nodes.Assign)
+ member = node.targets[0]
it = member.infer()
obj = next(it)
self.assertIsInstance(obj, nodes.Const)
diff --git a/tests/unittest_protocols.py b/tests/unittest_protocols.py
index 3250ca7866..6c8849deec 100644
--- a/tests/unittest_protocols.py
+++ b/tests/unittest_protocols.py
@@ -22,7 +22,6 @@
from astroid import extract_node, nodes, util
from astroid.const import PY38_PLUS, PY310_PLUS
from astroid.exceptions import InferenceError
-from astroid.nodes.node_classes import AssignName, Const, Name, Starred
@contextlib.contextmanager
@@ -38,14 +37,14 @@ class ProtocolTests(unittest.TestCase):
def assertConstNodesEqual(self, nodes_list_expected, nodes_list_got):
self.assertEqual(len(nodes_list_expected), len(nodes_list_got))
for node in nodes_list_got:
- self.assertIsInstance(node, Const)
+ self.assertIsInstance(node, nodes.Const)
for node, expected_value in zip(nodes_list_got, nodes_list_expected):
self.assertEqual(expected_value, node.value)
def assertNameNodesEqual(self, nodes_list_expected, nodes_list_got):
self.assertEqual(len(nodes_list_expected), len(nodes_list_got))
for node in nodes_list_got:
- self.assertIsInstance(node, Name)
+ self.assertIsInstance(node, nodes.Name)
for node, expected_name in zip(nodes_list_got, nodes_list_expected):
self.assertEqual(expected_name, node.name)
@@ -60,11 +59,11 @@ def test_assigned_stmts_simple_for(self):
"""
)
- for1_assnode = next(assign_stmts[0].nodes_of_class(AssignName))
+ for1_assnode = next(assign_stmts[0].nodes_of_class(nodes.AssignName))
assigned = list(for1_assnode.assigned_stmts())
self.assertConstNodesEqual([1, 2, 3], assigned)
- for2_assnode = next(assign_stmts[1].nodes_of_class(AssignName))
+ for2_assnode = next(assign_stmts[1].nodes_of_class(nodes.AssignName))
self.assertRaises(InferenceError, list, for2_assnode.assigned_stmts())
def test_assigned_stmts_starred_for(self):
@@ -75,14 +74,14 @@ def test_assigned_stmts_starred_for(self):
"""
)
- for1_starred = next(assign_stmts.nodes_of_class(Starred))
+ for1_starred = next(assign_stmts.nodes_of_class(nodes.Starred))
assigned = next(for1_starred.assigned_stmts())
assert isinstance(assigned, astroid.List)
assert assigned.as_string() == "[1, 2]"
def _get_starred_stmts(self, code):
assign_stmt = extract_node(f"{code} #@")
- starred = next(assign_stmt.nodes_of_class(Starred))
+ starred = next(assign_stmt.nodes_of_class(nodes.Starred))
return next(starred.assigned_stmts())
def _helper_starred_expected_const(self, code, expected):
@@ -97,7 +96,7 @@ def _helper_starred_expected(self, code, expected):
def _helper_starred_inference_error(self, code):
assign_stmt = extract_node(f"{code} #@")
- starred = next(assign_stmt.nodes_of_class(Starred))
+ starred = next(assign_stmt.nodes_of_class(nodes.Starred))
self.assertRaises(InferenceError, list, starred.assigned_stmts())
def test_assigned_stmts_starred_assnames(self):
@@ -143,11 +142,11 @@ def test_assigned_stmts_assignments(self):
"""
)
- simple_assnode = next(assign_stmts[0].nodes_of_class(AssignName))
+ simple_assnode = next(assign_stmts[0].nodes_of_class(nodes.AssignName))
assigned = list(simple_assnode.assigned_stmts())
self.assertNameNodesEqual(["a"], assigned)
- assnames = assign_stmts[1].nodes_of_class(AssignName)
+ assnames = assign_stmts[1].nodes_of_class(nodes.AssignName)
simple_mul_assnode_1 = next(assnames)
assigned = list(simple_mul_assnode_1.assigned_stmts())
self.assertNameNodesEqual(["b"], assigned)
@@ -162,13 +161,15 @@ def test_assigned_stmts_annassignments(self):
b: str #@
"""
)
- simple_annassign_node = next(annassign_stmts[0].nodes_of_class(AssignName))
+ simple_annassign_node = next(
+ annassign_stmts[0].nodes_of_class(nodes.AssignName)
+ )
assigned = list(simple_annassign_node.assigned_stmts())
self.assertEqual(1, len(assigned))
- self.assertIsInstance(assigned[0], Const)
+ self.assertIsInstance(assigned[0], nodes.Const)
self.assertEqual(assigned[0].value, "abc")
- empty_annassign_node = next(annassign_stmts[1].nodes_of_class(AssignName))
+ empty_annassign_node = next(annassign_stmts[1].nodes_of_class(nodes.AssignName))
assigned = list(empty_annassign_node.assigned_stmts())
self.assertEqual(1, len(assigned))
self.assertIs(assigned[0], util.Uninferable)
diff --git a/tests/unittest_python3.py b/tests/unittest_python3.py
index ba0dd4fa76..045ce90bb0 100644
--- a/tests/unittest_python3.py
+++ b/tests/unittest_python3.py
@@ -20,8 +20,6 @@
from astroid import nodes
from astroid.builder import AstroidBuilder, extract_node
-from astroid.nodes.node_classes import Assign, Const, Expr, Name, YieldFrom
-from astroid.nodes.scoped_nodes import ClassDef, FunctionDef
from astroid.test_utils import require_version
@@ -36,7 +34,7 @@ def test_starred_notation(self):
# Get the star node
node = next(next(next(astroid.get_children()).get_children()).get_children())
- self.assertTrue(isinstance(node.assign_type(), Assign))
+ self.assertTrue(isinstance(node.assign_type(), nodes.Assign))
def test_yield_from(self):
body = dedent(
@@ -47,11 +45,11 @@ def func():
)
astroid = self.builder.string_build(body)
func = astroid.body[0]
- self.assertIsInstance(func, FunctionDef)
+ self.assertIsInstance(func, nodes.FunctionDef)
yieldfrom_stmt = func.body[0]
- self.assertIsInstance(yieldfrom_stmt, Expr)
- self.assertIsInstance(yieldfrom_stmt.value, YieldFrom)
+ self.assertIsInstance(yieldfrom_stmt, nodes.Expr)
+ self.assertIsInstance(yieldfrom_stmt.value, nodes.YieldFrom)
self.assertEqual(yieldfrom_stmt.as_string(), "yield from iter([1, 2])")
def test_yield_from_is_generator(self):
@@ -63,7 +61,7 @@ def func():
)
astroid = self.builder.string_build(body)
func = astroid.body[0]
- self.assertIsInstance(func, FunctionDef)
+ self.assertIsInstance(func, nodes.FunctionDef)
self.assertTrue(func.is_generator())
def test_yield_from_as_string(self):
@@ -85,7 +83,7 @@ def test_simple_metaclass(self):
klass = astroid.body[0]
metaclass = klass.metaclass()
- self.assertIsInstance(metaclass, ClassDef)
+ self.assertIsInstance(metaclass, nodes.ClassDef)
self.assertEqual(metaclass.name, "type")
def test_metaclass_error(self):
@@ -104,7 +102,7 @@ class Test(metaclass=ABCMeta): pass"""
klass = astroid.body[1]
metaclass = klass.metaclass()
- self.assertIsInstance(metaclass, ClassDef)
+ self.assertIsInstance(metaclass, nodes.ClassDef)
self.assertEqual(metaclass.name, "ABCMeta")
def test_metaclass_multiple_keywords(self):
@@ -114,7 +112,7 @@ def test_metaclass_multiple_keywords(self):
klass = astroid.body[0]
metaclass = klass.metaclass()
- self.assertIsInstance(metaclass, ClassDef)
+ self.assertIsInstance(metaclass, nodes.ClassDef)
self.assertEqual(metaclass.name, "type")
def test_as_string(self):
@@ -171,7 +169,7 @@ class SubTest(Test): pass
klass = astroid["SubTest"]
self.assertTrue(klass.newstyle)
metaclass = klass.metaclass()
- self.assertIsInstance(metaclass, ClassDef)
+ self.assertIsInstance(metaclass, nodes.ClassDef)
self.assertEqual(metaclass.name, "ABCMeta")
def test_metaclass_ancestors(self):
@@ -199,7 +197,7 @@ class ThirdImpl(Simple, SecondMeta):
for name in names:
impl = astroid[name]
meta = impl.metaclass()
- self.assertIsInstance(meta, ClassDef)
+ self.assertIsInstance(meta, nodes.ClassDef)
self.assertEqual(meta.name, metaclass)
def test_annotation_support(self):
@@ -213,18 +211,18 @@ def test(a: int, b: str, c: None, d, e,
)
)
func = astroid["test"]
- self.assertIsInstance(func.args.varargannotation, Name)
+ self.assertIsInstance(func.args.varargannotation, nodes.Name)
self.assertEqual(func.args.varargannotation.name, "float")
- self.assertIsInstance(func.args.kwargannotation, Name)
+ self.assertIsInstance(func.args.kwargannotation, nodes.Name)
self.assertEqual(func.args.kwargannotation.name, "int")
- self.assertIsInstance(func.returns, Name)
+ self.assertIsInstance(func.returns, nodes.Name)
self.assertEqual(func.returns.name, "int")
arguments = func.args
- self.assertIsInstance(arguments.annotations[0], Name)
+ self.assertIsInstance(arguments.annotations[0], nodes.Name)
self.assertEqual(arguments.annotations[0].name, "int")
- self.assertIsInstance(arguments.annotations[1], Name)
+ self.assertIsInstance(arguments.annotations[1], nodes.Name)
self.assertEqual(arguments.annotations[1].name, "str")
- self.assertIsInstance(arguments.annotations[2], Const)
+ self.assertIsInstance(arguments.annotations[2], nodes.Const)
self.assertIsNone(arguments.annotations[2].value)
self.assertIsNone(arguments.annotations[3])
self.assertIsNone(arguments.annotations[4])
@@ -238,9 +236,9 @@ def test(a: int=1, b: str=2):
)
)
func = astroid["test"]
- self.assertIsInstance(func.args.annotations[0], Name)
+ self.assertIsInstance(func.args.annotations[0], nodes.Name)
self.assertEqual(func.args.annotations[0].name, "int")
- self.assertIsInstance(func.args.annotations[1], Name)
+ self.assertIsInstance(func.args.annotations[1], nodes.Name)
self.assertEqual(func.args.annotations[1].name, "str")
self.assertIsNone(func.returns)
@@ -255,11 +253,11 @@ def test(*, a: int, b: str, c: None, d, e):
)
func = node["test"]
arguments = func.args
- self.assertIsInstance(arguments.kwonlyargs_annotations[0], Name)
+ self.assertIsInstance(arguments.kwonlyargs_annotations[0], nodes.Name)
self.assertEqual(arguments.kwonlyargs_annotations[0].name, "int")
- self.assertIsInstance(arguments.kwonlyargs_annotations[1], Name)
+ self.assertIsInstance(arguments.kwonlyargs_annotations[1], nodes.Name)
self.assertEqual(arguments.kwonlyargs_annotations[1].name, "str")
- self.assertIsInstance(arguments.kwonlyargs_annotations[2], Const)
+ self.assertIsInstance(arguments.kwonlyargs_annotations[2], nodes.Const)
self.assertIsNone(arguments.kwonlyargs_annotations[2].value)
self.assertIsNone(arguments.kwonlyargs_annotations[3])
self.assertIsNone(arguments.kwonlyargs_annotations[4])
@@ -283,6 +281,7 @@ def test_unpacking_in_dicts(self):
code = "{'x': 1, **{'y': 2}}"
node = extract_node(code)
self.assertEqual(node.as_string(), code)
+ assert isinstance(node, nodes.Dict)
keys = [key for (key, _) in node.items]
self.assertIsInstance(keys[0], nodes.Const)
self.assertIsInstance(keys[1], nodes.DictUnpack)
diff --git a/tests/unittest_scoped_nodes.py b/tests/unittest_scoped_nodes.py
index bbb7cbee02..502d34d271 100644
--- a/tests/unittest_scoped_nodes.py
+++ b/tests/unittest_scoped_nodes.py
@@ -53,7 +53,7 @@
ResolveError,
TooManyLevelsError,
)
-from astroid.nodes import scoped_nodes
+from astroid.nodes.scoped_nodes import _is_metaclass
from . import resources
@@ -1120,7 +1120,7 @@ class BBB(AAA.JJJ):
pass
"""
)
- self.assertFalse(scoped_nodes._is_metaclass(klass))
+ self.assertFalse(_is_metaclass(klass))
ancestors = [base.name for base in klass.ancestors()]
self.assertIn("object", ancestors)
self.assertIn("JJJ", ancestors)
@@ -1169,7 +1169,7 @@ class WithMeta(object, metaclass=abc.ABCMeta):
)
inferred = next(klass.infer())
metaclass = inferred.metaclass()
- self.assertIsInstance(metaclass, scoped_nodes.ClassDef)
+ self.assertIsInstance(metaclass, nodes.ClassDef)
self.assertIn(metaclass.qname(), ("abc.ABCMeta", "_py_abc.ABCMeta"))
@unittest.skipUnless(HAS_SIX, "These tests require the six library")
@@ -1667,7 +1667,7 @@ class A(object):
pass
"""
)
- type_cls = scoped_nodes.builtin_lookup("type")[1][0]
+ type_cls = nodes.builtin_lookup("type")[1][0]
self.assertEqual(cls.implicit_metaclass(), type_cls)
def test_implicit_metaclass_lookup(self):
@@ -1743,7 +1743,7 @@ class A(object, metaclass=Metaclass):
# of the property
property_meta = next(module["Metaclass"].igetattr("meta_property"))
self.assertIsInstance(property_meta, objects.Property)
- wrapping = scoped_nodes.get_wrapping_class(property_meta)
+ wrapping = nodes.get_wrapping_class(property_meta)
self.assertEqual(wrapping, module["Metaclass"])
property_class = next(acls.igetattr("meta_property"))
@@ -1751,7 +1751,7 @@ class A(object, metaclass=Metaclass):
self.assertEqual(property_class.value, 42)
static = next(acls.igetattr("static"))
- self.assertIsInstance(static, scoped_nodes.FunctionDef)
+ self.assertIsInstance(static, nodes.FunctionDef)
def test_local_attr_invalid_mro(self):
cls = builder.extract_node(
@@ -1820,14 +1820,14 @@ class Test(object): #@
"""
)
cls = next(ast_nodes[0].infer())
- self.assertIsInstance(next(cls.igetattr("lam")), scoped_nodes.Lambda)
- self.assertIsInstance(next(cls.igetattr("not_method")), scoped_nodes.Lambda)
+ self.assertIsInstance(next(cls.igetattr("lam")), nodes.Lambda)
+ self.assertIsInstance(next(cls.igetattr("not_method")), nodes.Lambda)
instance = next(ast_nodes[1].infer())
lam = next(instance.igetattr("lam"))
self.assertIsInstance(lam, BoundMethod)
not_method = next(instance.igetattr("not_method"))
- self.assertIsInstance(not_method, scoped_nodes.Lambda)
+ self.assertIsInstance(not_method, nodes.Lambda)
def test_instance_bound_method_lambdas_2(self):
"""
@@ -1846,7 +1846,7 @@ class MyClass(object): #@
"""
)
cls = next(ast_nodes[0].infer())
- self.assertIsInstance(next(cls.igetattr("f2")), scoped_nodes.Lambda)
+ self.assertIsInstance(next(cls.igetattr("f2")), nodes.Lambda)
instance = next(ast_nodes[1].infer())
f2 = next(instance.igetattr("f2"))
diff --git a/tests/unittest_utils.py b/tests/unittest_utils.py
index 631f3e7fb5..ea5d036210 100644
--- a/tests/unittest_utils.py
+++ b/tests/unittest_utils.py
@@ -13,10 +13,8 @@
import unittest
-from astroid import builder, nodes
-from astroid import util as astroid_util
+from astroid import Uninferable, builder, nodes
from astroid.exceptions import InferenceError
-from astroid.nodes import node_classes
class InferenceUtil(unittest.TestCase):
@@ -38,8 +36,8 @@ def test_not_exclusive(self):
xnames = [n for n in module.nodes_of_class(nodes.Name) if n.name == "x"]
assert len(xnames) == 3
assert xnames[1].lineno == 6
- self.assertEqual(node_classes.are_exclusive(xass1, xnames[1]), False)
- self.assertEqual(node_classes.are_exclusive(xass1, xnames[2]), False)
+ self.assertEqual(nodes.are_exclusive(xass1, xnames[1]), False)
+ self.assertEqual(nodes.are_exclusive(xass1, xnames[2]), False)
def test_if(self):
module = builder.parse(
@@ -61,12 +59,12 @@ def test_if(self):
a4 = module.locals["a"][3]
a5 = module.locals["a"][4]
a6 = module.locals["a"][5]
- self.assertEqual(node_classes.are_exclusive(a1, a2), False)
- self.assertEqual(node_classes.are_exclusive(a1, a3), True)
- self.assertEqual(node_classes.are_exclusive(a1, a5), True)
- self.assertEqual(node_classes.are_exclusive(a3, a5), True)
- self.assertEqual(node_classes.are_exclusive(a3, a4), False)
- self.assertEqual(node_classes.are_exclusive(a5, a6), False)
+ self.assertEqual(nodes.are_exclusive(a1, a2), False)
+ self.assertEqual(nodes.are_exclusive(a1, a3), True)
+ self.assertEqual(nodes.are_exclusive(a1, a5), True)
+ self.assertEqual(nodes.are_exclusive(a3, a5), True)
+ self.assertEqual(nodes.are_exclusive(a3, a4), False)
+ self.assertEqual(nodes.are_exclusive(a5, a6), False)
def test_try_except(self):
module = builder.parse(
@@ -89,16 +87,16 @@ def exclusive_func2():
f2 = module.locals["exclusive_func2"][1]
f3 = module.locals["exclusive_func2"][2]
f4 = module.locals["exclusive_func2"][3]
- self.assertEqual(node_classes.are_exclusive(f1, f2), True)
- self.assertEqual(node_classes.are_exclusive(f1, f3), True)
- self.assertEqual(node_classes.are_exclusive(f1, f4), False)
- self.assertEqual(node_classes.are_exclusive(f2, f4), True)
- self.assertEqual(node_classes.are_exclusive(f3, f4), True)
- self.assertEqual(node_classes.are_exclusive(f3, f2), True)
+ self.assertEqual(nodes.are_exclusive(f1, f2), True)
+ self.assertEqual(nodes.are_exclusive(f1, f3), True)
+ self.assertEqual(nodes.are_exclusive(f1, f4), False)
+ self.assertEqual(nodes.are_exclusive(f2, f4), True)
+ self.assertEqual(nodes.are_exclusive(f3, f4), True)
+ self.assertEqual(nodes.are_exclusive(f3, f2), True)
- self.assertEqual(node_classes.are_exclusive(f2, f1), True)
- self.assertEqual(node_classes.are_exclusive(f4, f1), False)
- self.assertEqual(node_classes.are_exclusive(f4, f2), True)
+ self.assertEqual(nodes.are_exclusive(f2, f1), True)
+ self.assertEqual(nodes.are_exclusive(f4, f1), False)
+ self.assertEqual(nodes.are_exclusive(f4, f2), True)
def test_unpack_infer_uninferable_nodes(self):
node = builder.extract_node(
@@ -109,9 +107,9 @@ def test_unpack_infer_uninferable_nodes(self):
"""
)
inferred = next(node.infer())
- unpacked = list(node_classes.unpack_infer(inferred))
+ unpacked = list(nodes.unpack_infer(inferred))
self.assertEqual(len(unpacked), 3)
- self.assertTrue(all(elt is astroid_util.Uninferable for elt in unpacked))
+ self.assertTrue(all(elt is Uninferable for elt in unpacked))
def test_unpack_infer_empty_tuple(self):
node = builder.extract_node(
@@ -121,7 +119,7 @@ def test_unpack_infer_empty_tuple(self):
)
inferred = next(node.infer())
with self.assertRaises(InferenceError):
- list(node_classes.unpack_infer(inferred))
+ list(nodes.unpack_infer(inferred))
if __name__ == "__main__":
|
none
|
[
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup"
] |
[
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_bool-bool-?]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_byte-int-b]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_char-bytes-c]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_double-float-d]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_float-float-f]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_int-int-i]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_int16-int-h]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_int32-int-i]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_int64-int-l]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_int8-int-b]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_long-int-l]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_longdouble-float-g]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_longlong-int-l]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_short-int-h]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_size_t-int-L]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_ssize_t-int-l]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_ubyte-int-B]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_uint-int-I]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_uint16-int-H]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_uint32-int-I]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_uint64-int-L]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_uint8-int-B]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_ulong-int-L]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_ulonglong-int-L]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_ushort-int-H]",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_wchar-str-u]",
"tests/unittest_brain_ctypes.py::test_cdata_member_access",
"tests/unittest_brain_ctypes.py::test_other_ctypes_member_untouched",
"tests/unittest_lookup.py::LookupTest::test_builtin_lookup",
"tests/unittest_lookup.py::LookupTest::test_class",
"tests/unittest_lookup.py::LookupTest::test_class_ancestor_name",
"tests/unittest_lookup.py::LookupTest::test_class_in_function",
"tests/unittest_lookup.py::LookupTest::test_class_variables",
"tests/unittest_lookup.py::LookupTest::test_decorator_arguments_lookup",
"tests/unittest_lookup.py::LookupTest::test_dict_comp_nested",
"tests/unittest_lookup.py::LookupTest::test_dict_comps",
"tests/unittest_lookup.py::LookupTest::test_explicit___name__",
"tests/unittest_lookup.py::LookupTest::test_function_argument_with_default",
"tests/unittest_lookup.py::LookupTest::test_function_module_special",
"tests/unittest_lookup.py::LookupTest::test_function_nested",
"tests/unittest_lookup.py::LookupTest::test_generator_attributes",
"tests/unittest_lookup.py::LookupTest::test_global_delete",
"tests/unittest_lookup.py::LookupTest::test_inner_classes",
"tests/unittest_lookup.py::LookupTest::test_inner_decorator_member_lookup",
"tests/unittest_lookup.py::LookupTest::test_lambda_nested",
"tests/unittest_lookup.py::LookupTest::test_limit",
"tests/unittest_lookup.py::LookupTest::test_list_comp_nested",
"tests/unittest_lookup.py::LookupTest::test_list_comp_target",
"tests/unittest_lookup.py::LookupTest::test_list_comps",
"tests/unittest_lookup.py::LookupTest::test_loopvar_hiding",
"tests/unittest_lookup.py::LookupTest::test_method",
"tests/unittest_lookup.py::LookupTest::test_module",
"tests/unittest_lookup.py::LookupTest::test_set_comp_closure",
"tests/unittest_lookup.py::LookupTest::test_set_comp_nested",
"tests/unittest_lookup.py::LookupTest::test_set_comps",
"tests/unittest_lookup.py::LookupTest::test_static_method_lookup",
"tests/unittest_lookup.py::LookupControlFlowTest::test_assign_after_args_param",
"tests/unittest_lookup.py::LookupControlFlowTest::test_assign_after_kwonly_param",
"tests/unittest_lookup.py::LookupControlFlowTest::test_assign_after_param",
"tests/unittest_lookup.py::LookupControlFlowTest::test_assign_after_posonly_param",
"tests/unittest_lookup.py::LookupControlFlowTest::test_assign_after_use",
"tests/unittest_lookup.py::LookupControlFlowTest::test_assign_exclusive",
"tests/unittest_lookup.py::LookupControlFlowTest::test_assign_not_exclusive",
"tests/unittest_lookup.py::LookupControlFlowTest::test_consecutive_assign",
"tests/unittest_lookup.py::LookupControlFlowTest::test_del_exclusive",
"tests/unittest_lookup.py::LookupControlFlowTest::test_del_no_effect_after",
"tests/unittest_lookup.py::LookupControlFlowTest::test_del_not_exclusive",
"tests/unittest_lookup.py::LookupControlFlowTest::test_del_removes_prior",
"tests/unittest_lookup.py::LookupControlFlowTest::test_except_assign_after_block",
"tests/unittest_lookup.py::LookupControlFlowTest::test_except_assign_after_block_overwritten",
"tests/unittest_lookup.py::LookupControlFlowTest::test_except_assign_in_block",
"tests/unittest_lookup.py::LookupControlFlowTest::test_except_assign_in_block_multiple",
"tests/unittest_lookup.py::LookupControlFlowTest::test_except_var_after_block_multiple",
"tests/unittest_lookup.py::LookupControlFlowTest::test_except_var_after_block_single",
"tests/unittest_lookup.py::LookupControlFlowTest::test_except_var_in_block",
"tests/unittest_lookup.py::LookupControlFlowTest::test_except_var_in_block_overwrites",
"tests/unittest_lookup.py::LookupControlFlowTest::test_except_var_in_multiple_blocks",
"tests/unittest_lookup.py::LookupControlFlowTest::test_if_assign",
"tests/unittest_lookup.py::LookupControlFlowTest::test_if_assigns_different_branch",
"tests/unittest_lookup.py::LookupControlFlowTest::test_if_assigns_same_branch",
"tests/unittest_lookup.py::LookupControlFlowTest::test_if_else",
"tests/unittest_lookup.py::LookupControlFlowTest::test_if_variable_in_condition_1",
"tests/unittest_lookup.py::LookupControlFlowTest::test_if_variable_in_condition_2",
"tests/unittest_protocols.py::ProtocolTests::test_assign_stmts_starred_fails",
"tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_annassignments",
"tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_assignments",
"tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_simple_for",
"tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_starred_assnames",
"tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_starred_for",
"tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_starred_yes",
"tests/unittest_protocols.py::ProtocolTests::test_not_passing_uninferable_in_seq_inference",
"tests/unittest_protocols.py::ProtocolTests::test_sequence_assigned_stmts_not_accepting_empty_node",
"tests/unittest_protocols.py::test_named_expr_inference",
"tests/unittest_python3.py::Python3TC::test_annotation_as_string",
"tests/unittest_python3.py::Python3TC::test_annotation_support",
"tests/unittest_python3.py::Python3TC::test_as_string",
"tests/unittest_python3.py::Python3TC::test_async_comprehensions",
"tests/unittest_python3.py::Python3TC::test_async_comprehensions_as_string",
"tests/unittest_python3.py::Python3TC::test_async_comprehensions_outside_coroutine",
"tests/unittest_python3.py::Python3TC::test_format_string",
"tests/unittest_python3.py::Python3TC::test_kwonlyargs_annotations_supper",
"tests/unittest_python3.py::Python3TC::test_metaclass_ancestors",
"tests/unittest_python3.py::Python3TC::test_metaclass_error",
"tests/unittest_python3.py::Python3TC::test_metaclass_imported",
"tests/unittest_python3.py::Python3TC::test_metaclass_multiple_keywords",
"tests/unittest_python3.py::Python3TC::test_metaclass_yes_leak",
"tests/unittest_python3.py::Python3TC::test_nested_unpacking_in_dicts",
"tests/unittest_python3.py::Python3TC::test_old_syntax_works",
"tests/unittest_python3.py::Python3TC::test_parent_metaclass",
"tests/unittest_python3.py::Python3TC::test_simple_metaclass",
"tests/unittest_python3.py::Python3TC::test_starred_notation",
"tests/unittest_python3.py::Python3TC::test_underscores_in_numeral_literal",
"tests/unittest_python3.py::Python3TC::test_unpacking_in_dict_getitem",
"tests/unittest_python3.py::Python3TC::test_unpacking_in_dicts",
"tests/unittest_python3.py::Python3TC::test_yield_from",
"tests/unittest_python3.py::Python3TC::test_yield_from_as_string",
"tests/unittest_python3.py::Python3TC::test_yield_from_is_generator",
"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_abstract_methods_are_not_implicitly_none",
"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_no_returns_is_implicitly_none",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_only_raises_is_not_implicitly_none",
"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_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_scoped_nodes.py::test_slots_duplicate_bases_issue_1089",
"tests/unittest_utils.py::InferenceUtil::test_if",
"tests/unittest_utils.py::InferenceUtil::test_not_exclusive",
"tests/unittest_utils.py::InferenceUtil::test_try_except",
"tests/unittest_utils.py::InferenceUtil::test_unpack_infer_empty_tuple",
"tests/unittest_utils.py::InferenceUtil::test_unpack_infer_uninferable_nodes",
"tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_buffer-bytes-<class"
] |
[
"pytest tests/ -rA"
] |
pytest
|
{
"files": 1,
"hunks": 4,
"lines": 4
}
|
Actually, it seems a decorator is a red herring here, because I get the same off by one issue simply parsing a call
```python
source = """\
f(a=2,
b=3,
)
"""
[call] = ast.parse(source).body
print("ast", call.lineno, call.end_lineno)
[call] = astroid.parse(source).body
print("astroid", call.fromlineno, call.tolineno)
```
which outputs
```
ast 1 3
astroid 1 2
```
Okay, this seems to be caused by the implementation of `NodeNG.tolineno` which uses the last line of the *child* to approximate the last line of the parent:
https://github.com/PyCQA/astroid/blob/03efcc3f86b88bab3080fe69119ee4c69e4afd0a/astroid/nodes/node_ng.py#L437-L446
Once possible fix is to override `tolineno` in `Call`. Wdyt?
> this seems to be caused by the implementation of NodeNG.tolineno which uses the last line of the child to approximate the last line of the parent:
Naive question, would it be possible to use the last line of the node instead, directly in NodeNG ?
Yeah, I think that should work with a caveat that the `ast` module only reports end line/column since Python 3.8. I'll draft a PR.
@superbobry I was looking at `tolineno` recently. I was wondering if it would make sense to add a check for >= 3.8 and then just use the `end_lineno` attribute that was added recently. No need to reinvent the wheel on those versions.
Perhaps that's a bit out of the scope of the PR you were going to draft, but it might help!
@DanielNoord I was actually thinking of doing almost exactly that. Interestingly, this change seems to break block range computation in `TryFinally` (and possibly other node classes).
See https://github.com/PyCQA/astroid/runs/4822279617.
|
cfd9e74f7b4cbac08357cadec03c736501368afa
|
[
"https://github.com/pylint-dev/astroid/commit/b1e0db2ab2b81e303fdccbef44280b42747334e7",
"https://github.com/pylint-dev/astroid/commit/15a5bf0ee51b3707e79a42b6427ae6abc80ccf89",
"https://github.com/pylint-dev/astroid/commit/adbc4d48941967078a6100ad63953d5af9da2fa0",
"https://github.com/pylint-dev/astroid/commit/2a16e64e2b5798bc5d966a89a64c12ec26d73305",
"https://github.com/pylint-dev/astroid/commit/caf1916b9052d59280a8e50dc99ce34011924caa",
"https://github.com/pylint-dev/astroid/commit/fd3a6a89a29ff8f12289f7870a769433b3a4c81f"
] | 2022-01-14T21:14:48
|
pylint-dev__astroid-1351
|
[
"1350"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index bce6094b46..e206228968 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -30,6 +30,11 @@ Release date: TBA
Closes #1330
+* Use the ``end_lineno`` attribute for the ``NodeNG.tolineno`` property
+ when it is available.
+
+ Closes #1350
+
* Add ``is_dataclass`` attribute to ``ClassDef`` nodes.
* Use ``sysconfig`` instead of ``distutils`` to determine the location of
diff --git a/astroid/nodes/node_ng.py b/astroid/nodes/node_ng.py
index 4688876f50..5a12925deb 100644
--- a/astroid/nodes/node_ng.py
+++ b/astroid/nodes/node_ng.py
@@ -438,6 +438,8 @@ def fromlineno(self) -> Optional[int]:
@decorators.cachedproperty
def tolineno(self) -> Optional[int]:
"""The last line that this node appears on in the source code."""
+ if self.end_lineno is not None:
+ return self.end_lineno
if not self._astroid_fields:
# can't have children
last_child = None
diff --git a/astroid/rebuilder.py b/astroid/rebuilder.py
index 13b007026c..94043f7ba1 100644
--- a/astroid/rebuilder.py
+++ b/astroid/rebuilder.py
@@ -2125,11 +2125,21 @@ def visit_starred(self, node: "ast.Starred", parent: NodeNG) -> nodes.Starred:
def visit_tryexcept(self, node: "ast.Try", parent: NodeNG) -> nodes.TryExcept:
"""visit a TryExcept node by returning a fresh instance of it"""
if sys.version_info >= (3, 8):
+ # TryExcept excludes the 'finally' but that will be included in the
+ # end_lineno from 'node'. Therefore, we check all non 'finally'
+ # children to find the correct end_lineno and column.
+ end_lineno = node.end_lineno
+ end_col_offset = node.end_col_offset
+ all_children: List["ast.AST"] = [*node.body, *node.handlers, *node.orelse]
+ for child in reversed(all_children):
+ end_lineno = child.end_lineno
+ end_col_offset = child.end_col_offset
+ break
newnode = nodes.TryExcept(
lineno=node.lineno,
col_offset=node.col_offset,
- end_lineno=node.end_lineno,
- end_col_offset=node.end_col_offset,
+ end_lineno=end_lineno,
+ end_col_offset=end_col_offset,
parent=parent,
)
else:
|
Decorator.toline is off by 1
### Steps to reproduce
I came across this inconsistency while debugging why pylint reports `missing-docstring` on the wrong line for the `g2` function in the example. As it turns out, the `toline` of the decorator seems to point to `b=3,` instead of `)`.
```python
import ast
import astroid
source = """\
@f(a=2,
b=3,
)
def g2():
pass
"""
[f] = ast.parse(source).body
[deco] = f.decorator_list
print("ast", deco.lineno, deco.end_lineno)
[f] = astroid.parse(source).body
[deco] = f.decorators.nodes
print("astroid", deco.fromlineno, deco.tolineno)
```
### Current behavior
```
ast 1 3
astroid 1 2
```
### Expected behavior
```
ast 1 3
astroid 1 3
```
### `python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"` output
2.9.3
|
1351
|
pylint-dev/astroid
|
diff --git a/tests/unittest_builder.py b/tests/unittest_builder.py
index eb7fbdc77f..fbcf413174 100644
--- a/tests/unittest_builder.py
+++ b/tests/unittest_builder.py
@@ -71,11 +71,14 @@ def test_callfunc_lineno(self) -> None:
strarg = callfunc.args[0]
self.assertIsInstance(strarg, nodes.Const)
if hasattr(sys, "pypy_version_info"):
- lineno = 4
+ self.assertEqual(strarg.fromlineno, 4)
+ self.assertEqual(strarg.tolineno, 4)
else:
- lineno = 5 if not PY38_PLUS else 4
- self.assertEqual(strarg.fromlineno, lineno)
- self.assertEqual(strarg.tolineno, lineno)
+ if not PY38_PLUS:
+ self.assertEqual(strarg.fromlineno, 5)
+ else:
+ self.assertEqual(strarg.fromlineno, 4)
+ self.assertEqual(strarg.tolineno, 5)
namearg = callfunc.args[1]
self.assertIsInstance(namearg, nodes.Name)
self.assertEqual(namearg.fromlineno, 5)
diff --git a/tests/unittest_nodes_lineno.py b/tests/unittest_nodes_lineno.py
index 73cf0207cc..0f1b7e4ac7 100644
--- a/tests/unittest_nodes_lineno.py
+++ b/tests/unittest_nodes_lineno.py
@@ -784,7 +784,7 @@ def test_end_lineno_try() -> None:
assert (t3.lineno, t3.col_offset) == (10, 0)
assert (t3.end_lineno, t3.end_col_offset) == (17, 8)
assert (t3.body[0].lineno, t3.body[0].col_offset) == (10, 0)
- assert (t3.body[0].end_lineno, t3.body[0].end_col_offset) == (17, 8)
+ assert (t3.body[0].end_lineno, t3.body[0].end_col_offset) == (15, 8)
assert (t3.finalbody[0].lineno, t3.finalbody[0].col_offset) == (17, 4)
assert (t3.finalbody[0].end_lineno, t3.finalbody[0].end_col_offset) == (17, 8)
diff --git a/tests/unittest_scoped_nodes.py b/tests/unittest_scoped_nodes.py
index 9b2bc291a6..0009278d75 100644
--- a/tests/unittest_scoped_nodes.py
+++ b/tests/unittest_scoped_nodes.py
@@ -1092,15 +1092,19 @@ def g1(x):
print(x)
@f(a=2,
- b=3)
+ b=3,
+ )
def g2():
pass
"""
astroid = builder.parse(data)
self.assertEqual(astroid["g1"].fromlineno, 4)
self.assertEqual(astroid["g1"].tolineno, 5)
- self.assertEqual(astroid["g2"].fromlineno, 9)
- self.assertEqual(astroid["g2"].tolineno, 10)
+ if not PY38_PLUS:
+ self.assertEqual(astroid["g2"].fromlineno, 9)
+ else:
+ self.assertEqual(astroid["g2"].fromlineno, 10)
+ self.assertEqual(astroid["g2"].tolineno, 11)
def test_metaclass_error(self) -> None:
astroid = builder.parse(
|
none
|
[
"tests/unittest_builder.py::FromToLineNoTest::test_callfunc_lineno",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_try",
"tests/unittest_scoped_nodes.py::ClassNodeTest::test_function_with_decorator_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_no_classdict",
"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_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_container",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_name",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_attribute",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_call",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_assignment",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_mix_stmts",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_mix_nodes",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_ops",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_if",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_for",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_const",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_function",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_dict",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_subscript",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_import",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_with",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_while",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_string",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_comprehension",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_class",
"tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_module",
"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_abstract_methods_are_not_implicitly_none",
"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_no_returns_is_implicitly_none",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_only_raises_is_not_implicitly_none",
"tests/unittest_scoped_nodes.py::FunctionNodeTest::test_positional_only_argnames",
"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_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_typing_extensions",
"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_scoped_nodes.py::test_slots_duplicate_bases_issue_1089",
"tests/unittest_scoped_nodes.py::TestFrameNodes::test_frame_node",
"tests/unittest_scoped_nodes.py::TestFrameNodes::test_non_frame_node"
] |
[
". venv/bin/activate && pytest -rA tests"
] |
pytest
|
{
"files": 3,
"hunks": 3,
"lines": 21
}
|
|
How can I learn as begineer
Hi @Keuricloud8866, what do you want to learn ? In order to fix this ticket you should track the place where setuptools and distutils are used in pylint and find an alternative. For finding alternative we'll probably have to discuss how to do what we were doing before without setuptools.
I am new and begineer in software IT world i just jumped in and want to be in so
You should probably check a tutorial about learning programming first. Another useful thing would be to know how to ask question:
- First read the error or documentation
- Second search Google or Stackoverflow
- Third ask for help in the right place
Did you search how to learn programming by yourself first and read a blog about it ? I think you jumped to three and this is not the right place to ask either. This is an issue about a particular issue in a particular software, you were very unlikely to get answers here. (in fact please do not ask other off-topic questions or I'll have to ban you).
Do we still need to dependency on `setuptools` now? It was added in https://github.com/PyCQA/astroid/commit/40629baba2de2c9eb5e11b65798b3fae79f7284a.
Now that we have removed `distutils` I don't think it is necessary, right?
Probably ? I'm trying to think of a way to test that. Maybe launching pylint test suite in a venv after we deinstalled ``setuptools`` ?
Doing #1103 would remove the import time from ``pkg_resources`` and ``distutils`` which are non negligible.
Another possible culprit is the use of `NamedTuple`, see https://lwn.net/Articles/730915/
> Another possible culprit is the use of NamedTuple, see https://lwn.net/Articles/730915/
Thanks for the link, interesting read. Looks like it was optimized in Python 3.7.
By removing `pkg_resources`, https://github.com/PyCQA/astroid/pull/1536 reduces the time to import `astroid` to c.33% of what it was (i.e. 67% reduction) on a slow cloud console and about 50% of what it was on an M1 Mac. I think I will link that PR to close this issue.
|
fb31eede489b45498e65b1921b537f7bd2dd8c9b
|
[
"https://github.com/pylint-dev/astroid/commit/22bca184df3d2fbbfa2f32eab89fbb9ef076d97d",
"https://github.com/pylint-dev/astroid/commit/f53159ea09fc7c7106f4ca321d2ddeaf66938693",
"https://github.com/pylint-dev/astroid/commit/0c536f1a513f4e6666aef17fc1f69192c37e2bf7",
"https://github.com/pylint-dev/astroid/commit/52eb0955e4941b2d0f77540712810402a0827a52",
"https://github.com/pylint-dev/astroid/commit/3175f0d0e80e805fc2b495beca9842ff033ee040",
"https://github.com/pylint-dev/astroid/commit/c8e2764359c1a718e1ce0d0dd9763a46c6a356be",
"https://github.com/pylint-dev/astroid/commit/46a5d2970b36ef0e64500e14447c758e1ce87b87",
"https://github.com/pylint-dev/astroid/commit/cbb47d93e292f83ad0c414a65f59e86fd359447b",
"https://github.com/pylint-dev/astroid/commit/4394f6d2b61322e0d1ec8bb6b81b340ae2d579bc",
"https://github.com/pylint-dev/astroid/commit/ee77bfda4693a75bbafa5ede36a4da6696efdbe2",
"https://github.com/pylint-dev/astroid/commit/d116d52d9b8a144afd0830b511a24268795e0d8d",
"https://github.com/pylint-dev/astroid/commit/2054a5683c685af7cb53a3142f8cd1c29b21e202",
"https://github.com/pylint-dev/astroid/commit/2697e10c07dc8c98fb3871ed4b7fce23e11d0460",
"https://github.com/pylint-dev/astroid/commit/c46e4438d13d4d018651543ba7d4bbdbc2327f09",
"https://github.com/pylint-dev/astroid/commit/6d088abe805d6f60103124b2c207f6687d4f7a53",
"https://github.com/pylint-dev/astroid/commit/7aa7da459e1181167fef1b6f5f0516ce37b83235",
"https://github.com/pylint-dev/astroid/commit/fa6094062099de924f95242f1f1971add0e39f10",
"https://github.com/pylint-dev/astroid/commit/d0b90f48d8bf2e5223649209b3837686f8b1b19a",
"https://github.com/pylint-dev/astroid/commit/f30e100645e4d42e901c31d0a188befb66220cc7",
"https://github.com/pylint-dev/astroid/commit/3dbe761e92bd58fa1466770a815b27a8f011b670",
"https://github.com/pylint-dev/astroid/commit/d92c48eccf48ea7e50cb8696e2746a2070bdbc1d",
"https://github.com/pylint-dev/astroid/commit/01b00a26380adadb9c37a0ca606d807883bd3455"
] | 2022-05-01T14:27:44
|
How can I learn as begineer
Hi @Keuricloud8866, what do you want to learn ? In order to fix this ticket you should track the place where setuptools and distutils are used in pylint and find an alternative. For finding alternative we'll probably have to discuss how to do what we were doing before without setuptools.
I am new and begineer in software IT world i just jumped in and want to be in so
You should probably check a tutorial about learning programming first. Another useful thing would be to know how to ask question:
- First read the error or documentation
- Second search Google or Stackoverflow
- Third ask for help in the right place
Did you search how to learn programming by yourself first and read a blog about it ? I think you jumped to three and this is not the right place to ask either. This is an issue about a particular issue in a particular software, you were very unlikely to get answers here. (in fact please do not ask other off-topic questions or I'll have to ban you).
Do we still need to dependency on `setuptools` now? It was added in https://github.com/PyCQA/astroid/commit/40629baba2de2c9eb5e11b65798b3fae79f7284a.
Now that we have removed `distutils` I don't think it is necessary, right?
Probably ? I'm trying to think of a way to test that. Maybe launching pylint test suite in a venv after we deinstalled ``setuptools`` ?
Doing #1103 would remove the import time from ``pkg_resources`` and ``distutils`` which are non negligible.
Another possible culprit is the use of `NamedTuple`, see https://lwn.net/Articles/730915/
|
pylint-dev__astroid-1536
|
[
"1103",
"1320"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index bd6ed51cda..06a7163ff6 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -15,6 +15,10 @@ Release date: TBA
Closes #1512
+* Remove dependency on ``pkg_resources`` from ``setuptools``.
+
+ Closes #1103
+
* Allowed ``AstroidManager.clear_cache`` to reload necessary brain plugins.
* Rename ``ModuleSpec`` -> ``module_type`` constructor parameter to match attribute
diff --git a/astroid/interpreter/_import/spec.py b/astroid/interpreter/_import/spec.py
index c0601613d9..74a0e8081f 100644
--- a/astroid/interpreter/_import/spec.py
+++ b/astroid/interpreter/_import/spec.py
@@ -10,6 +10,7 @@
import importlib.machinery
import importlib.util
import os
+import pathlib
import sys
import zipimport
from collections.abc import Sequence
@@ -147,7 +148,7 @@ def contribute_to_path(self, spec, processed):
# Builtin.
return None
- if _is_setuptools_namespace(spec.location):
+ if _is_setuptools_namespace(Path(spec.location)):
# extend_path is called, search sys.path for module/packages
# of this name see pkgutil.extend_path documentation
path = [
@@ -179,7 +180,7 @@ def contribute_to_path(self, spec, processed):
class ExplicitNamespacePackageFinder(ImportlibFinder):
- """A finder for the explicit namespace packages, generated through pkg_resources."""
+ """A finder for the explicit namespace packages."""
def find_module(self, modname, module_parts, processed, submodule_path):
if processed:
@@ -256,12 +257,12 @@ def contribute_to_path(self, spec, processed):
)
-def _is_setuptools_namespace(location):
+def _is_setuptools_namespace(location: pathlib.Path) -> bool:
try:
- with open(os.path.join(location, "__init__.py"), "rb") as stream:
+ with open(location / "__init__.py", "rb") as stream:
data = stream.read(4096)
except OSError:
- return None
+ return False
else:
extend_path = b"pkgutil" in data and b"extend_path" in data
declare_namespace = (
diff --git a/astroid/interpreter/_import/util.py b/astroid/interpreter/_import/util.py
index ce3da7eac2..53c6922c33 100644
--- a/astroid/interpreter/_import/util.py
+++ b/astroid/interpreter/_import/util.py
@@ -2,15 +2,35 @@
# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
-try:
- import pkg_resources
-except ImportError:
- pkg_resources = None # type: ignore[assignment]
+import sys
+from functools import lru_cache
+from importlib.util import _find_spec_from_path
-def is_namespace(modname):
- return (
- pkg_resources is not None
- and hasattr(pkg_resources, "_namespace_packages")
- and modname in pkg_resources._namespace_packages
- )
+@lru_cache(maxsize=4096)
+def is_namespace(modname: str) -> bool:
+ if modname in sys.builtin_module_names:
+ return False
+
+ found_spec = None
+
+ # find_spec() attempts to import parent packages when given dotted paths.
+ # That's unacceptable here, so we fallback to _find_spec_from_path(), which does
+ # not, but requires instead that each single parent ('astroid', 'nodes', etc.)
+ # be specced from left to right.
+ processed_components = []
+ last_parent = None
+ for component in modname.split("."):
+ processed_components.append(component)
+ working_modname = ".".join(processed_components)
+ try:
+ found_spec = _find_spec_from_path(working_modname, last_parent)
+ except ValueError:
+ # executed .pth files may not have __spec__
+ return True
+ last_parent = working_modname
+
+ if found_spec is None:
+ return False
+
+ return found_spec.origin is None
diff --git a/astroid/manager.py b/astroid/manager.py
index 23330d5b95..6e7dcf4cdf 100644
--- a/astroid/manager.py
+++ b/astroid/manager.py
@@ -17,7 +17,7 @@
from astroid.const import BRAIN_MODULES_DIRECTORY
from astroid.exceptions import AstroidBuildingError, AstroidImportError
-from astroid.interpreter._import import spec
+from astroid.interpreter._import import spec, util
from astroid.modutils import (
NoSourceFile,
_cache_normalize_path_,
@@ -382,6 +382,7 @@ def clear_cache(self) -> None:
for lru_cache in (
LookupMixIn.lookup,
_cache_normalize_path_,
+ util.is_namespace,
ObjectModel.attributes,
):
lru_cache.cache_clear()
diff --git a/setup.cfg b/setup.cfg
index fa7c436e00..1e2341a882 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -39,7 +39,6 @@ packages = find:
install_requires =
lazy_object_proxy>=1.4.0
wrapt>=1.11,<2
- setuptools>=20.0
typed-ast>=1.4.0,<2.0;implementation_name=="cpython" and python_version<"3.8"
typing-extensions>=3.10;python_version<"3.10"
python_requires = >=3.7.2
|
Remove dependency to ``setuptools`` and ``distutil``
As see in #1030 and #1100 there is a hidden dependency to setuptools (and probably distutils too), we made it explicit in #1100 but the better thing to do would be to remove it entirely if possible.
Decrease the time required to import astroid
### Steps to reproduce
``python3 -X importtime -c 'import astroid'``
### Current behavior
It takes a half second to import astroid. This account for 92% of pylint's startup time in 2.13.0-dev0. See https://github.com/PyCQA/pylint/issues/4814 for details.
```
import time: self [us] | cumulative | imported package
import time: 182 | 182 | _io
import time: 59 | 59 | marshal
import time: 213 | 213 | posix
import time: 463 | 916 | _frozen_importlib_external
import time: 143 | 143 | time
import time: 210 | 353 | zipimport
import time: 68 | 68 | _codecs
import time: 8157 | 8225 | codecs
import time: 4532 | 4532 | encodings.aliases
import time: 2092 | 14848 | encodings
import time: 526 | 526 | encodings.utf_8
import time: 183 | 183 | _signal
import time: 910 | 910 | encodings.latin_1
import time: 34 | 34 | _abc
import time: 527 | 560 | abc
import time: 539 | 1099 | io
import time: 43 | 43 | _stat
import time: 522 | 564 | stat
import time: 1066 | 1066 | _collections_abc
import time: 459 | 459 | genericpath
import time: 481 | 939 | posixpath
import time: 781 | 3349 | os
import time: 451 | 451 | _sitebuiltins
import time: 57 | 57 | _locale
import time: 411 | 467 | _bootlocale
import time: 1220 | 1220 | apport_python_hook
import time: 396 | 1615 | sitecustomize
import time: 4927 | 10808 | site
import time: 989 | 989 | types
import time: 833 | 833 | warnings
import time: 1833 | 3654 | importlib
import time: 954 | 954 | enum
import time: 58 | 58 | _sre
import time: 560 | 560 | sre_constants
import time: 1033 | 1593 | sre_parse
import time: 788 | 2437 | sre_compile
import time: 58 | 58 | _operator
import time: 1129 | 1187 | operator
import time: 424 | 424 | keyword
import time: 34 | 34 | _heapq
import time: 499 | 533 | heapq
import time: 85 | 85 | itertools
import time: 496 | 496 | reprlib
import time: 47 | 47 | _collections
import time: 1360 | 4129 | collections
import time: 37 | 37 | _functools
import time: 3949 | 8114 | functools
import time: 451 | 451 | copyreg
import time: 751 | 12704 | re
import time: 547 | 13251 | fnmatch
import time: 70 | 70 | nt
import time: 49 | 49 | nt
import time: 46 | 46 | nt
import time: 46 | 46 | nt
import time: 608 | 817 | ntpath
import time: 47 | 47 | errno
import time: 734 | 734 | urllib
import time: 1519 | 2253 | urllib.parse
import time: 3700 | 20066 | pathlib
import time: 1277 | 1277 | astroid.__pkginfo__
import time: 423 | 423 | collections.abc
import time: 704 | 704 | contextlib
import time: 1683 | 2809 | typing
import time: 127 | 127 | _opcode
import time: 619 | 745 | opcode
import time: 744 | 1488 | dis
import time: 442 | 442 | importlib.machinery
import time: 480 | 480 | token
import time: 1048 | 1527 | tokenize
import time: 389 | 1915 | linecache
import time: 1941 | 5784 | inspect
import time: 518 | 518 | _weakrefset
import time: 873 | 1390 | weakref
import time: 1384 | 1384 | wrapt._wrappers
import time: 6921 | 9695 | wrapt.wrappers
import time: 1350 | 1350 | threading
import time: 1461 | 2811 | wrapt.decorators
import time: 1089 | 1089 | wrapt.importer
import time: 2134 | 15727 | wrapt
import time: 77 | 77 | copy_reg
import time: 449 | 449 | lazy_object_proxy.utils_py3
import time: 550 | 999 | lazy_object_proxy.utils
import time: 1466 | 1466 | lazy_object_proxy.cext
import time: 572 | 572 | lazy_object_proxy._version
import time: 4391 | 7503 | lazy_object_proxy
import time: 687 | 8190 | astroid.util
import time: 635 | 635 | pprint
import time: 2008 | 2643 | astroid.context
import time: 1714 | 1714 | astroid.exceptions
import time: 7641 | 7641 | typing_extensions
import time: 616 | 42312 | astroid.decorators
import time: 594 | 594 | astroid.mixins
import time: 1371 | 1371 | astroid.const
import time: 1881 | 1881 | astroid.interpreter._import
import time: 1275 | 1275 | distutils
import time: 385 | 385 | __future__
import time: 68 | 68 | binascii
import time: 631 | 631 | importlib.abc
import time: 503 | 1133 | importlib.util
import time: 66 | 66 | zlib
import time: 367 | 367 | _compression
import time: 251 | 251 | _bz2
import time: 485 | 1103 | bz2
import time: 217 | 217 | _lzma
import time: 431 | 647 | lzma
import time: 36 | 36 | pwd
import time: 26 | 26 | grp
import time: 1033 | 2908 | shutil
import time: 66 | 66 | _struct
import time: 337 | 402 | struct
import time: 1019 | 5528 | zipfile
import time: 599 | 599 | pkgutil
import time: 1913 | 1913 | platform
import time: 53 | 53 | math
import time: 120 | 120 | _datetime
import time: 1114 | 1286 | datetime
import time: 1129 | 1129 | xml
import time: 1078 | 2206 | xml.parsers
import time: 107 | 107 | pyexpat
import time: 431 | 2744 | xml.parsers.expat
import time: 1234 | 5263 | plistlib
import time: 578 | 578 | email
import time: 674 | 674 | email.errors
import time: 36 | 36 | _string
import time: 843 | 878 | string
import time: 465 | 1343 | email.quoprimime
import time: 524 | 524 | base64
import time: 402 | 925 | email.base64mime
import time: 451 | 451 | quopri
import time: 418 | 869 | email.encoders
import time: 874 | 1743 | email.charset
import time: 950 | 4960 | email.header
import time: 34 | 34 | _bisect
import time: 424 | 457 | bisect
import time: 27 | 27 | _sha512
import time: 22 | 22 | _random
import time: 616 | 1122 | random
import time: 136 | 136 | _socket
import time: 617 | 617 | select
import time: 885 | 1501 | selectors
import time: 1593 | 3229 | socket
import time: 1011 | 1011 | locale
import time: 919 | 1929 | calendar
import time: 557 | 2485 | email._parseaddr
import time: 813 | 7647 | email.utils
import time: 561 | 13167 | email._policybase
import time: 945 | 14785 | email.feedparser
import time: 8210 | 23572 | email.parser
import time: 721 | 721 | tempfile
import time: 1194 | 1194 | textwrap
import time: 6297 | 6297 | pkg_resources.extern
import time: 1130 | 1130 | pkg_resources._vendor
import time: 1168 | 2297 | pkg_resources._vendor.six
import time: 149 | 2446 | pkg_resources.extern.six
import time: 560 | 560 | pkg_resources._vendor.six
import time: 70 | 629 | pkg_resources._vendor.six.moves
import time: 56 | 685 | pkg_resources.extern.six.moves
import time: 20 | 20 | pkg_resources._vendor.six.moves
import time: 50 | 69 | pkg_resources._vendor.six.moves.urllib
import time: 461 | 461 | pkg_resources.py31compat
import time: 910 | 910 | pkg_resources._vendor.appdirs
import time: 81 | 990 | pkg_resources.extern.appdirs
import time: 436 | 436 | pkg_resources._vendor.packaging.__about__
import time: 3589 | 4025 | pkg_resources._vendor.packaging
import time: 72 | 4097 | pkg_resources.extern.packaging
import time: 378 | 378 | pkg_resources.extern.packaging._structures
import time: 2111 | 2489 | pkg_resources.extern.packaging.version
import time: 379 | 379 | pkg_resources.extern.packaging._compat
import time: 6610 | 6989 | pkg_resources.extern.packaging.specifiers
import time: 74 | 74 | org
import time: 17 | 90 | org.python
import time: 13 | 103 | org.python.core
import time: 539 | 641 | copy
import time: 1431 | 1431 | traceback
import time: 27210 | 29281 | pkg_resources._vendor.pyparsing
import time: 107 | 29388 | pkg_resources.extern.pyparsing
import time: 42 | 42 | pkg_resources.extern.six.moves.urllib
import time: 1463 | 1463 | pkg_resources.extern.packaging.markers
import time: 8461 | 39353 | pkg_resources.extern.packaging.requirements
import time: 4606 | 4606 | sysconfig
import time: 52302 | 159948 | pkg_resources
import time: 338 | 160286 | astroid.interpreter._import.util
import time: 1009 | 162569 | astroid.interpreter._import.spec
import time: 614 | 614 | distutils.errors
import time: 426 | 426 | distutils.dep_util
import time: 355 | 355 | distutils.debug
import time: 504 | 504 | distutils.log
import time: 548 | 1406 | distutils.spawn
import time: 559 | 2391 | distutils.util
import time: 889 | 3280 | distutils.sysconfig
import time: 854 | 4746 | astroid.modutils
import time: 463 | 463 | astroid.transforms
import time: 3030 | 172688 | astroid.manager
import time: 4830 | 178888 | astroid.bases
import time: 8974 | 8974 | astroid.nodes.const
import time: 737 | 737 | astroid.nodes.as_string
import time: 1306 | 2042 | astroid.nodes.node_ng
import time: 5136 | 240752 | astroid.nodes.node_classes
import time: 467 | 467 | astroid.interpreter.dunder_lookup
import time: 1416 | 1883 | astroid.nodes.scoped_nodes
import time: 4791 | 247424 | astroid.nodes
import time: 57 | 57 | _ast
import time: 764 | 820 | ast
import time: 177912 | 177912 | astroid.raw_building
import time: 656 | 178567 | astroid.helpers
import time: 569 | 569 | astroid.arguments
import time: 972 | 1541 | astroid.protocols
import time: 1415 | 182342 | astroid.inference
import time: 1575 | 1575 | astroid.astroid_manager
import time: 1293 | 1293 | astroid.brain
import time: 712 | 2005 | astroid.brain.helpers
import time: 76 | 76 | typed_ast
import time: 53 | 128 | typed_ast.ast3
import time: 655 | 783 | astroid._ast
import time: 1616 | 2399 | astroid.rebuilder
import time: 561 | 2959 | astroid.builder
import time: 355 | 355 | astroid.inference_tip
import time: 701 | 701 | astroid.objects
import time: 305 | 305 | astroid.brain.brain_numpy_utils
import time: 46840 | 509498 | astroid
```
### Expected behavior
Faster import, so pylint's can analyses empty file in less than half a second.
|
1536
|
pylint-dev/astroid
|
diff --git a/tests/unittest_manager.py b/tests/unittest_manager.py
index cd63950ea2..6c105a12bb 100644
--- a/tests/unittest_manager.py
+++ b/tests/unittest_manager.py
@@ -10,12 +10,11 @@
from collections.abc import Iterator
from contextlib import contextmanager
-import pkg_resources
-
import astroid
from astroid import manager, test_utils
from astroid.const import IS_JYTHON
from astroid.exceptions import AstroidBuildingError, AstroidImportError
+from astroid.interpreter._import import util
from astroid.modutils import is_standard_module
from astroid.nodes import Const
from astroid.nodes.scoped_nodes import ClassDef
@@ -111,6 +110,16 @@ def test_ast_from_namespace_pkgutil(self) -> None:
def test_ast_from_namespace_pkg_resources(self) -> None:
self._test_ast_from_old_namespace_package_protocol("pkg_resources")
+ def test_identify_old_namespace_package_protocol(self) -> None:
+ # Like the above cases, this package follows the old namespace package protocol
+ # astroid currently assumes such packages are in sys.modules, so import it
+ # pylint: disable-next=import-outside-toplevel
+ import tests.testdata.python3.data.path_pkg_resources_1.package.foo as _ # noqa
+
+ self.assertTrue(
+ util.is_namespace("tests.testdata.python3.data.path_pkg_resources_1")
+ )
+
def test_implicit_namespace_package(self) -> None:
data_dir = os.path.dirname(resources.find("data/namespace_pep_420"))
contribute = os.path.join(data_dir, "contribute_to_namespace")
@@ -131,7 +140,6 @@ def test_implicit_namespace_package(self) -> None:
def test_namespace_package_pth_support(self) -> None:
pth = "foogle_fax-0.12.5-py2.7-nspkg.pth"
site.addpackage(resources.RESOURCE_PATH, pth, [])
- pkg_resources._namespace_packages["foogle"] = []
try:
module = self.manager.ast_from_module_name("foogle.fax")
@@ -141,18 +149,14 @@ def test_namespace_package_pth_support(self) -> None:
with self.assertRaises(AstroidImportError):
self.manager.ast_from_module_name("foogle.moogle")
finally:
- del pkg_resources._namespace_packages["foogle"]
sys.modules.pop("foogle")
def test_nested_namespace_import(self) -> None:
pth = "foogle_fax-0.12.5-py2.7-nspkg.pth"
site.addpackage(resources.RESOURCE_PATH, pth, [])
- pkg_resources._namespace_packages["foogle"] = ["foogle.crank"]
- pkg_resources._namespace_packages["foogle.crank"] = []
try:
self.manager.ast_from_module_name("foogle.crank")
finally:
- del pkg_resources._namespace_packages["foogle"]
sys.modules.pop("foogle")
def test_namespace_and_file_mismatch(self) -> None:
@@ -161,12 +165,10 @@ def test_namespace_and_file_mismatch(self) -> None:
self.assertEqual(ast.name, "unittest")
pth = "foogle_fax-0.12.5-py2.7-nspkg.pth"
site.addpackage(resources.RESOURCE_PATH, pth, [])
- pkg_resources._namespace_packages["foogle"] = []
try:
with self.assertRaises(AstroidImportError):
self.manager.ast_from_module_name("unittest.foogle.fax")
finally:
- del pkg_resources._namespace_packages["foogle"]
sys.modules.pop("foogle")
def _test_ast_from_zip(self, archive: str) -> None:
@@ -323,6 +325,7 @@ def test_clear_cache_clears_other_lru_caches(self) -> None:
lrus = (
astroid.nodes.node_classes.LookupMixIn.lookup,
astroid.modutils._cache_normalize_path_,
+ util.is_namespace,
astroid.interpreter.objectmodel.ObjectModel.attributes,
)
@@ -332,6 +335,7 @@ def test_clear_cache_clears_other_lru_caches(self) -> None:
# Generate some hits and misses
ClassDef().lookup("garbage")
is_standard_module("unittest", std_path=["garbage_path"])
+ util.is_namespace("unittest")
astroid.interpreter.objectmodel.ObjectModel().attributes()
# Did the hits or misses actually happen?
|
none
|
[
"tests/unittest_manager.py::AstroidManagerTest::test_namespace_package_pth_support",
"tests/unittest_manager.py::AstroidManagerTest::test_nested_namespace_import",
"tests/unittest_manager.py::ClearCacheTest::test_clear_cache_clears_other_lru_caches"
] |
[
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_class",
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_class_attr_error",
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_class_with_module",
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_file",
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_file_astro_builder",
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_file_cache",
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_file_name_astro_builder_exception",
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_module",
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_module_cache",
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_module_name",
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_module_name_astro_builder_exception",
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_module_name_egg",
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_module_name_not_python_source",
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_module_name_pyz",
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_module_name_zip",
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_namespace_pkg_resources",
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_namespace_pkgutil",
"tests/unittest_manager.py::AstroidManagerTest::test_ast_from_string",
"tests/unittest_manager.py::AstroidManagerTest::test_do_not_expose_main",
"tests/unittest_manager.py::AstroidManagerTest::test_failed_import_hooks",
"tests/unittest_manager.py::AstroidManagerTest::test_file_from_module",
"tests/unittest_manager.py::AstroidManagerTest::test_file_from_module_name_astro_building_exception",
"tests/unittest_manager.py::AstroidManagerTest::test_identify_old_namespace_package_protocol",
"tests/unittest_manager.py::AstroidManagerTest::test_implicit_namespace_package",
"tests/unittest_manager.py::AstroidManagerTest::test_namespace_and_file_mismatch",
"tests/unittest_manager.py::AstroidManagerTest::test_zip_import_data",
"tests/unittest_manager.py::AstroidManagerTest::test_zip_import_data_without_zipimport",
"tests/unittest_manager.py::BorgAstroidManagerTC::test_borg",
"tests/unittest_manager.py::ClearCacheTest::test_brain_plugins_reloaded_after_clearing_cache"
] |
[
"pytest -rA tests/"
] |
pytest
|
{
"files": 5,
"hunks": 9,
"lines": 59
}
|
I can't seem to reproduce this in my `virtualenv`. This might be specific to `venv`? Needs some further investigation.
@interifter Which version of `pylint` are you using?
Right, ``pip install pylint astroid==2.9.0``, will keep the local version if you already have one, so I thought it was ``2.12.2`` but that could be false. In fact it probably isn't 2.12.2. For the record, you're not supposed to set the version of ``astroid`` yourself, pylint does, and bad thing will happen if you try to set the version of an incompatible astroid. We might want to update the issue's template to have this information next.
My apologies... I updated the repro steps with a critical missed detail: `pylint src/project`, instead of `pylint src`
But I verified that either with, or without, `venv`, the issue is reproduced.
Also, I never have specified the `astroid` version, before.
However, this isn't the first time the issue has been observed.
Back in early 2019, a [similar issue](https://stackoverflow.com/questions/48024049/pylint-raises-error-if-directory-doesnt-contain-init-py-file) was observed with either `astroid 2.2.0` or `isort 4.3.5`, which led me to try pinning `astroid==2.9.0`, which worked.
> @interifter Which version of `pylint` are you using?
`2.12.2`
Full env info:
```
Package Version
----------------- -------
astroid 2.9.2
colorama 0.4.4
isort 5.10.1
lazy-object-proxy 1.7.1
mccabe 0.6.1
pip 20.2.3
platformdirs 2.4.1
pylint 2.12.2
setuptools 49.2.1
toml 0.10.2
typing-extensions 4.0.1
wrapt 1.13.3
```
I confirm the bug and i'm able to reproduce it with `python 3.9.1`.
```
$> pip freeze
astroid==2.9.2
isort==5.10.1
lazy-object-proxy==1.7.1
mccabe==0.6.1
platformdirs==2.4.1
pylint==2.12.2
toml==0.10.2
typing-extensions==4.0.1
wrapt==1.13.3
```
Bisected and this is the faulty commit:
https://github.com/PyCQA/astroid/commit/2ee20ccdf62450db611acc4a1a7e42f407ce8a14
Fix in #1333, no time to write tests yet so if somebody has any good ideas: please let me know!
@interifter Fixed and released with `2.9.3`. Thanks for the report and reproducible example. Not sure why I couldn't reproduce this to begin with.
@DanielNoord I had the incorrect steps to reproduce when I initially filed the bug, so that likely would prevent you, or anyone else, from being able to :)
|
d2a5b3c7b1e203fec3c7ca73c30eb1785d3d4d0a
|
[
"https://github.com/pylint-dev/astroid/commit/3661e1264643a27293e31cd6760ade8dc7b6d920",
"https://github.com/pylint-dev/astroid/commit/b19b115d4549569700c395500653ff83cc894f88"
] | 2022-01-08T19:36:45
|
I can't seem to reproduce this in my `virtualenv`. This might be specific to `venv`? Needs some further investigation.
@interifter Which version of `pylint` are you using?
Right, ``pip install pylint astroid==2.9.0``, will keep the local version if you already have one, so I thought it was ``2.12.2`` but that could be false. In fact it probably isn't 2.12.2. For the record, you're not supposed to set the version of ``astroid`` yourself, pylint does, and bad thing will happen if you try to set the version of an incompatible astroid. We might want to update the issue's template to have this information next.
My apologies... I updated the repro steps with a critical missed detail: `pylint src/project`, instead of `pylint src`
But I verified that either with, or without, `venv`, the issue is reproduced.
Also, I never have specified the `astroid` version, before.
However, this isn't the first time the issue has been observed.
Back in early 2019, a [similar issue](https://stackoverflow.com/questions/48024049/pylint-raises-error-if-directory-doesnt-contain-init-py-file) was observed with either `astroid 2.2.0` or `isort 4.3.5`, which led me to try pinning `astroid==2.9.0`, which worked.
> @interifter Which version of `pylint` are you using?
`2.12.2`
Full env info:
```
Package Version
----------------- -------
astroid 2.9.2
colorama 0.4.4
isort 5.10.1
lazy-object-proxy 1.7.1
mccabe 0.6.1
pip 20.2.3
platformdirs 2.4.1
pylint 2.12.2
setuptools 49.2.1
toml 0.10.2
typing-extensions 4.0.1
wrapt 1.13.3
```
|
pylint-dev__astroid-1333
|
[
"1327"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index 6c56d234f9..783391c360 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -7,6 +7,14 @@ What's New in astroid 2.10.0?
Release date: TBA
+What's New in astroid 2.9.3?
+============================
+Release date: TBA
+
+* Fixed regression where packages without a ``__init__.py`` file were
+ not recognized or imported correctly.
+
+ Closes #1327
What's New in astroid 2.9.2?
============================
diff --git a/astroid/modutils.py b/astroid/modutils.py
index 6d69846925..b20a184021 100644
--- a/astroid/modutils.py
+++ b/astroid/modutils.py
@@ -297,6 +297,9 @@ def _get_relative_base_path(filename, path_to_check):
if os.path.normcase(real_filename).startswith(path_to_check):
importable_path = real_filename
+ # if "var" in path_to_check:
+ # breakpoint()
+
if importable_path:
base_path = os.path.splitext(importable_path)[0]
relative_base_path = base_path[len(path_to_check) :]
@@ -307,8 +310,11 @@ def _get_relative_base_path(filename, path_to_check):
def modpath_from_file_with_callback(filename, path=None, is_package_cb=None):
filename = os.path.expanduser(_path_from_filename(filename))
+ paths_to_check = sys.path.copy()
+ if path:
+ paths_to_check += path
for pathname in itertools.chain(
- path or [], map(_cache_normalize_path, sys.path), sys.path
+ paths_to_check, map(_cache_normalize_path, paths_to_check)
):
if not pathname:
continue
|
astroid 2.9.1 breaks pylint with missing __init__.py: F0010: error while code parsing: Unable to load file __init__.py
### Steps to reproduce
> Steps provided are for Windows 11, but initial problem found in Ubuntu 20.04
> Update 2022-01-04: Corrected repro steps and added more environment details
1. Set up simple repo with following structure (all files can be empty):
```
root_dir/
|--src/
|----project/ # Notice the missing __init__.py
|------file.py # It can be empty, but I added `import os` at the top
|----__init__.py
```
2. Open a command prompt
3. `cd root_dir`
4. `python -m venv venv`
5. `venv/Scripts/activate`
6. `pip install pylint astroid==2.9.1` # I also repro'd on the latest, 2.9.2
7. `pylint src/project` # Updated from `pylint src`
8. Observe failure:
```
src\project\__init__.py:1:0: F0010: error while code parsing: Unable to load file src\project\__init__.py:
```
### Current behavior
Fails with `src\project\__init__.py:1:0: F0010: error while code parsing: Unable to load file src\project\__init__.py:`
### Expected behavior
Does not fail with error.
> If you replace step 6 with `pip install pylint astroid==2.9.0`, you get no failure with an empty output - since no files have content
### `python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"` output
2.9.1
`python 3.9.1`
`pylint 2.12.2 `
This issue has been observed with astroid `2.9.1` and `2.9.2`
|
1333
|
pylint-dev/astroid
|
diff --git a/tests/unittest_modutils.py b/tests/unittest_modutils.py
index d6fcb68e25..01d5e5b91e 100644
--- a/tests/unittest_modutils.py
+++ b/tests/unittest_modutils.py
@@ -30,6 +30,7 @@
import tempfile
import unittest
import xml
+from pathlib import Path
from xml import etree
from xml.etree import ElementTree
@@ -189,6 +190,30 @@ def test_load_from_module_symlink_on_symlinked_paths_in_syspath(self) -> None:
# this should be equivalent to: import secret
self.assertEqual(modutils.modpath_from_file(symlink_secret_path), ["secret"])
+ def test_load_packages_without_init(self) -> None:
+ """Test that we correctly find packages with an __init__.py file.
+
+ Regression test for issue reported in:
+ https://github.com/PyCQA/astroid/issues/1327
+ """
+ tmp_dir = Path(tempfile.gettempdir())
+ self.addCleanup(os.chdir, os.curdir)
+ os.chdir(tmp_dir)
+
+ self.addCleanup(shutil.rmtree, tmp_dir / "src")
+ os.mkdir(tmp_dir / "src")
+ os.mkdir(tmp_dir / "src" / "package")
+ with open(tmp_dir / "src" / "__init__.py", "w", encoding="utf-8"):
+ pass
+ with open(tmp_dir / "src" / "package" / "file.py", "w", encoding="utf-8"):
+ pass
+
+ # this should be equivalent to: import secret
+ self.assertEqual(
+ modutils.modpath_from_file(str(Path("src") / "package"), ["."]),
+ ["src", "package"],
+ )
+
class LoadModuleFromPathTest(resources.SysPathSetup, unittest.TestCase):
def test_do_not_load_twice(self) -> None:
|
none
|
[
"tests/unittest_modutils.py::ModPathFromFileTest::test_load_packages_without_init"
] |
[
"tests/unittest_modutils.py::ModuleFileTest::test_find_egg_module",
"tests/unittest_modutils.py::ModuleFileTest::test_find_zipped_module",
"tests/unittest_modutils.py::LoadModuleFromNameTest::test_known_values_load_module_from_name_1",
"tests/unittest_modutils.py::LoadModuleFromNameTest::test_known_values_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_known_values_get_builtin_module_part",
"tests/unittest_modutils.py::GetModulePartTest::test_known_values_get_compiled_module_part",
"tests/unittest_modutils.py::GetModulePartTest::test_known_values_get_module_part_1",
"tests/unittest_modutils.py::GetModulePartTest::test_known_values_get_module_part_2",
"tests/unittest_modutils.py::GetModulePartTest::test_known_values_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_known_values_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_known_values_is_relative_1",
"tests/unittest_modutils.py::IsRelativeTest::test_known_values_is_relative_3",
"tests/unittest_modutils.py::IsRelativeTest::test_known_values_is_relative_4",
"tests/unittest_modutils.py::IsRelativeTest::test_known_values_is_relative_5",
"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",
"tests/unittest_modutils.py::ExtensionPackageWhitelistTest::test_is_module_name_part_of_extension_package_whitelist_success",
"tests/unittest_modutils.py::ExtensionPackageWhitelistTest::test_is_module_name_part_of_extension_package_whitelist_true"
] |
[
"pytest -rA tests"
] |
pytest
|
{
"files": 2,
"hunks": 3,
"lines": 16
}
|
@cdce8p thanks for pointing this out. I'm on it, hope to get up a PR soon.
|
02a4c266534fb473da07ea5b905726281d06cbde
|
[
"https://github.com/pylint-dev/astroid/commit/c6150a4f080bbf6c0cdc3891b9c46cda75340ced",
"https://github.com/pylint-dev/astroid/commit/cf5e941983a62a9c87e1081658f38adc29c60a69"
] | 2021-08-16T14:36:35
|
pylint-dev__astroid-1130
|
[
"1129"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index f0cc1df31e..615941fb66 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -12,8 +12,13 @@ What's New in astroid 2.7.1?
============================
Release date: TBA
+* When processing dataclass attributes, only do typing inference on collection types.
+ Support for instantiating other typing types is left for the future, if desired.
+
+
* Fixed LookupMixIn missing from ``astroid.node_classes``.
+ Closes #1129
What's New in astroid 2.7.0?
diff --git a/astroid/brain/brain_dataclasses.py b/astroid/brain/brain_dataclasses.py
index f42c981cad..b4be357fc9 100644
--- a/astroid/brain/brain_dataclasses.py
+++ b/astroid/brain/brain_dataclasses.py
@@ -97,16 +97,7 @@ def infer_dataclass_attribute(
if value is not None:
yield from value.infer(context=ctx)
if annotation is not None:
- klass = None
- try:
- klass = next(annotation.infer())
- except (InferenceError, StopIteration):
- yield Uninferable
-
- if not isinstance(klass, ClassDef):
- yield Uninferable
- else:
- yield klass.instantiate_class()
+ yield from _infer_instance_from_annotation(annotation, ctx=ctx)
else:
yield Uninferable
@@ -229,6 +220,44 @@ def _is_init_var(node: NodeNG) -> bool:
return getattr(inferred, "name", "") == "InitVar"
+# Allowed typing classes for which we support inferring instances
+_INFERABLE_TYPING_TYPES = frozenset(
+ (
+ "Dict",
+ "FrozenSet",
+ "List",
+ "Set",
+ "Tuple",
+ )
+)
+
+
+def _infer_instance_from_annotation(
+ node: NodeNG, ctx: context.InferenceContext = None
+) -> Generator:
+ """Infer an instance corresponding to the type annotation represented by node.
+
+ Currently has limited support for the typing module.
+ """
+ klass = None
+ try:
+ klass = next(node.infer(context=ctx))
+ except (InferenceError, StopIteration):
+ yield Uninferable
+ if not isinstance(klass, ClassDef):
+ yield Uninferable
+ elif klass.root().name in (
+ "typing",
+ "",
+ ): # "" because of synthetic nodes in brain_typing.py
+ if klass.name in _INFERABLE_TYPING_TYPES:
+ yield klass.instantiate_class()
+ else:
+ yield Uninferable
+ else:
+ yield klass.instantiate_class()
+
+
if PY37_PLUS:
AstroidManager().register_transform(
ClassDef, dataclass_transform, is_decorated_with_dataclass
|
Regression with dataclass inference
### Steps to reproduce
```py
from dataclasses import dataclass
from typing import Any, Callable
@dataclass
class A:
enabled: Callable[[Any], bool]
instance = A(lambda x: x == 42)
instance.enabled(2) # not-callable
```
### Current behavior
```
************* Module test
test.py:9:0: E1102: instance.enabled is not callable (not-callable)
```
### Expected behavior
No error
### Additional information
Tested with astroid `v2.7.0`.
The issue seems to be a direct result of #1126
/CC: @david-yz-liu @Pierre-Sassoulas
|
1130
|
pylint-dev/astroid
|
diff --git a/tests/unittest_brain_dataclasses.py b/tests/unittest_brain_dataclasses.py
index f7b08747f0..f90893d5cd 100644
--- a/tests/unittest_brain_dataclasses.py
+++ b/tests/unittest_brain_dataclasses.py
@@ -4,6 +4,7 @@
from astroid import bases, nodes
from astroid.const import PY37_PLUS
from astroid.exceptions import InferenceError
+from astroid.util import Uninferable
if not PY37_PLUS:
pytest.skip("Dataclasses were added in 3.7", allow_module_level=True)
@@ -235,3 +236,62 @@ class A:
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const)
assert inferred[0].value == "hi"
+
+
+def test_inference_generic_collection_attribute():
+ """Test that an attribute with a generic collection type from the
+ typing module is inferred correctly.
+ """
+ attr_nodes = astroid.extract_node(
+ """
+ from dataclasses import dataclass, field
+ import typing
+
+ @dataclass
+ class A:
+ dict_prop: typing.Dict[str, str]
+ frozenset_prop: typing.FrozenSet[str]
+ list_prop: typing.List[str]
+ set_prop: typing.Set[str]
+ tuple_prop: typing.Tuple[int, str]
+
+ a = A({}, frozenset(), [], set(), (1, 'hi'))
+ a.dict_prop #@
+ a.frozenset_prop #@
+ a.list_prop #@
+ a.set_prop #@
+ a.tuple_prop #@
+ """
+ )
+ names = (
+ "Dict",
+ "FrozenSet",
+ "List",
+ "Set",
+ "Tuple",
+ )
+ for node, name in zip(attr_nodes, names):
+ inferred = next(node.infer())
+ assert isinstance(inferred, bases.Instance)
+ assert inferred.name == name
+
+
+def test_inference_callable_attribute():
+ """Test that an attribute with a Callable annotation is inferred as Uninferable.
+
+ See issue#1129.
+ """
+ instance = astroid.extract_node(
+ """
+ from dataclasses import dataclass
+ from typing import Any, Callable
+
+ @dataclass
+ class A:
+ enabled: Callable[[Any], bool]
+
+ A(lambda x: x == 42).enabled #@
+ """
+ )
+ inferred = next(instance.infer())
+ assert inferred is Uninferable
|
none
|
[
"tests/unittest_brain_dataclasses.py::test_inference_callable_attribute"
] |
[
"tests/unittest_brain_dataclasses.py::test_inference_attribute_no_default",
"tests/unittest_brain_dataclasses.py::test_inference_non_field_default",
"tests/unittest_brain_dataclasses.py::test_inference_field_default",
"tests/unittest_brain_dataclasses.py::test_inference_field_default_factory",
"tests/unittest_brain_dataclasses.py::test_inference_method",
"tests/unittest_brain_dataclasses.py::test_inference_no_annotation",
"tests/unittest_brain_dataclasses.py::test_inference_class_var",
"tests/unittest_brain_dataclasses.py::test_inference_init_var",
"tests/unittest_brain_dataclasses.py::test_inference_generic_collection_attribute"
] |
[
"pytest -rA tests/"
] |
pytest
|
{
"files": 2,
"hunks": 3,
"lines": 54
}
|
|
39c2a9805970ca57093d32bbaf0e6a63e05041d8
|
[
"https://github.com/pylint-dev/astroid/commit/a4b1d5b529aa73f681a8ae5eb77a8f79c534e68b",
"https://github.com/pylint-dev/astroid/commit/5ab5949077261fef86591690dd617b9bb1d7772f",
"https://github.com/pylint-dev/astroid/commit/c9cc6a67c05bd74da63b813f7fa01dc757d18193",
"https://github.com/pylint-dev/astroid/commit/dd10dc1766a10413ec05c9311c90ef4efab2a27b",
"https://github.com/pylint-dev/astroid/commit/59ad5cdda1d7d050490efdc51ba536bd443dd229",
"https://github.com/pylint-dev/astroid/commit/460fab03b4128997fcb34e70a2ce50cbf03fe83a"
] | 2021-10-03T15:58:07
|
pylint-dev__astroid-1196
|
[
"1195"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index c3b3e6b90b..24a7d49bfc 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -55,6 +55,10 @@ Release date: TBA
* Fix test for Python ``3.11``. In some instances ``err.__traceback__`` will
be uninferable now.
+* Infer the ``DictUnpack`` value for ``Dict.getitem`` calls.
+
+ Closes #1195
+
What's New in astroid 2.11.6?
=============================
Release date: TBA
diff --git a/astroid/nodes/node_classes.py b/astroid/nodes/node_classes.py
index 11136f8c77..c97be2dfba 100644
--- a/astroid/nodes/node_classes.py
+++ b/astroid/nodes/node_classes.py
@@ -2346,24 +2346,33 @@ def itered(self):
"""
return [key for (key, _) in self.items]
- def getitem(self, index, context=None):
+ def getitem(
+ self, index: Const | Slice, context: InferenceContext | None = None
+ ) -> NodeNG:
"""Get an item from this node.
:param index: The node to use as a subscript index.
- :type index: Const or Slice
:raises AstroidTypeError: When the given index cannot be used as a
subscript index, or if this node is not subscriptable.
:raises AstroidIndexError: If the given index does not exist in the
dictionary.
"""
+ # pylint: disable-next=import-outside-toplevel; circular import
+ from astroid.helpers import safe_infer
+
for key, value in self.items:
# TODO(cpopa): no support for overriding yet, {1:2, **{1: 3}}.
if isinstance(key, DictUnpack):
+ inferred_value = safe_infer(value, context)
+ if not isinstance(inferred_value, Dict):
+ continue
+
try:
- return value.getitem(index, context)
+ return inferred_value.getitem(index, context)
except (AstroidTypeError, AstroidIndexError):
continue
+
for inferredkey in key.infer(context):
if inferredkey is util.Uninferable:
continue
|
getitem does not infer the actual unpacked value
When trying to call `Dict.getitem()` on a context where we have a dict unpacking of anything beside a real dict, astroid currently raises an `AttributeError: 'getitem'`, which has 2 problems:
- The object might be a reference against something constant, this pattern is usually seen when we have different sets of dicts that extend each other, and all of their values are inferrable.
- We can have something that is uninferable, but in that case instead of an `AttributeError` I think it makes sense to raise the usual `AstroidIndexError` which is supposed to be already handled by the downstream.
Here is a short reproducer;
```py
from astroid import parse
source = """
X = {
'A': 'B'
}
Y = {
**X
}
KEY = 'A'
"""
tree = parse(source)
first_dict = tree.body[0].value
second_dict = tree.body[1].value
key = tree.body[2].value
print(f'{first_dict.getitem(key).value = }')
print(f'{second_dict.getitem(key).value = }')
```
The current output;
```
$ python t1.py 3ms
first_dict.getitem(key).value = 'B'
Traceback (most recent call last):
File "/home/isidentical/projects/astroid/t1.py", line 23, in <module>
print(f'{second_dict.getitem(key).value = }')
File "/home/isidentical/projects/astroid/astroid/nodes/node_classes.py", line 2254, in getitem
return value.getitem(index, context)
AttributeError: 'Name' object has no attribute 'getitem'
```
Expeceted output;
```
$ python t1.py 4ms
first_dict.getitem(key).value = 'B'
second_dict.getitem(key).value = 'B'
```
|
1196
|
pylint-dev/astroid
|
diff --git a/tests/unittest_python3.py b/tests/unittest_python3.py
index 9f60833e8e..bf0a0b33da 100644
--- a/tests/unittest_python3.py
+++ b/tests/unittest_python3.py
@@ -5,7 +5,9 @@
import unittest
from textwrap import dedent
-from astroid import nodes
+import pytest
+
+from astroid import exceptions, nodes
from astroid.builder import AstroidBuilder, extract_node
from astroid.test_utils import require_version
@@ -285,6 +287,33 @@ def test_unpacking_in_dict_getitem(self) -> None:
self.assertIsInstance(value, nodes.Const)
self.assertEqual(value.value, expected)
+ @staticmethod
+ def test_unpacking_in_dict_getitem_with_ref() -> None:
+ node = extract_node(
+ """
+ a = {1: 2}
+ {**a, 2: 3} #@
+ """
+ )
+ assert isinstance(node, nodes.Dict)
+
+ for key, expected in ((1, 2), (2, 3)):
+ value = node.getitem(nodes.Const(key))
+ assert isinstance(value, nodes.Const)
+ assert value.value == expected
+
+ @staticmethod
+ def test_unpacking_in_dict_getitem_uninferable() -> None:
+ node = extract_node("{**a, 2: 3}")
+ assert isinstance(node, nodes.Dict)
+
+ with pytest.raises(exceptions.AstroidIndexError):
+ node.getitem(nodes.Const(1))
+
+ value = node.getitem(nodes.Const(2))
+ assert isinstance(value, nodes.Const)
+ assert value.value == 3
+
def test_format_string(self) -> None:
code = "f'{greetings} {person}'"
node = extract_node(code)
|
none
|
[
"tests/unittest_python3.py::Python3TC::test_unpacking_in_dict_getitem_uninferable",
"tests/unittest_python3.py::Python3TC::test_unpacking_in_dict_getitem_with_ref"
] |
[
"tests/unittest_python3.py::Python3TC::test_annotation_as_string",
"tests/unittest_python3.py::Python3TC::test_annotation_support",
"tests/unittest_python3.py::Python3TC::test_as_string",
"tests/unittest_python3.py::Python3TC::test_async_comprehensions",
"tests/unittest_python3.py::Python3TC::test_async_comprehensions_as_string",
"tests/unittest_python3.py::Python3TC::test_async_comprehensions_outside_coroutine",
"tests/unittest_python3.py::Python3TC::test_format_string",
"tests/unittest_python3.py::Python3TC::test_kwonlyargs_annotations_supper",
"tests/unittest_python3.py::Python3TC::test_metaclass_ancestors",
"tests/unittest_python3.py::Python3TC::test_metaclass_error",
"tests/unittest_python3.py::Python3TC::test_metaclass_imported",
"tests/unittest_python3.py::Python3TC::test_metaclass_multiple_keywords",
"tests/unittest_python3.py::Python3TC::test_metaclass_yes_leak",
"tests/unittest_python3.py::Python3TC::test_nested_unpacking_in_dicts",
"tests/unittest_python3.py::Python3TC::test_old_syntax_works",
"tests/unittest_python3.py::Python3TC::test_parent_metaclass",
"tests/unittest_python3.py::Python3TC::test_simple_metaclass",
"tests/unittest_python3.py::Python3TC::test_starred_notation",
"tests/unittest_python3.py::Python3TC::test_underscores_in_numeral_literal",
"tests/unittest_python3.py::Python3TC::test_unpacking_in_dict_getitem",
"tests/unittest_python3.py::Python3TC::test_unpacking_in_dicts",
"tests/unittest_python3.py::Python3TC::test_yield_from",
"tests/unittest_python3.py::Python3TC::test_yield_from_as_string",
"tests/unittest_python3.py::Python3TC::test_yield_from_is_generator"
] |
[
"pytest -rA tests/"
] |
pytest
|
{
"files": 2,
"hunks": 2,
"lines": 19
}
|
||
4cfd9b6d1003b9912ab94538e1dfa5d734f55251
|
[
"https://github.com/pylint-dev/astroid/commit/c18286e1d7eef287297441ec020347f3f15780fb",
"https://github.com/pylint-dev/astroid/commit/fa3731ba6992abaf6cf256fcf85381053799e484"
] | 2021-04-07T23:44:25
|
pylint-dev__astroid-934
|
[
"904"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index 6097526bbd..c606b76106 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -41,6 +41,10 @@ Release Date: TBA
Closes #922
+* Fix inference of attributes defined in a base class that is an inner class
+
+ Closes #904
+
What's New in astroid 2.5.6?
============================
diff --git a/astroid/inference.py b/astroid/inference.py
index 20c986478e..dd9a565aec 100644
--- a/astroid/inference.py
+++ b/astroid/inference.py
@@ -309,6 +309,7 @@ def infer_attribute(self, context=None):
elif not context:
context = contextmod.InferenceContext()
+ old_boundnode = context.boundnode
try:
context.boundnode = owner
yield from owner.igetattr(self.attrname, context)
@@ -319,7 +320,7 @@ def infer_attribute(self, context=None):
):
pass
finally:
- context.boundnode = None
+ context.boundnode = old_boundnode
return dict(node=self, context=context)
|
error during inference of class inheriting from another with `mod.Type` format
Consider package a `level` with a class `Model` defined in `level`'s `__init__.py` file.
```
class Model:
data: int = 1
```
If a class `Test` inherits from `Model` as `class Test(Model)`, and `Model` comes from `from level import Model`, then inferring `Test.data` works fine (below, A is an alias for astroid).
<img width="248" alt="Screen Shot 2021-02-19 at 09 41 09" src="https://user-images.githubusercontent.com/2905588/108505730-9b3c1900-7296-11eb-8bb8-5b66b7253cf4.png">
However, if a `Test` inherits from `Model` as `class Test(level.Model)` and `level` comes from `import level`, then inference triggers an exception.
<img width="784" alt="Screen Shot 2021-02-19 at 09 42 09" src="https://user-images.githubusercontent.com/2905588/108505815-beff5f00-7296-11eb-92a2-641be827e1f0.png">
|
934
|
pylint-dev/astroid
|
diff --git a/tests/unittest_inference.py b/tests/unittest_inference.py
index 7fb1ed55c9..6b9f4c0609 100644
--- a/tests/unittest_inference.py
+++ b/tests/unittest_inference.py
@@ -3894,6 +3894,65 @@ class Clazz(metaclass=_Meta):
).inferred()[0]
assert isinstance(cls, nodes.ClassDef) and cls.name == "Clazz"
+ def test_infer_subclass_attr_outer_class(self):
+ node = extract_node(
+ """
+ class Outer:
+ data = 123
+
+ class Test(Outer):
+ pass
+ Test.data
+ """
+ )
+ inferred = next(node.infer())
+ assert isinstance(inferred, nodes.Const)
+ assert inferred.value == 123
+
+ def test_infer_subclass_attr_inner_class_works_indirectly(self):
+ node = extract_node(
+ """
+ class Outer:
+ class Inner:
+ data = 123
+ Inner = Outer.Inner
+
+ class Test(Inner):
+ pass
+ Test.data
+ """
+ )
+ inferred = next(node.infer())
+ assert isinstance(inferred, nodes.Const)
+ assert inferred.value == 123
+
+ def test_infer_subclass_attr_inner_class(self):
+ clsdef_node, attr_node = extract_node(
+ """
+ class Outer:
+ class Inner:
+ data = 123
+
+ class Test(Outer.Inner):
+ pass
+ Test #@
+ Test.data #@
+ """
+ )
+ clsdef = next(clsdef_node.infer())
+ assert isinstance(clsdef, nodes.ClassDef)
+ inferred = next(clsdef.igetattr("data"))
+ assert isinstance(inferred, nodes.Const)
+ assert inferred.value == 123
+ # Inferring the value of .data via igetattr() worked before the
+ # old_boundnode fixes in infer_subscript, so it should have been
+ # possible to infer the subscript directly. It is the difference
+ # between these two cases that led to the discovery of the cause of the
+ # bug in https://github.com/PyCQA/astroid/issues/904
+ inferred = next(attr_node.infer())
+ assert isinstance(inferred, nodes.Const)
+ assert inferred.value == 123
+
def test_delayed_attributes_without_slots(self):
ast_node = extract_node(
"""
|
none
|
[
"tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_inner_class"
] |
[
"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_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_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 -m \"not acceptance\""
] |
pytest
|
{
"files": 2,
"hunks": 3,
"lines": 7
}
|
||
@gpshead thanks for the report.
|
efc5be48e8294cea6c5335a3ad0821fa920fd1e6
|
[
"https://github.com/pylint-dev/astroid/commit/9d4082a518198037f5ac564ea4c111584d4d648f",
"https://github.com/pylint-dev/astroid/commit/0cbce24ba586144114e9f51c1242523c3362a2f9",
"https://github.com/pylint-dev/astroid/commit/dffd1bfbdeb19be77a9d2f08a2fa7d76f206d39a"
] | 2021-05-16T07:13:50
|
@gpshead thanks for the report.
|
pylint-dev__astroid-993
|
[
"922"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index 9d7b945fde..6097526bbd 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -37,6 +37,10 @@ Release Date: TBA
Closes PyCQA/pylint#3535
Closes PyCQA/pylint#4358
+* Update random brain to fix a crash with inference of some sequence elements
+
+ Closes #922
+
What's New in astroid 2.5.6?
============================
diff --git a/astroid/brain/brain_random.py b/astroid/brain/brain_random.py
index ee5506cbae..6efd1ff134 100644
--- a/astroid/brain/brain_random.py
+++ b/astroid/brain/brain_random.py
@@ -9,6 +9,8 @@
def _clone_node_with_lineno(node, parent, lineno):
+ if isinstance(node, astroid.EvaluatedObject):
+ node = node.original
cls = node.__class__
other_fields = node._other_fields
_astroid_fields = node._astroid_fields
|
__init__() got an unexpected keyword argument 'lineno' from brain_random.py
### Steps to reproduce & current behavior
```
~/tempenv$ pylint --version
pylint 2.7.2
astroid 2.5.1
Python 3.8.7 (default, Dec 22 2020, 10:37:26)
[GCC 10.2.0]
(tempenv) ~/tempenv$ cat example.py
class A:
pass
b = sample(list({1: A()}.values()), 1)
(tempenv) ~/tempenv$ pylint example.py
************* Module example
example.py:1:0: C0114: Missing module docstring (missing-module-docstring)
example.py:1:0: C0103: Class name "A" doesn't conform to PascalCase naming style (invalid-name)
example.py:1:0: C0115: Missing class docstring (missing-class-docstring)
example.py:1:0: R0903: Too few public methods (0/2) (too-few-public-methods)
Traceback (most recent call last):
File "/home/gps/tempenv/lib/python3.8/site-packages/astroid/__init__.py", line 94, in _inference_tip_cached
return iter(_cache[func, node])
KeyError: (<function infer_random_sample at 0x7f5d412c5940>, <Call l.4 at 0x7f5d40decf70>)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/gps/tempenv/bin/pylint", line 8, in <module>
sys.exit(run_pylint())
File "/home/gps/tempenv/lib/python3.8/site-packages/pylint/__init__.py", line 22, in run_pylint
PylintRun(sys.argv[1:])
File "/home/gps/tempenv/lib/python3.8/site-packages/pylint/lint/run.py", line 358, in __init__
linter.check(args)
File "/home/gps/tempenv/lib/python3.8/site-packages/pylint/lint/pylinter.py", line 862, in check
self._check_files(
File "/home/gps/tempenv/lib/python3.8/site-packages/pylint/lint/pylinter.py", line 896, in _check_files
self._check_file(get_ast, check_astroid_module, name, filepath, modname)
File "/home/gps/tempenv/lib/python3.8/site-packages/pylint/lint/pylinter.py", line 922, in _check_file
check_astroid_module(ast_node)
File "/home/gps/tempenv/lib/python3.8/site-packages/pylint/lint/pylinter.py", line 1054, in check_astroid_module
retval = self._check_astroid_module(
File "/home/gps/tempenv/lib/python3.8/site-packages/pylint/lint/pylinter.py", line 1099, in _check_astroid_module
walker.walk(ast_node)
File "/home/gps/tempenv/lib/python3.8/site-packages/pylint/utils/ast_walker.py", line 75, in walk
self.walk(child)
File "/home/gps/tempenv/lib/python3.8/site-packages/pylint/utils/ast_walker.py", line 75, in walk
self.walk(child)
File "/home/gps/tempenv/lib/python3.8/site-packages/pylint/utils/ast_walker.py", line 72, in walk
callback(astroid)
File "/home/gps/tempenv/lib/python3.8/site-packages/pylint/checkers/base.py", line 1968, in visit_assignname
if isinstance(utils.safe_infer(assign_type.value), astroid.ClassDef):
File "/home/gps/tempenv/lib/python3.8/site-packages/pylint/checkers/utils.py", line 1205, in safe_infer
value = next(infer_gen)
File "/home/gps/tempenv/lib/python3.8/site-packages/astroid/node_classes.py", line 360, in infer
yield from self._explicit_inference(self, context, **kwargs)
File "/home/gps/tempenv/lib/python3.8/site-packages/wrapt/wrappers.py", line 566, in __call__
return self._self_wrapper(self.__wrapped__, self._self_instance,
File "/home/gps/tempenv/lib/python3.8/site-packages/astroid/__init__.py", line 96, in _inference_tip_cached
result = func(*args, **kwargs)
File "/home/gps/tempenv/lib/python3.8/site-packages/astroid/brain/brain_random.py", line 56, in infer_random_sample
new_elts = [
File "/home/gps/tempenv/lib/python3.8/site-packages/astroid/brain/brain_random.py", line 57, in <listcomp>
_clone_node_with_lineno(elt, parent=new_node, lineno=new_node.lineno)
File "/home/gps/tempenv/lib/python3.8/site-packages/astroid/brain/brain_random.py", line 21, in _clone_node_with_lineno
new_node = cls(**init_params)
TypeError: __init__() got an unexpected keyword argument 'lineno'
```
### Expected behavior
A successful pylint run, probably highlighting that `simple` is undefined.
### ``python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"`` output
2.5.1
If this winds up being a pylint issue, I guess refile it over there. I filed here based on the bottom the traceback but that doesn't mean the problem originated in astroid. I haven't spent time looking at the code.
|
993
|
pylint-dev/astroid
|
diff --git a/tests/unittest_brain.py b/tests/unittest_brain.py
index 0e8c591198..26fad2e3bf 100644
--- a/tests/unittest_brain.py
+++ b/tests/unittest_brain.py
@@ -1858,6 +1858,18 @@ def test_inferred_successfully(self):
elems = sorted(elem.value for elem in inferred.elts)
self.assertEqual(elems, [1, 2])
+ def test_no_crash_on_evaluatedobject(self):
+ node = astroid.extract_node(
+ """
+ from random import sample
+ class A: pass
+ sample(list({1: A()}.values()), 1)"""
+ )
+ inferred = next(node.infer())
+ assert isinstance(inferred, astroid.List)
+ assert len(inferred.elts) == 1
+ assert isinstance(inferred.elts[0], nodes.Call)
+
class SubprocessTest(unittest.TestCase):
"""Test subprocess brain"""
|
none
|
[
"tests/unittest_brain.py::RandomSampleTest::test_no_crash_on_evaluatedobject"
] |
[
"tests/unittest_brain.py::HashlibTest::test_hashlib",
"tests/unittest_brain.py::HashlibTest::test_hashlib_py36",
"tests/unittest_brain.py::CollectionsDequeTests::test_deque",
"tests/unittest_brain.py::CollectionsDequeTests::test_deque_py35methods",
"tests/unittest_brain.py::CollectionsDequeTests::test_deque_py39methods",
"tests/unittest_brain.py::OrderedDictTest::test_ordered_dict_py34method",
"tests/unittest_brain.py::NamedTupleTest::test_invalid_label_does_not_crash_inference",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_access_class_fields",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_advanced_inference",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_base",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_bases_are_actually_names_not_nodes",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_func_form",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_func_form_args_and_kwargs",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_inference",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_inference_failure",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_instance_attrs",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_rename_duplicates",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_rename_keywords",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_rename_uninferable",
"tests/unittest_brain.py::NamedTupleTest::test_namedtuple_uninferable_fields",
"tests/unittest_brain.py::DefaultDictTest::test_1",
"tests/unittest_brain.py::ModuleExtenderTest::testExtensionModules",
"tests/unittest_brain.py::MultiprocessingBrainTest::test_module_name",
"tests/unittest_brain.py::MultiprocessingBrainTest::test_multiprocessing_manager",
"tests/unittest_brain.py::MultiprocessingBrainTest::test_multiprocessing_module_attributes",
"tests/unittest_brain.py::ThreadingBrainTest::test_boundedsemaphore",
"tests/unittest_brain.py::ThreadingBrainTest::test_lock",
"tests/unittest_brain.py::ThreadingBrainTest::test_rlock",
"tests/unittest_brain.py::ThreadingBrainTest::test_semaphore",
"tests/unittest_brain.py::EnumBrainTest::test_dont_crash_on_for_loops_in_body",
"tests/unittest_brain.py::EnumBrainTest::test_enum_func_form_has_dunder_members",
"tests/unittest_brain.py::EnumBrainTest::test_enum_func_form_is_class_not_instance",
"tests/unittest_brain.py::EnumBrainTest::test_enum_func_form_iterable",
"tests/unittest_brain.py::EnumBrainTest::test_enum_func_form_subscriptable",
"tests/unittest_brain.py::EnumBrainTest::test_enum_multiple_base_classes",
"tests/unittest_brain.py::EnumBrainTest::test_enum_starred_is_skipped",
"tests/unittest_brain.py::EnumBrainTest::test_enum_tuple_list_values",
"tests/unittest_brain.py::EnumBrainTest::test_ignores_with_nodes_from_body_of_enum",
"tests/unittest_brain.py::EnumBrainTest::test_infer_enum_value_as_the_right_type",
"tests/unittest_brain.py::EnumBrainTest::test_int_enum",
"tests/unittest_brain.py::EnumBrainTest::test_looks_like_enum_false_positive",
"tests/unittest_brain.py::EnumBrainTest::test_mingled_single_and_double_quotes_does_not_crash",
"tests/unittest_brain.py::EnumBrainTest::test_simple_enum",
"tests/unittest_brain.py::EnumBrainTest::test_special_characters_does_not_crash",
"tests/unittest_brain.py::PytestBrainTest::test_pytest",
"tests/unittest_brain.py::TypeBrain::test_builtin_subscriptable",
"tests/unittest_brain.py::TypeBrain::test_invalid_type_subscript",
"tests/unittest_brain.py::TypeBrain::test_type_subscript",
"tests/unittest_brain.py::CollectionsBrain::test_collections_object_not_subscriptable",
"tests/unittest_brain.py::CollectionsBrain::test_collections_object_subscriptable",
"tests/unittest_brain.py::CollectionsBrain::test_collections_object_subscriptable_2",
"tests/unittest_brain.py::CollectionsBrain::test_collections_object_subscriptable_3",
"tests/unittest_brain.py::CollectionsBrain::test_collections_object_subscriptable_4",
"tests/unittest_brain.py::TypingBrain::test_has_dunder_args",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_base",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_bug_pylint_4383",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_can_correctly_access_methods",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_class_form",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_few_args",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_few_fields",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_inference",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_inference_nonliteral",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_inferred_as_class",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_instance_attrs",
"tests/unittest_brain.py::TypingBrain::test_namedtuple_simple",
"tests/unittest_brain.py::TypingBrain::test_tuple_type",
"tests/unittest_brain.py::TypingBrain::test_typedDict",
"tests/unittest_brain.py::TypingBrain::test_typing_alias_type",
"tests/unittest_brain.py::TypingBrain::test_typing_alias_type_2",
"tests/unittest_brain.py::TypingBrain::test_typing_annotated_subscriptable",
"tests/unittest_brain.py::TypingBrain::test_typing_generic_slots",
"tests/unittest_brain.py::TypingBrain::test_typing_generic_subscriptable",
"tests/unittest_brain.py::TypingBrain::test_typing_namedtuple_dont_crash_on_no_fields",
"tests/unittest_brain.py::TypingBrain::test_typing_object_builtin_subscriptable",
"tests/unittest_brain.py::TypingBrain::test_typing_object_not_subscriptable",
"tests/unittest_brain.py::TypingBrain::test_typing_object_notsubscriptable_3",
"tests/unittest_brain.py::TypingBrain::test_typing_object_subscriptable",
"tests/unittest_brain.py::TypingBrain::test_typing_object_subscriptable_2",
"tests/unittest_brain.py::TypingBrain::test_typing_types",
"tests/unittest_brain.py::ReBrainTest::test_re_pattern_subscriptable",
"tests/unittest_brain.py::ReBrainTest::test_regex_flags",
"tests/unittest_brain.py::BrainFStrings::test_no_crash_on_const_reconstruction",
"tests/unittest_brain.py::BrainNamedtupleAnnAssignTest::test_no_crash_on_ann_assign_in_namedtuple",
"tests/unittest_brain.py::BrainUUIDTest::test_uuid_has_int_member",
"tests/unittest_brain.py::RandomSampleTest::test_inferred_successfully",
"tests/unittest_brain.py::SubprocessTest::test_popen_does_not_have_class_getitem",
"tests/unittest_brain.py::SubprocessTest::test_subprcess_check_output",
"tests/unittest_brain.py::SubprocessTest::test_subprocess_args",
"tests/unittest_brain.py::TestIsinstanceInference::test_type_type",
"tests/unittest_brain.py::TestIsinstanceInference::test_object_type",
"tests/unittest_brain.py::TestIsinstanceInference::test_type_object",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_int_true",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_int_false",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_object_true",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_object_true3",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_class_false",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_type_false",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_str_true",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_str_false",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_tuple_argument",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_type_false2",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_object_true2",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_type_true",
"tests/unittest_brain.py::TestIsinstanceInference::test_isinstance_edge_case",
"tests/unittest_brain.py::TestIsinstanceInference::test_uninferable_bad_type",
"tests/unittest_brain.py::TestIsinstanceInference::test_uninferable_keywords",
"tests/unittest_brain.py::TestIsinstanceInference::test_too_many_args",
"tests/unittest_brain.py::TestIsinstanceInference::test_first_param_is_uninferable",
"tests/unittest_brain.py::TestIssubclassBrain::test_type_type",
"tests/unittest_brain.py::TestIssubclassBrain::test_object_type",
"tests/unittest_brain.py::TestIssubclassBrain::test_type_object",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_same_class",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_not_the_same_class",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_object_true",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_same_user_defined_class",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_different_user_defined_classes",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_type_false",
"tests/unittest_brain.py::TestIssubclassBrain::test_isinstance_tuple_argument",
"tests/unittest_brain.py::TestIssubclassBrain::test_isinstance_object_true2",
"tests/unittest_brain.py::TestIssubclassBrain::test_issubclass_short_circuit",
"tests/unittest_brain.py::TestIssubclassBrain::test_uninferable_bad_type",
"tests/unittest_brain.py::TestIssubclassBrain::test_uninferable_keywords",
"tests/unittest_brain.py::TestIssubclassBrain::test_too_many_args",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_list",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_tuple",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_var",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_dict",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_set",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_object",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_class_with_metaclass",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_object_failure",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_string",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_generator_failure",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_failure_missing_variable",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_bytes",
"tests/unittest_brain.py::TestLenBuiltinInference::test_int_subclass_result",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_builtin_inference_attribute_error_str",
"tests/unittest_brain.py::TestLenBuiltinInference::test_len_builtin_inference_recursion_error_self_referential_attribute",
"tests/unittest_brain.py::test_infer_str",
"tests/unittest_brain.py::test_infer_int",
"tests/unittest_brain.py::test_infer_dict_from_keys",
"tests/unittest_brain.py::TestFunctoolsPartial::test_invalid_functools_partial_calls",
"tests/unittest_brain.py::TestFunctoolsPartial::test_inferred_partial_function_calls",
"tests/unittest_brain.py::test_http_client_brain",
"tests/unittest_brain.py::test_http_status_brain",
"tests/unittest_brain.py::test_oserror_model",
"tests/unittest_brain.py::test_crypt_brain",
"tests/unittest_brain.py::test_dataclasses",
"tests/unittest_brain.py::test_str_and_bytes['hey'.encode()-Const-]",
"tests/unittest_brain.py::test_str_and_bytes[b'hey'.decode()-Const-]",
"tests/unittest_brain.py::test_str_and_bytes['hey'.encode().decode()-Const-]",
"tests/unittest_brain.py::test_no_recursionerror_on_self_referential_length_check",
"tests/unittest_brain.py::TestLenBuiltinInference::test_int_subclass_argument"
] |
[
"pytest -rA tests/"
] |
pytest
|
{
"files": 2,
"hunks": 2,
"lines": 6
}
|
This seems relevant:
https://github.com/PyCQA/astroid/blob/1a698acd4ca746851e6a525bf7e012ac6e6eb877/astroid/nodes/scoped_nodes/scoped_nodes.py#L1702-L1712
I am not familiar with that code, but it seems like this is indeed very error-prone.
@DanielNoord
https://github.com/PyCQA/astroid/blob/1a698acd4ca746851e6a525bf7e012ac6e6eb877/astroid/nodes/scoped_nodes/scoped_nodes.py#L1713
I think this line is the exact problem. Did `FunctionDef.args` ever return a list of nodes before? It seems to return an `Arguments` type now.
Not as far as I know. However, is `caller` always a `FunctionDef`? Might that be where this is going wrong?
@DanielNoord do you know of any node type which has an `args` field of type list?
`CallContext` has `list[NodeNG]` and `Arguments` has `list[AssignName]`.
It looks like this is happening whether or not `six` is involved, but yes, since #1622 we no longer inject a `Call` as a fake base. That fake `Call` would have had `.args`.
|
495581f0ff1b0513397b9177c62f27e702e11bb2
|
[
"https://github.com/pylint-dev/astroid/commit/4b31a4bdbde019bf26fa7751172d5541530d2982",
"https://github.com/pylint-dev/astroid/commit/15722e60a1180d1d766d8daa6711b87fafbc0674",
"https://github.com/pylint-dev/astroid/commit/65b09d5d9242277ec55df957eeaca6112de783ac"
] | 2023-04-15T14:52:11
|
This seems relevant:
https://github.com/PyCQA/astroid/blob/1a698acd4ca746851e6a525bf7e012ac6e6eb877/astroid/nodes/scoped_nodes/scoped_nodes.py#L1702-L1712
I am not familiar with that code, but it seems like this is indeed very error-prone.
@DanielNoord
https://github.com/PyCQA/astroid/blob/1a698acd4ca746851e6a525bf7e012ac6e6eb877/astroid/nodes/scoped_nodes/scoped_nodes.py#L1713
I think this line is the exact problem. Did `FunctionDef.args` ever return a list of nodes before? It seems to return an `Arguments` type now.
Not as far as I know. However, is `caller` always a `FunctionDef`? Might that be where this is going wrong?
@DanielNoord do you know of any node type which has an `args` field of type list?
`CallContext` has `list[NodeNG]` and `Arguments` has `list[AssignName]`.
It looks like this is happening whether or not `six` is involved, but yes, since #1622 we no longer inject a `Call` as a fake base. That fake `Call` would have had `.args`.
|
pylint-dev__astroid-2118
|
[
"1735"
] |
python
|
diff --git a/ChangeLog b/ChangeLog
index 460ef30507..f02a58516c 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -61,6 +61,9 @@ What's New in astroid 2.15.3?
=============================
Release date: TBA
+* Fix ``infer_call_result()`` crash on methods called ``with_metaclass()``.
+
+ Closes #1735
What's New in astroid 2.15.2?
diff --git a/astroid/nodes/scoped_nodes/scoped_nodes.py b/astroid/nodes/scoped_nodes/scoped_nodes.py
index c75237729d..8c39129c28 100644
--- a/astroid/nodes/scoped_nodes/scoped_nodes.py
+++ b/astroid/nodes/scoped_nodes/scoped_nodes.py
@@ -1692,10 +1692,18 @@ def infer_call_result(self, caller=None, context: InferenceContext | None = None
# generators, and filter it out later.
if (
self.name == "with_metaclass"
+ and caller is not None
and len(self.args.args) == 1
and self.args.vararg is not None
):
- metaclass = next(caller.args[0].infer(context), None)
+ if isinstance(caller.args, Arguments):
+ metaclass = next(caller.args.args[0].infer(context), None)
+ elif isinstance(caller.args, list):
+ metaclass = next(caller.args[0].infer(context), None)
+ else:
+ raise TypeError( # pragma: no cover
+ f"caller.args was neither Arguments nor list; got {type(caller.args)}"
+ )
if isinstance(metaclass, ClassDef):
try:
class_bases = [
|
Code for supporting `with_metaclass` seems broken
So this code works as expected:
```python
node = astroid.extract_node('''
def foo():
return 42
''')
print(list(node.infer_call_result(caller=node)))
```
```console
$ python a.py
[<Const.int l.3 at 0x105704070>]
```
But this breaks:
```python
node = astroid.extract_node('''
def with_metaclass(meta, *bases):
return 42
''')
print(list(node.infer_call_result(caller=node)))
```
```console
$ python a.py
Traceback (most recent call last):
File "/Users/tusharsadhwani/a.py", line 14, in <module>
print(list(node.infer_call_result(node)))
File "/Users/tusharsadhwani/venv/lib/python3.10/site-packages/astroid/nodes/scoped_nodes/scoped_nodes.py", line 1738, in infer_call_result
metaclass = next(caller.args[0].infer(context), None)
TypeError: 'Arguments' object is not subscriptable
```
astroid seems to have special handling for functions called `with_metaclass`, which seems to be broken.
Am I using the method wrongly? I tried using it just as I saw it being used in the project itself.
|
2118
|
pylint-dev/astroid
|
diff --git a/tests/test_inference.py b/tests/test_inference.py
index 37a48f089d..7fcbb10cce 100644
--- a/tests/test_inference.py
+++ b/tests/test_inference.py
@@ -4055,6 +4055,11 @@ class C:
inferred = next(node.infer())
self.assertRaises(InferenceError, next, inferred.infer_call_result(node))
+ def test_infer_call_result_with_metaclass(self) -> None:
+ node = extract_node("def with_metaclass(meta, *bases): return 42")
+ inferred = next(node.infer_call_result(caller=node))
+ self.assertIsInstance(inferred, nodes.Const)
+
def test_context_call_for_context_managers(self) -> None:
ast_nodes = extract_node(
"""
|
none
|
[
"tests/test_inference.py::InferenceTest::test_infer_call_result_with_metaclass"
] |
[
"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_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_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_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_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_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::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_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_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::InferenceTest::test_descriptor_are_callable",
"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"
] |
[
". venv/bin/activate && pytest -rA"
] |
pytest
|
{
"files": 2,
"hunks": 2,
"lines": 13
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.