Python enum


An enum (enumeration) is a set of symbolic names bound to unique constant values.

We can use enums by referring to their names, as opposed to an index number. The constant value can be any type: numeric or text. As the example below:

currency = enum(EUR='Euro',USD='United States Dollar', GBP='Great British Pound')
print(currency.USD)

Related course

Module enum installation
To use enums module, you need Python 3.4; To install for Python 3.4:

sudo pip install enum34

For older versions (Python 2.7):

sudo pip install aenum

enum example (using enum/aenum)
We can create an Enum after importing the class Enum from either the module enum or aenum.
After importing the list

#from enum import Enum
from aenum import Enum
 
class Numbers(Enum):
    ONE = 1
    TWO = 2
    THREE = 3
    FOUR = 4
 
print(Numbers.ONE.value)
print(Numbers.THREE.value)

or as a one liner:

#from enum import Enum
from aenum import Enum
 
class Numbers(Enum):
    ONE, TWO, THREE, FOUR = 1,2,3,4
 
print(Numbers.ONE.value)
print(Numbers.THREE.value)

enum example (without using modules)
The old way of creating enums is:

def enum(**enums):
    return type('Enum', (), enums)
 
Numbers = enum(ONE=1,TWO=2, THREE=3, FOUR=4, FIVE=5, SIX=6)
print(Numbers.ONE)

Python Debugging