Skip to content

Commit

Permalink
Fix crash on unimported Any with Required/NotRequired
Browse files Browse the repository at this point in the history
Fixes python#17604; fixes python#17608.  (To reproduce the crash without mypyc,
replace `cast(ProperType, typ)` with an assertion in
`get_proper_type`.)

Signed-off-by: Anders Kaseorg <[email protected]>
  • Loading branch information
andersk committed Jul 30, 2024
1 parent 8b74b5a commit 071f0f3
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
7 changes: 6 additions & 1 deletion mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@
Overloaded,
PartialType,
ProperType,
RequiredType,
TupleType,
Type,
TypeAliasType,
Expand Down Expand Up @@ -2945,7 +2946,11 @@ def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
"A type on this line", AnyType(TypeOfAny.special_form), s
)
else:
self.msg.unimported_type_becomes_any("Type of variable", s.type, s)
self.msg.unimported_type_becomes_any(
"Type of variable",
s.type.item if isinstance(s.type, RequiredType) else s.type,
s,
)
check_for_explicit_any(s.type, self.options, self.is_typeshed_stub, self.msg, context=s)

if len(s.lvalues) > 1:
Expand Down
3 changes: 2 additions & 1 deletion mypy/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
CallableType,
FunctionLike,
Instance,
RequiredType,
TupleType,
Type,
TypeOfAny,
Expand Down Expand Up @@ -205,7 +206,7 @@ def visit_assignment_stmt(self, o: AssignmentStmt) -> None:
if o.type:
# If there is an explicit type, don't visit the l.h.s. as an expression
# to avoid double-counting and mishandling special forms.
self.type(o.type)
self.type(o.type.item if isinstance(o.type, RequiredType) else o.type)
o.rvalue.accept(self)
return
elif self.inferred and not self.all_nodes:
Expand Down
8 changes: 8 additions & 0 deletions test-data/unit/check-typeddict.test
Original file line number Diff line number Diff line change
Expand Up @@ -2394,6 +2394,14 @@ class ForceDeferredEval: pass
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictRequiredUnimportedAny]
# flags: --disallow-any-unimported
from typing import NotRequired, TypedDict
from nonexistent import Foo # type: ignore[import-not-found]
class Bar(TypedDict):
foo: NotRequired[Foo] # E: Type of variable becomes "Any" due to an unfollowed import
[typing fixtures/typing-typeddict.pyi]

-- Required[]

[case testDoesRecognizeRequiredInTypedDictWithClass]
Expand Down

0 comments on commit 071f0f3

Please sign in to comment.