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"

Asked By: Kit

||

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.

Answered By: Joseph Mattouk

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"]:
        ...
Answered By: jprebys

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:
        ...
Answered By: João Bonfim
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.