Skip to content

Commit

Permalink
Fix invalid type causing namedtuple errors in wrong files (#8549)
Browse files Browse the repository at this point in the history
Fixes #8511.

This is a workaround of #4987, where UnboundTypes can leak.
  • Loading branch information
msullivan authored Mar 17, 2020
1 parent 1677efd commit 7f8ea4a
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
6 changes: 5 additions & 1 deletion mypy/semanal_namedtuple.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
from typing_extensions import Final

from mypy.types import (
Type, TupleType, AnyType, TypeOfAny, TypeVarDef, CallableType, TypeType, TypeVarType
Type, TupleType, AnyType, TypeOfAny, TypeVarDef, CallableType, TypeType, TypeVarType,
UnboundType,
)
from mypy.semanal_shared import (
SemanticAnalyzerInterface, set_callable_name, calculate_tuple_fallback, PRIORITY_FALLBACKS
Expand Down Expand Up @@ -334,6 +335,9 @@ def parse_namedtuple_fields_with_types(self, nodes: List[Expression], context: C
except TypeTranslationError:
return self.fail_namedtuple_arg('Invalid field type', type_node)
analyzed = self.api.anal_type(type)
# Workaround #4987 and avoid introducing a bogus UnboundType
if isinstance(analyzed, UnboundType):
analyzed = AnyType(TypeOfAny.from_error)
# These should be all known, otherwise we would defer in visit_assignment_stmt().
if analyzed is None:
return None
Expand Down
14 changes: 14 additions & 0 deletions test-data/unit/check-namedtuple.test
Original file line number Diff line number Diff line change
Expand Up @@ -948,3 +948,17 @@ class A:

reveal_type(A().b) # N: Revealed type is 'Any'
[builtins fixtures/tuple.pyi]

[case testNamedTupleWrongfile]
from typing import NamedTuple
from b import Type1
Type2 = NamedTuple('Type2', [('x', Type1)])
[file b.py]
from typing import NamedTuple

def foo():
pass

Type1 = NamedTuple('Type1', [('foo', foo)]) # E: Function "b.foo" is not valid as a type # N: Perhaps you need "Callable[...]" or a callback protocol?

[builtins fixtures/tuple.pyi]
4 changes: 2 additions & 2 deletions test-data/unit/fine-grained.test
Original file line number Diff line number Diff line change
Expand Up @@ -8477,8 +8477,8 @@ m.py:4: note: See https://mypy.readthedocs.io/en/latest/common_issues.html#varia
==
m.py:4: error: Variable "a.A" is not valid as a type
m.py:4: note: See https://mypy.readthedocs.io/en/latest/common_issues.html#variables-vs-type-aliases
m.py:5: note: Revealed type is 'A?'
m.py:7: note: Revealed type is 'A?'
m.py:5: note: Revealed type is 'Any'
m.py:7: note: Revealed type is 'Any'

[case testAliasForwardFunctionDirect]
# flags: --ignore-missing-imports
Expand Down

0 comments on commit 7f8ea4a

Please sign in to comment.