简体   繁体   中英

How do I use typing to force using a specific enum as an argument in python

I'm trying to write a function that would only except a specific enum that each value is a string so the function could not except a string but would get the wanted value from the enum

from enum import Enum

class Options(Enum):
    A = "a"
    B = "b"
    C = "c"

def some_func(option: Options):
    # some code
    return option

The problem I'm experiencing is that if I check the type I get this instead of a string:

>>> type(Options.A)
<enum 'Options'>

I would like to have it return this:

>>> type(Options.A)
<class 'str'>

Any idea how I can implement this so it would work the way I intended? Thanks in advance 😁

>>> type(Options.A)

is always going to return

<enum 'Options'>

because Options.A is an <enum 'Options'> member. However, if you want

>>> isinstance(Options.A, str)

to be

True

then you need to mix in the str type:

class Options(str, Enum):
    A = "a"
    B = "b"
    C = "c"

NB If you mix in the str type, then your Enum members become directly comparable with str :

>>> Options.A == 'a'
True

You can cast the value of the enum attribute:

from enum import Enum

class Options(Enum):
    A = "a"
    B = "b"
    C = "c"


str_enum = str(Options.A)
print(type(str_enum))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM