You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
"'field' in typed_dict_union" discrimination #13802
This has been discussed previously in various typing forums. (I can't find the threads currently, but perhaps someone else can find a pointer.)
The problem here is that narrowing based on field discrimination within a TypedDict isn't type safe unless that TypedDict class is marked @final. Otherwise it would be possible for a subclass of B to add a field foo.
With an @final decorator on A and B it should be possible for mypy to implement type narrowing based on field discrimination. I've implemented this support in pyright. Currently, mypy emits an error if you attempt to add a @final decorator to a TypedDict class.
fromtypingimportTypedDict, final@finalclassA(TypedDict):
foo: int@finalclassB(TypedDict):
bar: intdeffunc(union: A|B):
if"foo"inunion:
reveal_type(union) # Aelse:
reveal_type(union) # B
Activity
erictraut commentedon Oct 3, 2022
This has been discussed previously in various typing forums. (I can't find the threads currently, but perhaps someone else can find a pointer.)
The problem here is that narrowing based on field discrimination within a
TypedDictisn't type safe unless thatTypedDictclass is marked@final. Otherwise it would be possible for a subclass ofBto add a fieldfoo.With an
@finaldecorator onAandBit should be possible for mypy to implement type narrowing based on field discrimination. I've implemented this support in pyright. Currently, mypy emits an error if you attempt to add a@finaldecorator to aTypedDictclass.hauntsaninja commentedon Oct 3, 2022
#7981 is probably the right mypy issue to track this
ikonst commentedon Oct 4, 2022
Thanks for the pointer @hauntsaninja, indeed appears to be addressed in #13557. Happy to test once it makes its way into the next release.
hauntsaninja commentedon Oct 4, 2022
Only half the feature is implemented; want to take a shot at completing it?