This PEP proposes adding an enumeration type to the Python standard library.
An enumeration is a set of symbolic names bound to unique, constant values. Within an enumeration, the values can be compared by identity, and the enumeration itself can be iterated over.
The idea of adding an enum type to Python is not new - PEP 354 is a previous attempt that was rejected in 2005. Recently a new set of discussions was initiated [3] on the python-ideas mailing list. Many new ideas were proposed in several threads; after a lengthy discussion Guido proposed adding flufl.enum to the standard library [4]. During the PyCon 2013 language summit the issue was discussed further. It became clear that many developers want to see an enum that subclasses int, which can allow us to replace many integer constants in the standard library by enums with friendly string representations, without ceding backwards compatibility. An additional discussion among several interested core developers led to the proposal of having IntEnum as a special case of Enum.
The key dividing issue between Enum and IntEnum is whether comparing to integers is semantically meaningful. For most uses of enumerations, it’s a feature to reject comparison to integers; enums that compare to integers lead, through transitivity, to comparisons between enums of unrelated types, which isn’t desirable in most cases. For some uses, however, greater interoperability with integers is desired. For instance, this is the case for replacing existing standard library constants (such as socket.AF_INET) with enumerations.
Further discussion in late April 2013 led to the conclusion that enumeration members should belong to the type of their enum: type(Color.red) == Color. Guido has pronounced a decision on this issue [5], as well as related issues of not allowing to subclass enums [6], unless they define no enumeration members [7].
The PEP was accepted by Guido on May 10th, 2013 [1].
[Based partly on the Motivation stated in PEP 354]
The properties of an enumeration are useful for defining an immutable, related set of constant values that may or may not have a semantic meaning. Classic examples are days of the week (Sunday through Saturday) and school assessment grades (‘A’ through ‘D’, and ‘F’). Other examples include error status values and states within a defined process.
It is possible to simply define a sequence of values of some other basic type, such as int or str, to represent discrete arbitrary values. However, an enumeration ensures that such values are distinct from any others including, importantly, values within other enumerations, and that operations without meaning (“Wednesday times two”) are not defined for these values. It also provides a convenient printable representation of enum values without requiring tedious repetition while defining them (i.e. no GREEN = 'green').
We propose to add a module named enum to the standard library. The main type exposed by this module is Enum. Hence, to import the Enum type user code will run:
Enumerations are created using the class syntax, which makes them easy to read and write. An alternative creation method is described in Functional API. To define an enumeration, subclass Enum as follows:
A note on nomenclature: we call Color an enumeration (or enum) and Color.red, Color.green are enumeration members (or enum members). Enumeration members also have values (the value of Color.red is 1, etc.)
Enumeration members have human readable string representations:
…while their repr has more information:
The type of an enumeration member is the enumeration it belongs to:
Enums also have a property that contains just their item name:
Enumerations support iteration, in definition order:
Enumeration members are hashable, so they can be used in dictionaries and sets:
Sometimes it’s useful to access members in enumerations programmatically (i.e. situations where Color.red won’t do because the exact color is not known at program-writing time). Enum allows such access:
If you want to access enum members by name, use item access:
Having two enum members with the same name is invalid:
However, two enum members are allowed to have the same value. Given two members A and B with the same value (and A defined first), B is an alias to A. By-value lookup of the value of A and B will return A. By-name lookup of B will also return A:
Iterating over the members of an enum does not provide the aliases:
The special attribute __members__ is an ordered dictionary mapping names to members. It includes all names defined in the enumeration, including the aliases:
The __members__ attribute can be used for detailed programmatic access to the enumeration members. For example, finding all the aliases:
Enumeration members are compared by identity:
Ordered comparisons between enumeration values are not supported. Enums are not integers (but see IntEnum below):
Equality comparisons are defined though:
Comparisons against non-enumeration values will always compare not equal (again, IntEnum was explicitly designed to behave differently, see below):
The examples above use integers for enumeration values. Using integers is short and handy (and provided by default by the Functional API), but not strictly enforced. In the vast majority of use-cases, one doesn’t care what the actual value of an enumeration is. But if the value is important, enumerations can have arbitrary values.
Enumerations are Python classes, and can have methods and special methods as usual. If we have this enumeration:
Then:
The rules for what is allowed are as follows: all attributes defined within an enumeration will become members of this enumeration, with the exception of __dunder__ names and descriptors [9]; methods are descriptors too.
Subclassing an enumeration is allowed only if the enumeration does not define any members. So this is forbidden:
But this is allowed:
The rationale for this decision was given by Guido in [6]. Allowing to subclass enums that define members would lead to a violation of some important invariants of types and instances. On the other hand, it makes sense to allow sharing some common behavior between a group of enumerations, and subclassing empty enumerations is also used to implement IntEnum.
A variation of Enum is proposed which is also a subclass of int. Members of an IntEnum can be compared to integers; by extension, integer enumerations of different types can also be compared to each other:
However they still can’t be compared to Enum:
IntEnum values behave like integers in other ways you’d expect:
For the vast majority of code, Enum is strongly recommended, since IntEnum breaks some semantic promises of an enumeration (by being comparable to integers, and thus by transitivity to other unrelated enumerations). It should be used only in special cases where there’s no other choice; for example, when integer constants are replaced with enumerations and backwards compatibility is required with code that still expects integers.
IntEnum will be part of the enum module. However, it would be very simple to implement independently:
This demonstrates how similar derived enumerations can be defined, for example a StrEnum that mixes in str instead of int.
Some rules:
Enumerations can be pickled and unpickled:
The usual restrictions for pickling apply: picklable enums must be defined in the top level of a module, since unpickling requires them to be importable from that module.
The Enum class is callable, providing the following functional API:
The semantics of this API resemble namedtuple. The first argument of the call to Enum is the name of the enumeration. Pickling enums created with the functional API will work on CPython and PyPy, but for IronPython and Jython you may need to specify the module name explicitly as follows:
The second argument is the source of enumeration member names. It can be a whitespace-separated string of names, a sequence of names, a sequence of 2-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to values. The last two options enable assigning arbitrary values to enumerations; the others auto-assign increasing integers starting with 1. A new class derived from Enum is returned. In other words, the above assignment to Animal is equivalent to:
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.
Some variations were proposed during the discussions in the mailing list. Here’s some of the more popular ones.
flufl.enum was the reference implementation upon which this PEP was originally based. Eventually, it was decided against the inclusion of flufl.enum because its design separated enumeration members from enumerations, so the former are not instances of the latter. Its design also explicitly permits subclassing enumerations for extending them with more members (due to the member/enum separation, the type invariants are not violated in flufl.enum with such a scheme).
Michael Foord proposed (and Tim Delaney provided a proof-of-concept implementation) to use metaclass magic that makes this possible:
The values get actually assigned only when first looked up.
Pros: cleaner syntax that requires less typing for a very common task (just listing enumeration names without caring about the values).
Cons: involves much magic in the implementation, which makes even the definition of such enums baffling when first seen. Besides, explicit is better than implicit.
A different approach to avoid specifying enum values is to use a special name or form to auto assign them. For example:
More flexibly:
Some variations on this theme:
Pros: no need to manually enter values. Makes it easier to change the enum and extend it, especially for large enumerations.
Cons: actually longer to type in many simple cases. The argument of explicit vs. implicit applies here as well.
The Python standard library has many places where the usage of enums would be beneficial to replace other idioms currently used to represent them. Such usages can be divided to two categories: user-code facing constants, and internal constants.
User-code facing constants like os.SEEK_*, socket module constants, decimal rounding modes and HTML error codes could require backwards compatibility since user code may expect integers. IntEnum as described above provides the required semantics; being a subclass of int, it does not affect user code that expects integers, while on the other hand allowing printable representations for enumeration values:
Internal constants are not seen by user code but are employed internally by stdlib modules. These can be implemented with Enum. Some examples uncovered by a very partial skim through the stdlib: binhex, imaplib, http/client, urllib/robotparser, idlelib, concurrent.futures, turtledemo.
In addition, looking at the code of the Twisted library, there are many use cases for replacing internal state constants with enums. The same can be said about a lot of networking code (especially implementation of protocols) and can be seen in test protocols written with the Tulip library as well.
This PEP was initially proposing including the flufl.enum package [8] by Barry Warsaw into the stdlib, and is inspired in large parts by it. Ben Finney is the author of the earlier enumeration PEP 354.
This document has been placed in the public domain.
Source: https://github.com/python/peps/blob/main/peps/pep-0435.rst
Last modified: 2025-02-01 08:59:27 UTC