Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type hint for a list of possible values [duplicate]

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?

like image 493
Christian Sauer Avatar asked Dec 05 '25 21:12

Christian Sauer


1 Answers

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.

like image 163
jonrsharpe Avatar answered Dec 08 '25 09:12

jonrsharpe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!