Skip to content

Commit e76c347

Browse files
martindemellorchen152
authored andcommitted
Stop dropping TypedDict annotations from local assignments.
Previously if we had ``` f: SomeTypedDict = {...} ``` and f was not a module-level variable, we would drop the type (after checking the dict's validity) and store it as a `Dict[str, ...]` instead. Fixes #1185 PiperOrigin-RevId: 443447773
1 parent fac1237 commit e76c347

File tree

2 files changed

+34
-5
lines changed

2 files changed

+34
-5
lines changed

pytype/annotation_utils.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
from pytype.abstract import abstract
1111
from pytype.abstract import abstract_utils
1212
from pytype.abstract import mixin
13-
from pytype.overlays import typed_dict
1413
from pytype.overlays import typing_overlay
1514
from pytype.pytd import pytd_utils
1615

@@ -345,10 +344,6 @@ def apply_annotation(self, node, op, name, value):
345344
return AnnotatedValue(None, value, final=True)
346345
elif isinstance(typ, abstract.FinalAnnotation):
347346
return AnnotatedValue(typ.annotation, annot_val, final=True)
348-
elif isinstance(typ, typed_dict.TypedDictClass):
349-
# We do not want to instantiate a TypedDict annotation if we have a
350-
# concrete value.
351-
return AnnotatedValue(typ, value)
352347
elif typ.full_name == "typing.TypeAlias":
353348
# Validate that 'value' is a legal type alias and use it.
354349
annot = self.extract_annotation(node, value, name, stack)

pytype/tests/test_typed_dict.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,40 @@ class A(TypedDict):
128128
"type errors", "{'x': ...}", "expected int", "got str"
129129
]})
130130

131+
def test_annotated_global_var(self):
132+
ty = self.Infer("""
133+
from typing_extensions import TypedDict
134+
class A(TypedDict):
135+
x: int
136+
a: A = {'x': 10}
137+
""")
138+
self.assertTypesMatchPytd(ty, """
139+
from typing import TypedDict
140+
141+
class A(TypedDict):
142+
x: int
143+
144+
a: A
145+
""")
146+
147+
def test_annotated_local_var(self):
148+
ty = self.Infer("""
149+
from typing_extensions import TypedDict
150+
class A(TypedDict):
151+
x: int
152+
def f():
153+
a: A = {'x': 10}
154+
return a
155+
""")
156+
self.assertTypesMatchPytd(ty, """
157+
from typing import TypedDict
158+
159+
class A(TypedDict):
160+
x: int
161+
162+
def f() -> A: ...
163+
""")
164+
131165
def test_return_type(self):
132166
err = self.CheckWithErrors("""
133167
from typing_extensions import TypedDict

0 commit comments

Comments
 (0)