Search code examples
pythonmypy

Programmatic generation of Literal options


MyPy's Literal type can be super useful for defining available options. Is it possible to generate a literal type programmatically, e.g. from a canonical registry?

e.g.

class Dispatcher():
    func_reg = {
        'f1': my_func,
        'f2': new_func,
        'f3': shoe_func,
    }

    def dispatch(cls, func_name: Literal[*func_reg.keys()]) -> Whatever:
        pass

Solution

  • Unfortunately, the answer is no.

    According to the mypy documentation:

    Literal types may contain one or more literal bools, ints, strs, bytes, and enum values. However, literal types cannot contain arbitrary expressions: types like Literal[my_string.trim()], Literal[x > 3], or Literal[3j + 4] are all illegal.