Skip to content

Commit ffee3a0

Browse files
committed
Fix overzealous inference of "type" in subscript contexts
Ref pylint-dev/pylint#4083. Ref pylint-dev/pylint#4387. When used in a nodes.Subscript, an existing inference_tip was set for Name nodes matching called type. However, when this name was redefined this led to false-positive typecheck errors in pylint such as invalid-sequence-index (see pylint-dev/pylint#4083 and pylint-dev/pylint#4387)
1 parent d09c210 commit ffee3a0

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

astroid/brain/brain_type.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
"""
1818
import sys
1919

20-
from astroid import MANAGER, extract_node, inference_tip, nodes
20+
from astroid import MANAGER, extract_node, inference_tip, nodes, UseInferenceDefault
2121

2222
PY39 = sys.version_info >= (3, 9)
2323

@@ -47,6 +47,8 @@ def infer_type_sub(node, context=None):
4747
:return: the inferred node
4848
:rtype: nodes.NodeNG
4949
"""
50+
if "type" in node.scope().locals:
51+
raise UseInferenceDefault()
5052
class_src = """
5153
class type:
5254
def __class_getitem__(cls, key):

tests/unittest_inference.py

+13
Original file line numberDiff line numberDiff line change
@@ -4012,6 +4012,19 @@ def func(type):
40124012
assert not isinstance(inferred, nodes.ClassDef) # was inferred as builtins.type
40134013
assert inferred is util.Uninferable
40144014

4015+
@pytest.mark.skipif(sys.version_info < (3, 8), reason="only fails on Python 3.9")
4016+
def test_infer_arg_called_type_when_used_as_subscript_is_uninferable(self):
4017+
# Only this case seems to fail
4018+
node = extract_node(
4019+
"""
4020+
def func(type):
4021+
type[0] #@
4022+
"""
4023+
)
4024+
inferred = next(node.infer())
4025+
assert not isinstance(inferred, nodes.ClassDef) # was inferred as builtins.type
4026+
assert inferred is util.Uninferable
4027+
40154028

40164029
class GetattrTest(unittest.TestCase):
40174030
def test_yes_when_unknown(self):

0 commit comments

Comments
 (0)