Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python TypedDict: functional syntax when inheriting another TypedDict

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?

like image 952
Aero WuBook Avatar asked Sep 01 '25 11:09

Aero WuBook


1 Answers

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
like image 63
Jasmijn Avatar answered Sep 03 '25 01:09

Jasmijn