Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Typing: Given Set of Values [duplicate]

I want to type the parameter of a method to be one of a finite set of valid values. So basically, I would like to have the typing equivalent of the following minimal example:

valid_parameters = ["value", "other value"]

def typed_method(parameter):
    if not parameter in valid_parameters:
        raise ValueError("invalid parameter")

I checked typing already, but I didn't manage to find a solution. Maybe I was just not able to fully understand the documentation. Is there such a solution? Can it be created?

like image 623
jonathan.scholbach Avatar asked Dec 05 '25 21:12

jonathan.scholbach


2 Answers

This feature has just been introduced in Python 3.8: typing.Literal. See PEP 586 for details.

Example:

def typed_method(parameter: Literal["value", "other value"]):
    pass
like image 160
deceze Avatar answered Dec 08 '25 09:12

deceze


I want to type the parameter of a method to be one of a finite set of valid values

Use Enum

from enum import Enum


class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3


def handle_color(color):
    if not isinstance(color, Color):
        raise ValueError('Not a color')
    print(color)


handle_color(Color.GREEN)
handle_color('something')
like image 38
balderman Avatar answered Dec 08 '25 11:12

balderman



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!