Python Typing: Given Set of Values

前端 未结 2 1902
没有蜡笔的小新
没有蜡笔的小新 2021-01-23 03:16

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 minima

相关标签:
2条回答
  • 2021-01-23 03:46

    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
    
    0 讨论(0)
  • 2021-01-23 03:56

    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')
    
    0 讨论(0)
提交回复
热议问题