Python Typing: Given Set of Values

寵の児 提交于 2020-03-16 08:12:18

问题


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?


回答1:


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



回答2:


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')


来源:https://stackoverflow.com/questions/58521577/python-typing-given-set-of-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!