Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I type hint for Enums in Python?

I have a python function for which I want to use type hinting.
There are two arguments. The first is any Enum class, the second optional arg is an element of that Enum.

For example, say I have:

class Foo(Enum):
    ALPHA = 1
    BETA = 2
    GAMMA = 3

The first arg would be, e.g. Foo, the second would be e.g. Foo.ALPHA

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What would be the correct way of type hinting this? What I have so far is:

def switch(options: Enum, selected: Optional[Enum] = None) -> Enum:
   # Rest of fn...

but that doesn’t seem right.

>Solution :

Define a TypeVar with Enum as a bound, and then specify that your function takes the Type of that typevar and returns an instance of it:

from enum import Enum
from typing import Optional, Type, TypeVar

_E = TypeVar('_E', bound=Enum)

def switch(
    options: Type[_E],
    selected: Optional[_E] = None
) -> _E:
    ...

Testing it in mypy with an actual Enum subclass:

class Foo(Enum):
    ALPHA = 1
    BETA = 2
    GAMMA = 3

reveal_type(switch(Foo, Foo.ALPHA))  # Revealed type is "Foo"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading