Type annotations for Enum value

Posted on

Question :

Type annotations for Enum value

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

How do I properly add type annotations to the some_color varaible in this function, if I suppose to receive a value from the Color enum (for example: Color.RED)?

Answer #1:

Type hinting the Color class should work:

def get_color_return_something(some_color: Color):
Answered By: ibarrond

Answer #2:

def get_color_return_something(some_color: Color):
Answered By: Ramazan Polat

Answer #3:

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:
        return ValueError(f"It's not {Color.RED}")

Answered By: Paul Weemaes

Leave a Reply

Your email address will not be published. Required fields are marked *