I was catching up on some discussions about
TypedDict and noticed that the topic of
TypedDict has come up repeatedly but there seems to be no thread for directly discussing it.
In particular I noticed in this thread on subclassing that:
- @hauntsaninja specifically called out that the semantics need to be decided
- Pyright and Pylance appear to have supported it in the past mainly for type narrowing, then @erictraut mentiond that he decided that because the behavior is undefined it would be better to just narrow in an unsound way.
- MyPy has a longstanding open discussion on this, and also a discussion about whether to allow unsound narrowing without @final on the grounds that
@finalis without meaning
In my opinion the semantics are not entirely 100% specified right now. No PEP actually discusses
@final, nor does the current typing spec, so the most reasonable conclusion is that as of today
@final is meaningless and TypedDicts always allow structural subtyping.
But it also would be reasonable to treat
@final TypedDicts as exact, given how final classes work. I actually thought that was already true (and it sounds like at least for a while Pyright and Pylance treated it this way), and as far as I can tell it doesn’t cause problems in the type system if we were to declare that
TypedDict into an exact structural type.
I noticed a few comments in other threads suggesting that it’s not meaningful to talk about exact types with structural typing. I believe this is not inherently true; today Python only has “open” structural types that allow structural subtyping, but “exact” structural types make sense and can coexist with open types.
Two examples I know of offhand of languages that allow both open (structural subtypes) and exact structural types:
- Flow objects are exact by default (like the proposed
TypedDict) but can be explicitly marked as open.
- Ocaml objects behave similarly, closed by default but there’s syntax to allow structural subtyping
Typescript objects are open by default unlike Flow, but there is a long-standing discussion about adding an explicit
Exact form. It’s not clear whether it will be added (and the discussion there is likely informative for us since open-by-default is the existing
Since this appears to be a question of whether we want semantics to exist that haven’t been specified thus far, I thought it would make sense to have a thread where people can directly express views on this, rather than leaving to issue trackers and as a side topic in other threads.