I created an enum base class to standardize reverse lookups on simple enums.
from enum import Enum
class ReversibleEnum(Enum):
@classmethod
def fromName(cls, str):
return getattr(cls, str.lower())
@classmethod
def fromValue(cls, value):
return cls._value2member_map_[value]
Is there is an official way to get one's hands on the _value2member_map_
dict? (or is there a standard way to do this that I missed?)
Thanks!
3. “ name ” keyword is used to display the name of the enum member. 4. Enumerations are iterable. They can be iterated using loops 5. Enumerations support hashing. Enums can be used in dictionaries or sets. 1. By value :- In this method, the value of enum member is passed. 2. By name :- In this method, the name of enum member is passed.
Enum does have a __contains__ method, but it checks for member names rather than member values: Internally (in CPython) they do have a private attribute that maps values to names (will only work for hashable values though): >>> 2 in TestEnum._value2member_map_ True >>> 3 in TestEnum._value2member_map_ False
Enumerations are Python classes, and can have methods and special methods as usual. If we have this enumeration: >>> class Mood(Enum): ... FUNKY = 1 ...
To make your own Enum’s boolean evaluation depend on the member’s value add the following to your class: Enum classes always evaluate as True. If you give your Enum subclass extra methods, like the Planet class above, those methods will show up in a dir () of the member, but not of the class:
Getting members is supported both by name and by value:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
>>> Color['RED'] # note square brackets
<Color.RED: 1>
>>> Color(1)
<Color.RED: 1> # note round parenthesis
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With