How would I constrain a method to only return one of a set of specific values in python?
Question:
Is there a pythonic way to constrain the output of a method so that it can only be one of a set? Sort of like typing but for specific values only. I hope you can see what I’m trying to get at with this snippet:
class Rule:
def evaluate(self, user_id: int) -> {"PASS", "FAIL", "ERROR"}:
...
In the above case I would be hoping for evaluate to only return "PASS", "FAIL" or "ERROR"
Answers:
You could create a separate class with all the description and add it as arguments whilst coding. I would recommend you to to watch a few youtube videos of how to create classes, and maybe you could try implement it.
In python 3.8 or higher, you can use Literal types:
from typing import Literal
class Rule:
def evaluate(self, user_id: int) -> Literal["PASS", "FAIL", "ERROR"]:
...
Yes there is. Commonly Enum
is used for this. (https://docs.python.org/3/library/enum.html)
from enum import Enum
class Evaluate(Enum):
PASS = "value1"
FAIL = "value2"
ERROR = "value3"
class Rule:
def evaluate(self, user_id: int) -> Evaluate:
...
Is there a pythonic way to constrain the output of a method so that it can only be one of a set? Sort of like typing but for specific values only. I hope you can see what I’m trying to get at with this snippet:
class Rule:
def evaluate(self, user_id: int) -> {"PASS", "FAIL", "ERROR"}:
...
In the above case I would be hoping for evaluate to only return "PASS", "FAIL" or "ERROR"
You could create a separate class with all the description and add it as arguments whilst coding. I would recommend you to to watch a few youtube videos of how to create classes, and maybe you could try implement it.
In python 3.8 or higher, you can use Literal types:
from typing import Literal
class Rule:
def evaluate(self, user_id: int) -> Literal["PASS", "FAIL", "ERROR"]:
...
Yes there is. Commonly Enum
is used for this. (https://docs.python.org/3/library/enum.html)
from enum import Enum
class Evaluate(Enum):
PASS = "value1"
FAIL = "value2"
ERROR = "value3"
class Rule:
def evaluate(self, user_id: int) -> Evaluate:
...