There are two ways to set up an enumeration in Python:
Subclassing the Enum class. This is the most common way to create an enumeration in Python. To do this, you simply subclass the
Enum class and define the members of the enumeration. For example, the following code defines an enumeration called
Color:
Python
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
Using the functional API. The Enum class also provides a functional API that you can use to create enumerations without using the usual class syntax. For example, the following code defines an enumeration called
Color using the functional API:
Python
from enum import Enum
Color = Enum('Color', 'RED GREEN BLUE')
The functional API is a bit more concise, but it is less flexible than subclassing the
Enum class.
Here are some of the benefits of using enumerations in Python:
Enumerations are a way to represent a set of named constants.
Enumerations are type-safe, which means that you can be sure that the values of an enumeration are always valid.
Enumerations are easy to use and to read.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
There are two ways to set up an enumeration in Python:
Enumclass. This is the most common way to create an enumeration in Python. To do this, you simply subclass theEnumclass and define the members of the enumeration. For example, the following code defines an enumeration calledColor:Python
Enumclass also provides a functional API that you can use to create enumerations without using the usual class syntax. For example, the following code defines an enumeration calledColorusing the functional API:Python
The functional API is a bit more concise, but it is less flexible than subclassing the
Enumclass.Here are some of the benefits of using enumerations in Python: