"Sealed" TypedDict
s that don't allow subtypes which introduce additional keys
#1984
Labels
topic: feature
Discussions about new features for Python's type annotations
Proposal
It might be useful if there was a possibility to mark a
TypedDict
as "sealed" (other naming suggestions welcome!), so that dicts with additional keys are not considered subtypes. E.g.:An alternative syntax may be to allow making any already-defined
TypedDict
sealed by wrapping it inSealed[...]
. E.g.:Motivation
Situation
Consider trying to
update()
aTypedDict
instance with an instance of a "partial" variant that only contains some of the former's keys:Current type checking behavior
Both major type checkers will complain about this:
error: Argument 1 to
update
ofTypedDict
has incompatible typeA
; expectedTypedDict({'a': int, 'b'?: int})
[typeddict-item]error: No overloads for
update
match the provided arguments (reportCallIssue)error: Argument of type
A
cannot be assigned to parameter__m
of typePartial[AB]
in functionupdate
b
is an incompatible typeobject
is incompatible withint
(reportArgumentType)As can be seen from the error messages, the reason is that
A
allows subtypes which would have a keyb
just likeAB
, but the type of the value for that key could be different in these hypothetical subtypes from what it is inAB
.Current workaround & why it's insufficient
This issue can be worked around by adding all additional keys of
AB
asNotRequired
keys onA
:This will make
ab.update(a)
pass type checking.But that is quite hacky:
TypedDict
s likeAB
, with different extra keys (beyond those inA
), I have to introduce separate variants ofA
for each of them just to makeupdate
work correctly.AB
has many more keys thanA
, I have to repeat all of them.A
should have any knowledge ofAB
's keys just to make theupdate
operation work.By contrast, if "sealed"
TypedDict
s were possible, I would only need the one sealedA
and that's it.Related proposals
@sealed
decorator@sealed
decorator would apply to classes and forbid subclasses beyond those found in the same module. Meanwhile, this proposal is only about individualTypedDict
s, shares none of the module-scoping logic, and can be seen as introducing a new kind of structural type, whereas@sealed
is about nominal types.The text was updated successfully, but these errors were encountered: