Table of Contents
In this tutorial I will give you an overview on Python enum
class and different python script examples to declare and access Enum
members
Overview on Python enum class
- An enumeration is a set of symbolic names (members) bound to unique, constant values.
- The
enum
module provides an implementation of an enumeration type, with iteration and comparison capabilities. - It can be used to create well-defined symbols for values, instead of using literal strings or integers.
- This module defines four enumeration classes that can be used to define unique sets of names and values:
Enum
,IntEnum
,Flag
, andIntFlag
. - It also defines one decorator,
unique()
, and one helper,auto
.
Creating Enumerations
- A new enumeration is defined using the class syntax by subclassing
Enum
and adding class attributes describing the values. - The members of the
Enum
are converted to instances as the class is parsed. - Each instance has a name property corresponding to the member name and a value property corresponding to the value assigned to the name in the class definition.
# Define an enumeration subclass Enum from enum import Enum class errorcode(Enum): success = 0 warning = 1 invalid = 2
Here,
- The class
errorcode
is an enumeration (orenum
) - The attributes
errorcode.success
,errorcode.warning
,errorcode.invalid
etc., are enumeration members (or enum members) and are functionally constants. - The
enum
members havenames
andvalues
(the name oferrorcode.success
issuccess
, the value oferrorcode.success
is0
, etc.)
Declare and print Enum members
In this sample python script I will access the enumerations and print them using different methods.
#!/usr/bin/env python3 from enum import Enum class errorcode(Enum): success = 0 warning = 1 invalid = 2 # Print Enum member "success" for class "errorcode" using string format print('Exit message: {}'.format(errorcode.success)) # Print Enum member "invalid" for class "errorcode" print('Exit message:', errorcode.invalid) # Print Enum member "warning" for class "errorcode" print('Exit message:', errorcode(1))
The output from this script:
# python3 create_enum.py
Exit message: errorcode.success
Exit message: errorcode.invalid
Exit message: errorcode.warning
Print Enum members as string type
To print enum
members as string type you can use str()
function. The default type of an enumeration member is the enumeration it belongs to:
#!/usr/bin/env python3 from enum import Enum class errorcode(Enum): success = 0 warning = 1 invalid = 2 # Print default type print('Before: ', type(errorcode.invalid)) # Change the type to string enum_str = str(errorcode.invalid) # Check type of variable print('After: ', type(enum_str))
The output from this script:
# python3 create_enum.py
Before: <enum 'errorcode'>
After: <class 'str'>
Print IntEnum members as Integers type
Similarly to print Enum
members as Integers we can use int()
function but we must also use IntEnum
subclass instead of Enum
#!/usr/bin/env python3 from enum import IntEnum class errorcode(IntEnum): success = 0 warning = 1 invalid = 2 # Print default type print('Before: ', type(errorcode.invalid)) # Change the type to string enum_int = int(errorcode.invalid) # Check type of variable print('After: ', type(enum_int))
The output from this script:
# python3 create_enum.py
Before: <enum 'errorcode'>
After: <class 'int'>
Print Enum member’s properties
The members of the Enum
are converted to instances as the class is parsed. Each instance has a name
property corresponding to the member name and a value
property corresponding to the value assigned to the name in the class definition.
#!/usr/bin/env python3 from enum import Enum class errorcode(Enum): success = 0 warning = 1 invalid = 2 # Different method to access the enum members and it's properties print('Member Name:', errorcode.success.name, ', Member Value:', errorcode.success.value) print('Member Name:', errorcode(1).name, ', Member Value:', errorcode(1).value)
Output from this script:
# python3 create_enum.py
Member Name: success , Member Value: 0
Member Name: warning , Member Value: 1
Print Enum member as repr
The repr()
function returns a printable representation of the given object
#!/usr/bin/env python3 from enum import Enum class errorcode(Enum): success = 0 warning = 1 invalid = 2 print('repr representation: ',repr(errorcode.success))
The output from this example script:
# python3 create_enum.py
repr representation: <errorcode.success: 0>
Print Enum member as iterable
Enumerations support iteration, in definition order. Iterating over the enum
class produces the individual members of the enumeration.
#!/usr/bin/env python3 from enum import Enum class errorcode(Enum): success = 0 warning = 1 invalid = 2 for member in errorcode: print(member.name, '=', member.value)
The output from this script shows the members are produced in the order they are declared in the class
definition. The names
and values
are not used to sort them in any way.
# python3 create_enum.py
success = 0
warning = 1
invalid = 2
Creating Enumerations Programmatically
In some cases, it is more convenient to create enumerations programmatically, rather than hard-coding them in a class definition. For those situations, Enum
also supports passing the member names
and values
to the class
constructor.
Syntax:
Enum(value='NewEnumName', names=<...>, *, module='...', qualname='...', type=<mixed-in class>, start=1)
The value argument is the name of the enumeration, which is used to build the representation of members. The names
argument lists the members of the enumeration. When a single string is passed, it is split on whitespace
and commas
, and the resulting tokens are used as names
for the members, which are automatically assigned values
starting with 1.
#!/usr/bin/env python3 from enum import Enum errorcode = Enum ( value = 'Exit Code', names = ('success warning invalid'), ) # Print single member print('Member: ', errorcode.success) # Iterate over all the members print('\nAll members:') for member in errorcode: print(member.name, '=', member.value)
Output from this script:
# python3 create_enum.py
Member: Exit Code.success
All members:
success = 1
warning = 2
invalid = 3
The reason for defaulting to 1 as the starting number and not 0 is that 0 is False
in a boolean sense, but enum
members all evaluate to True
.
For more control over the values associated with members, the names string can be replaced with a sequence of two-part tuples or a dictionary mapping names to values.
In this example, a list of two-part tuples is given instead of a single string containing only the member names. This makes it possible to reconstruct the "errorcode
" enumeration with the members in the same order as the version we defined as hard coded values earlier.
#!/usr/bin/env python3 from enum import Enum errorcode = Enum ( value = 'Exit Code', names = [ ('success', 0), ('warning', 1), ('invalid', 2), ], ) for member in errorcode: print(member.name, '=', member.value)
The output from this script:
# python3 create_enum.py
success = 0
warning = 1
invalid = 2
Conclusion
In this tutorial we learned about Enum in Python and different methods to declare enum
members with it's properties. We have covered major use cases of Enum
and intEnum
sub class but there are other content of the enum module i.e. Intflag
, Flag
, unique()
and auto
With enum.unique()
Enum
class decorator that ensures only one name is bound to any one value and with enum.auto
instances are replaced with an appropriate value for Enum
members.
Lastly I hope this tutorial on Python enum
in Linux Programming was helpful. So, let me know your suggestions and feedback using the comment section.
References
I have used below external references for this tutorial guide
The Python 3 Standard Library by Example
python.org enum