I'd like to do something like:
from typing import TypeVar, Generic, TypedDict
T = TypeVar("T")
class Foo(Generic[T], TypedDict):
bar: T
...
foo: Foo[int] = {"bar": 42}
But this yields a type error ("cannot inherit from both a TypedDict and a non-TypedDict base class").
Are there any ways to achieve this result?
This is not possible at the moment. You cannot inherit from both a TypedDict and a non-TypedDict base class. But there is issue active on the cpython repository and a discussion going on to support this feature.
EDIT: As per the latest update, this feature is now available in python 3.11.
If one can't upgrade to Python 3.11, a workaround would be to use typing-extensions module instead of built-in typings module. I use Python 3.10 and typing-extensions 4.9.0 and it works as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With