Skip to content

Commit ee92008

Browse files
author
Alice Purcell
committed
Implement closed support in TypeAnalyser
Propagate closed when analysing a TypedDictType with a fallback. This ensures subtype checks work correctly for a TypeVar with a closed TypedDict upper bound.
1 parent 95465e8 commit ee92008

2 files changed

Lines changed: 20 additions & 2 deletions

File tree

mypy/typeanal.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1317,6 +1317,7 @@ def visit_typeddict_type(self, t: TypedDictType) -> Type:
13171317
" must be enabled with --enable-incomplete-feature=InlineTypedDict",
13181318
t,
13191319
)
1320+
is_closed = False
13201321
required_keys = req_keys
13211322
fallback = self.named_type("typing._TypedDict")
13221323
for typ in t.extra_items_from:
@@ -1339,9 +1340,9 @@ def visit_typeddict_type(self, t: TypedDictType) -> Type:
13391340
readonly_keys = t.readonly_keys
13401341
required_keys = t.required_keys
13411342
fallback = t.fallback
1342-
# TODO: Implement closure analysis
1343+
is_closed = t.is_closed
13431344
return TypedDictType(
1344-
items, required_keys, readonly_keys, False, fallback, t.line, t.column
1345+
items, required_keys, readonly_keys, is_closed, fallback, t.line, t.column
13451346
)
13461347

13471348
def visit_raw_expression_type(self, t: RawExpressionType) -> Type:

test-data/unit/check-typeddict.test

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4961,6 +4961,23 @@ f_g(h) # E: Argument 1 to "f_g" has incompatible type "H"; expected "G"
49614961
[builtins fixtures/dict.pyi]
49624962
[typing fixtures/typing-typeddict.pyi]
49634963

4964+
[case testTypedDictSubtypingClosedTypeVarBound]
4965+
from typing import TypedDict, TypeVar
4966+
A = TypedDict('A', {'x': int}, closed=True)
4967+
B = TypedDict('B', {'x': int})
4968+
TA = TypeVar('TA', bound=A)
4969+
TB = TypeVar('TB', bound=B)
4970+
def fA(t: TA) -> TA: return t
4971+
def fB(t: TB) -> TB: return t
4972+
a: A
4973+
b: B
4974+
fA(a)
4975+
fA(b) # E: Value of type variable "TA" of "fA" cannot be "B"
4976+
fB(a)
4977+
fB(b)
4978+
[builtins fixtures/dict.pyi]
4979+
[typing fixtures/typing-typeddict.pyi]
4980+
49644981
[case testJoinOfClosedTypedDict]
49654982
from typing import TypedDict, TypeVar
49664983
A = TypedDict('A', {'x': int}, closed=True)

0 commit comments

Comments
 (0)