2

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.

Epic Programmer
  • 383
  • 3
  • 12
  • 1
    Fortunately, Python is not TypeScript. There's no such construct in python - usually no one needs it, because dicts are not objects, and I'd put this "rest" into separate key (`x: int; y: int; extra: dict[str, str]`) to reduce namespace polllusion and just improve readability. Then you can keep using a TypedDict or define a normal class. Also, a class with custom `__getattr__` would be the closest possible equivalent, I guess - you can always convert it to dict manually later. – STerliakov Feb 19 '23 at 16:39
  • @SUTerliakov the thing is that I already have a method that takes a dictionary where the keys are all prefixed with "P" and have a certain output type. But I want to make it possible to add some other keys without the prefix and with a different type. It seems to not be possible. – Epic Programmer Feb 19 '23 at 17:29
  • 2
    [XY Problem](https://xyproblem.info) alert! Please edit your post and provide additional context: Why do you think such a construct would be useful? What problem would it solve? Otherwise I agree with @SUTerliakov – Daniil Fajnberg Feb 19 '23 at 18:11
  • A not so shameless plug: thank you Daniil for your [answer](https://stackoverflow.com/a/75507540/6225838) detailing how to address this. – CPHPython Mar 01 '23 at 10:23

0 Answers0