pythontypesliteralstypingpython-3.8

Getting the literal out of a python Literal type, at runtime?


How can I get the literal value out of a Literal[] from typing?

from typing import Literal, Union

Add = Literal['add']
Multiply = Literal['mul']
Action = Union[Add,Multiply]

def do(a: Action):
    if a == Add:
        print("Adding!")
    elif a == Multiply:
        print("Multiplying!")
    else:
        raise ValueError

do('add')

The code above type checks since 'add' is of type Literal['add'], but at runtime, it raises a ValueError since the string 'add' is not the same as typing.Literal['add'].

How can I, at runtime, reuse the literals that I defined at type level?


Solution

  • The typing module provides a function get_args which retrieves the arguments with which your Literal was initialized.

    >>> from typing import Literal, get_args
    >>> l = Literal['add', 'mul']
    >>> get_args(l)
    ('add', 'mul')
    

    However, I don't think you gain anything by using a Literal for what you propose.