64
votes

I have this piece of code:

import enum


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


def get_color_return_something(some_color):
    pass

How do I properly add type annotations to the some_color variable in this function, if I suppose that I'll receive an enum attribute from the Color enum (for example: Color.RED)?

3
Color.RED.value ? - GraphicalDot
Yes, the some_color should have value from the Color Enum @GraphicalDot - Yuval Pruss
I'm proposing an edit since the question is really about enum attributes, not values. - Garrett

3 Answers

53
votes

Type hinting the Color class should work:

def get_color_return_something(some_color: Color):
    print(some_color.value)
3
votes
def get_color_return_something(some_color: Color):
    pass
0
votes

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)