Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Enum _value2member_map_ Accessor?

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!

like image 224
Toaster Avatar asked Apr 22 '15 13:04

Toaster


People also ask

How to display the name of the enum member in Python?

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.

Does enum have a __contains__ method in Python?

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

What are enumerations in Python?

Enumerations are Python classes, and can have methods and special methods as usual. If we have this enumeration: >>> class Mood(Enum): ... FUNKY = 1 ...

How do I make an enum member’s value depend on its value?

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:


1 Answers

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
like image 178
Ethan Furman Avatar answered Nov 15 '22 15:11

Ethan Furman