Home > DeveloperSection > Forums > 'Enum' in Python
Monaj Singh
Monaj Singh

Total Post:41

Points:287
Posted on    May-13-2015 12:13 AM

 Python Python  python-3.x 
Ratings:


 1 Reply(s)
 434  View(s)
Rate this:

I'm mainly a C# developer, but I'm currently working on a project in Python.

How can I represent the equivalent of an Enum in Python?



Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    May-13-2015 6:30 AM

Enums have been added to Python 3.4 as described in PEP 435. It has also been backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4 on pypi.

o use backports, do $ pip install enum34, installing enum (no numbers) will install a completely different and incompatible version.

from enum import Enum
Animal = Enum('Animal', 'ant bee cat dog')
or equivalently:

class Animals(Enum):
    ant = 1
    bee = 2
    cat = 3
    dog = 4
In earlier versions, one way of accomplishing enums is:

def enum(**enums):
    return type('Enum', (), enums)
which is used like so:

>>> Numbers = enum(ONE=1, TWO=2, THREE='three')
>>> Numbers.ONE
1
>>> Numbers.TWO
2
>>> Numbers.THREE
'three'
You can also easily support automatic enumeration with something like this:

def enum(*sequential, **named):
    enums = dict(zip(sequential, range(len(sequential))), **named)
    return type('Enum', (), enums)
and used like so:

>>> Numbers = enum('ZERO', 'ONE', 'TWO')
>>> Numbers.ZERO
0
>>> Numbers.ONE
1
Support for converting the values back to names can be added this way:

def enum(*sequential, **named):
    enums = dict(zip(sequential, range(len(sequential))), **named)
    reverse = dict((value, key) for key, value in enums.iteritems())
    enums['reverse_mapping'] = reverse
    return type('Enum', (), enums)
This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw KeyError if the reverse mapping doesn't exist. With the first example:

>>> Numbers.reverse_mapping['three']
'THREE'


Don't want to miss updates? Please click the below button!

Follow MindStick