enum - Support for enumerations in Python

PythonServer Side ProgrammingProgramming

Enumeration is a set of identifiers (members) given unique and constant values. Within an enumeration, the members can be compared by identity. Enumeration object can also terated over.

The enum module defines following classes

Enum : Base class for creating enumerated constants.

IntEnum : Base class for creating enumerated constants that are also subclasses of int.

Enumerations are created using the class syntax

#enumexample.py
from enum import Enum
class langs(Enum):
Python = 1
Java = 2
Cpp = 3
Ruby = 4

Enumeration members have human readable string representation and repr representation.

>>> from enumexample import langs
>>> print (langs.Python)
langs.Python
>>> print (repr(langs.Python))
<langs.Python: 1>

Each enum member has name and value properties.

>>> x = langs.Python
>>> x.name
'Python'
>>> x.value
1

You can use a loop to iterate over all members.

>>> for lang in langs:
print (lang.name, lang.value)
Python 1
Java 2
Cpp 3
Ruby 4

Members can be accessed with the help of value or identity

>>> langs(3)
<langs.Cpp: 3>
>>> langs['Java']
<langs.Java: 2>

Identity operators is and is not can be used to compare members of enum.

>>> x = langs(2)
>>> y = langs(4)
>>> x is y
False

Having two enum members with the same name is invalid. However, two enum members are allowed to have the same value. Change enumexample.py to following:

from enum import Enum
class langs(Enum):
Python = 1
Java = 2
Cpp = 3
Ruby = 4
Cplusplus = 3
>>> from enumexample import langs
>>> langs.Cpp
<langs.Cpp: 3>
>>> langs.Cplusplus
<langs.Cpp: 3>
>>> langs(3)
<langs.Cpp: 3>

By default, enumerations can have multiple names as aliases for the same value. To ensure unique value, use @enum.unique A class decorator specifically for enumerations.

raja
Published on 16-Apr-2019 15:43:12
Advertisements