

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
enum - Support for enumerations in Python
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.
- Related Questions & Answers
- Support for Enumerations in Python
- What are enumerations in Java? How to retrieve values from an enum?
- Python Support for gzip files (gzip)
- Python Support for bzip2 compression (bz2)
- Support for line-oriented command interpreters in Python
- Enum in Python
- Enumerations in Dart Programming
- How MySQL handles the empty and null values for enumerations?
- Python class browser support
- Does Python support polymorphism?
- Constructor overloading in enumerations in Java.
- Enum for days of week in Java
- Set ENUM in MySQL for column values
- HyperText Markup Language support in Python?
- Does Python support multiple inheritance?