Type annotations for Enum value

前端 未结 3 1146
甜味超标
甜味超标 2020-12-03 06:40

I have this piece of code:

import enum


class Color(enum.Enum):
    RED = \'1\'
    BLUE = \'2\'
    GREEN = \'3\'


def get_color_return_something(some_col         


        
相关标签:
3条回答
  • 2020-12-03 07:01
    def get_color_return_something(some_color: Color):
        pass
    
    0 讨论(0)
  • 2020-12-03 07:06

    The following will work with Pyton 3.9/PyCharm

    from enum import Enum
    from typing import Optional, Union
    
    
    class Color(Enum):
        RED: int = 1
        GREEN: int = 2
    
    
    def guess_color(x: Union[Color.RED, Color.GREEN]) -> Optional[ValueError]:
        if x == Color.RED:
            print("Gotcha!")
        else:
            return ValueError(f"It's not {Color.RED}")
    
    
    guess_color(Color.RED)
    
    0 讨论(0)
  • 2020-12-03 07:17

    Type hinting the Color class should work:

    def get_color_return_something(some_color: Color):
        print(some_color.value)
    
    0 讨论(0)
提交回复
热议问题