Insights from Our Experts
Implementing Enum in Python
Enum is a data type consisting of a set of named values called elements, members or enumerators of the type. These enumerated named values function as constants in the computing language. For instance a Color enum many include named values like Red, Green and Yellow.
Enumerations in Python are implemented by using the module named ‘enum’. Enumerations are created using classes. Enums have names and values associated with them.
Python 3.x has built in type enum. Otherwise
pip install enum34
For creating an enumerated type Card
Or enum could be directly invoked as
where Cards will be the enum name and ['Club', 'Diamond', 'Heart','Spade'] will be the enum members, They could be list or name-value pairs or dict.Unless value is not specified the default values will be the lidt indices (the start indices could be specified explicitly by setting start parameter)
Accessing enum values
Enum members could be accessed by 2 ways
1. By name: In this method, the name of enum member is passed.
2. By value: In this method, the value of enum member is passed.
1. Identity:- These are checked using keywords “is” and “is not“.
2. Equality:- Equality comparisons of “==” and “!=” types are also supported.
- The special attribute __members__ is an ordered dictionary mapping names to members. It includes all names defined in the enumeration
Uniqueness in value
If enum members are required to have unique value assignment then @unique is added. ValueError exception will be raised if member value repeats.
Pythonic programmatic way for enum creation
Rather than hardcoding the enum in class definition,
A small comparison between the earlier and enum usage
Converting it to use enum
Advantageous of using enum
- If you use enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.
- Enums are not allocated in memory. They only exists in compilation stage.
- A new developer could easily understand the variable type and the values that could be allocated for that variable. It will be clearer.
- If any error is present, it'll be seen in compile time itself.
- An enum that is identical across Python and the database management system could prevent lots of hard-to-find bug.
- Always check the input values before accepting them into your system. It could resist malicious input.
Note: Overuse of enums might mean that your methods do too much (it's often better to have several separate methods, rather than one method that takes several flags which modify what it does), but if you have to use flags or type codes, enums are the way to go.