pythonpython-typing

Type hint for a list of possible values


I have a function which can take a fixed list of values: e.g.

def func(mode="a"):
   if mode not in ["a", "b"]:
      raise AttributeError("not ok")

is there a way to type hint it can only be one of these two values?


Solution

  • I think you want a literal type:

    def func(mode: Literal["a", "b"] = "a"):
        if mode not in ["a", "b"]:
            raise AttributeError("not ok")
    

    This was introduced in Python 3.8, via PEP 586.