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?
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']
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?
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']