0

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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
JohnD
  • 456
  • 1
  • 5
  • 13
  • I don't understand your question, or what you are even trying to accomplish. Why do you want `type(Options.A)` to return a string? – juanpa.arrivillaga Dec 10 '19 at 15:48
  • Does this answer your question? https://stackoverflow.com/q/58521577/476 – deceze Dec 10 '19 at 15:50
  • Are you looking for `Options.A.name` or `Options.A.value`? Those will get you the strings `"A"` and `"a"` respectively. I think explicitly using these fields are better alternatives to mixing in a str or doing `str(Options.A)` or whatever. Or alternatively, consider stopping using Enums altogether: the fact that they're normally distinct from strs or ints or whatever is supposed to be a feature. So if you're trying to circumvent that, Enums may not be the right tool for you to currently be using. – Michael0x2a Dec 11 '19 at 19:58

2 Answers2

1
>>> 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
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • Thank you, mixing worked for me. Would you mind replying why mixing worked or what is mixing specifically? – JohnD Dec 10 '19 at 19:28
  • @JohnD: `mixing` is just giving your (sub)class one more parent. Originally, your `Options` class only had `Enum` for a parent (and so inherited `Enum` methods, properties, etc.), but when you mix-in, or add, `str` as a parent then your `Options` `Enum` also gets those properties, methods, etc., as well as also being that type. For instance, `Options.A.upper() == 'A'` -> `True`. – Ethan Furman Dec 11 '19 at 01:57
0

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))
MEDZ
  • 2,227
  • 2
  • 14
  • 18