Skip to content

Commit 7f8ea4a

Browse files
authored
Fix invalid type causing namedtuple errors in wrong files (#8549)
Fixes #8511. This is a workaround of #4987, where UnboundTypes can leak.
1 parent 1677efd commit 7f8ea4a

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

mypy/semanal_namedtuple.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
from typing_extensions import Final
99

1010
from mypy.types import (
11-
Type, TupleType, AnyType, TypeOfAny, TypeVarDef, CallableType, TypeType, TypeVarType
11+
Type, TupleType, AnyType, TypeOfAny, TypeVarDef, CallableType, TypeType, TypeVarType,
12+
UnboundType,
1213
)
1314
from mypy.semanal_shared import (
1415
SemanticAnalyzerInterface, set_callable_name, calculate_tuple_fallback, PRIORITY_FALLBACKS
@@ -334,6 +335,9 @@ def parse_namedtuple_fields_with_types(self, nodes: List[Expression], context: C
334335
except TypeTranslationError:
335336
return self.fail_namedtuple_arg('Invalid field type', type_node)
336337
analyzed = self.api.anal_type(type)
338+
# Workaround #4987 and avoid introducing a bogus UnboundType
339+
if isinstance(analyzed, UnboundType):
340+
analyzed = AnyType(TypeOfAny.from_error)
337341
# These should be all known, otherwise we would defer in visit_assignment_stmt().
338342
if analyzed is None:
339343
return None

test-data/unit/check-namedtuple.test

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -948,3 +948,17 @@ class A:
948948

949949
reveal_type(A().b) # N: Revealed type is 'Any'
950950
[builtins fixtures/tuple.pyi]
951+
952+
[case testNamedTupleWrongfile]
953+
from typing import NamedTuple
954+
from b import Type1
955+
Type2 = NamedTuple('Type2', [('x', Type1)])
956+
[file b.py]
957+
from typing import NamedTuple
958+
959+
def foo():
960+
pass
961+
962+
Type1 = NamedTuple('Type1', [('foo', foo)]) # E: Function "b.foo" is not valid as a type # N: Perhaps you need "Callable[...]" or a callback protocol?
963+
964+
[builtins fixtures/tuple.pyi]

test-data/unit/fine-grained.test

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8477,8 +8477,8 @@ m.py:4: note: See https://mypy.readthedocs.io/en/latest/common_issues.html#varia
84778477
==
84788478
m.py:4: error: Variable "a.A" is not valid as a type
84798479
m.py:4: note: See https://mypy.readthedocs.io/en/latest/common_issues.html#variables-vs-type-aliases
8480-
m.py:5: note: Revealed type is 'A?'
8481-
m.py:7: note: Revealed type is 'A?'
8480+
m.py:5: note: Revealed type is 'Any'
8481+
m.py:7: note: Revealed type is 'Any'
84828482

84838483
[case testAliasForwardFunctionDirect]
84848484
# flags: --ignore-missing-imports

0 commit comments

Comments
 (0)