Python equivalent to TypeScript type unions?

Question:

In TypeScript you can create a type defined by a set of particular elements:

type Context = '2d' | 'webgl' | 'webgl2'

class CanvasFacade {
  constructor(ctx: Context) {}
}

Are there any recommended ways to achieve this in Python? Presumably using libraries such as typing? Enums?

Asked By: Michael Moreno

||

Answers:

You’re looking for typing.Union, for general unions. However, in Python, literal string types are not written as strings, so the type called '2d' in Typescript is equivalent to Literal['2d'] in Python, where Literal is also from typing.

Union[Literal['2d'], Literal['webgl'], Literal['webgl2']]

Now, if you’re using Python 3.10 or newer, you can benefit from PEP 604, which allows writing union types with the bitwise-or operator.

Literal['2d'] | Literal['webgl'] | Literal['webgl2']

Finally, because this "union of literals" pattern is so common, the Literal type supports it directly.

Literal['2d', 'webgl', 'webgl2']
Answered By: Silvio Mayolo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.