Parameterizing Literals
Literal types may contain one or more literal bools, ints, strs, bytes, andenum values. However, literal types cannot contain arbitrary expressions:types like Literal[my_string.trim()]
, Literal[x > 3]
, or Literal[3j + 4]
are all illegal.
Literals containing two or more values are equivalent to the union of those values.So, Literal[-3, b"foo", MyEnum.A]
is equivalent toUnion[Literal[-3], Literal[b"foo"], Literal[MyEnum.A]]
. This makes writing morecomplex types involving literals a little more convenient.
Literal types may also contain None
. Mypy will treat Literal[None]
as beingequivalent to just None
. This means that Literal[4, None]
,Union[Literal[4], None]
, and Optional[Literal[4]]
are all equivalent.
Literals may also contain aliases to other literal types. For example, thefollowing program is legal:
- PrimaryColors = Literal["red", "blue", "yellow"]
- SecondaryColors = Literal["purple", "green", "orange"]
- AllowedColors = Literal[PrimaryColors, SecondaryColors]
- def paint(color: AllowedColors) -> None: ...
- paint("red") # Type checks!
- paint("turquoise") # Does not type check
Literals may not contain any other kind of type or expression. This means doingLiteral[my_instance]
, Literal[Any]
, Literal[3.14]
, orLiteral[{"foo": 2, "bar": 5}]
are all illegal.