5

Say I need a list of values both at runtime and as type hint:

from typing import Literal

valid_values = ('foo', 'bar', 'baz')

def f(arg: Literal[???]):
    assert arg in valid_values

Is it possible to unpack valid_values into the Literal type hint somehow, e.g. Literal[*valid_values] (which is invalid syntax)? Repeating the values would be sub-optimal.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    Seems like the arguments to `Literal['foo', 'bar', 'baz']` are collected in the `__args__` attribute, so you could use `L = Literal['foo', 'bar', 'baz']` and then annotate with `def f(arg: L): ...` while using `arg in L.__args__` for the runtime check, but since `__args__` is a dunder attribute this availability might break without being deprecated. – a_guest Oct 23 '19 at 12:27

0 Answers0