Given this type:
class TPerson(TypedDict):
name: str
address: str
I want another TypedDict
inheriting the previous one, like:
class TDealer(TPerson):
db-id: int
police_record: str
arrested_now: bool
class TConsumer(TPerson):
db-id: int
preferred_product: str
stoned_now: bool
But, since db-id
is not a valid identifier, I need to use functional syntax both for TDealer
and TConsumer
.
Is it possible to inherit from another TypedDict
using functional syntax?
I see TypedDict
definition is like:
class _TypedDict(Mapping[str, object], metaclass=ABCMeta):
But not sure 100% if this is a No!
If not, which could be a nice workaround?
Not directly, but there are a number of workarounds.
Including the fields of TPerson
directly into its "subclasses":
TDealer = TypedDict('TDealer', {'name': str, 'address': str, 'db-id': int, 'police_record': str, 'arrested_now': bool}
TConsumer = TypedDict('TConsumer', {'name': str, 'address': str, 'db-id': int, 'preferred_product': str, 'stoned_now': bool})
Making mix-ins:
class TPerson(TypedDict):
name: str
address: str
TDealer = TypedDict('TDealer', {'db-id': int, 'police_record': str, 'arrested_now': bool}
TConsumer = TypedDict('TConsumer', {'db-id': int, 'preferred_product': str, 'stoned_now': bool})
class TDealer(TDealer, TPerson):
pass
class TConsumer(TConsumer, TPerson):
pass
Both subclasses share db-int
, so you could consider moving that to TPerson
:
TPerson = TypedDict('TPerson', {'name': str, 'address': str, 'db-id': int})
class TDealer(TPerson):
police_record: str
arrested_now: bool
class TConsumer(TPerson):
preferred_product: str
stoned_now: bool
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