Python arbritary keys in TypedDict

839 Views Asked by At

Is it possible to make a TypedDict with a set of known keys and then a type for an arbitrary key? For example, in TypeScript, I could do this:

interface Sample {
  x: boolean;
  y: number;

  [name: string]: string;
}

What is the equivalent in Python?


Edit: My problem is that I make a library where a function's argument expects a type of Mapping[str, SomeCustomClass]. I want to change the type so that there are now special keys, where the types are like this:

  • labels: Mapping[str, str]
  • aliases: Mapping[str, List[str]]

But I want it to still be an arbitrary mapping where if a key is not in the two special cases above, it should be of type SomeCustomClass. What is a good way to do this? I am not interested in making a backwards-incompatible change if there is an alternative.

1

There are 1 best solutions below

0
Roman On

That is possible with Union type operator, but unfortunately with this solution, you lose checking the required fields:

from typing import TypedDict, Union, Dict

class SampleRequiredType(TypedDict, total=True):
  x: bool
  y: int

SampleType = Union[SampleRequiredType, Dict]

# Now all these dictionaries will be valid:

dict1: SampleType = {
  'x': True,
  'y': 123
}

dict2: SampleType = {
  'x': True,
  'y': 123
  'z': 'my string' 
}

dict3: SampleType = {
  'z': 'my string' 
}