Search code examples
pythonpython-typing

Accessing typing.Literal values


How can the literals of a typing.Literal be accessed (and iterated over)?

For context, this is to avoid having to define the list of literals twice.


Solution

  • typing.get_args can be used to that end.

    MyLiteral = Literal["foo", "bar"]
    
    for literal_option in typing.get_args(MyLiteral):
        print(literal_option)