I have started couple of threads before about adding `Generic` support for `TypedDict`. But this thread is specifically to get an idea about the viability to let `TypedDict` classes inherit from `Generic` **without a PEP change**. Specifically the impact on type checker implementations. The discussion was started in https://bugs.python.org/issue44863 (and associated PR: https://github.com/python/cpython/pull/27663).
Copied (with minor edits) my reasoning from https://bugs.python.org/issue44863 ::
TypedDict PEP-589 says: A TypedDict cannot inherit from both a TypedDict type and a non-TypedDict base class.
So the current run time implementation has: `if type(base) is not _TypedDictMeta: raise TypeError(...)`
This restricts the user from defining generic TypedDicts in the natural class based syntax: `class Pager(TypedDict, Generic[T]): ...`
Although PEP 589 doesn't explicitly state generic support. I believe it is complete in covering all semantic details even with Generics. Even structural subtyping because it says: "Value types behave invariantly, since TypedDict objects are mutable."
I have tried putting together a PEP from guidance of typing-sig https://github.com/sransara/py-generic-typeddict/blob/master/pep-9999.rst. There is not much new contributions by that draft, except for specifying the alternative syntax and being more explicit about Generics: 1. relaxing this line from PEP-589 and be explicit to include Generic: "A TypedDict cannot inherit from both a TypedDict type and a non-TypedDict base class." (IMO by thinking `Generic` as a mixin even this is not needed) 2. may be syntax for generic in the alternative syntax (side note: collecting typevars from the values is hard to implement because of forward refs) 3. Some explicit generic examples for good measure
So I'm wondering if it would be possible to relax the constraint: TypedDict inheritance to include Generic. In my point of view `Generic` is more of a mixin, so it doesn't go against the PEP 589. Or is this change really big enough to warrant a new PEP or PEP update?
My understanding was that during initial implementation this was not done for the sake of implementation simplicity (days before PEP-560).
All that said, a new PEP would be a good way to notify the type checkers of this capability.
Please let me know your thoughts.
I can't speak for the maintainers of other type checkers, but this change would be simple to make within pyright. Just a few lines of code and some test cases.
The runtime will need to change to accommodate this, so type checkers will probably want to add some logic that warns users if they are on a version of Python that will generate an exception if they include `Generic`.
My personal view is that this shouldn't require an entirely new PEP — that a small change to PEP 589 should suffice.
--- Eric Traut Contributor to Pyright & Pylance Microsoft Corp.