blob: a9584b9c91083c4549a0f89b9c86760341a6d2a8 [file] [log] [blame]
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001:mod:`enum` --- Support for enumerations
2========================================
3
4.. module:: enum
Brett Cannon15e489f2013-06-14 21:59:16 -04005 :synopsis: Implementation of an enumeration class.
6
Andrés Delfino2d748382018-07-07 16:01:25 -03007.. moduleauthor:: Ethan Furman <ethan@stoneleaf.us>
8.. sectionauthor:: Barry Warsaw <barry@python.org>
9.. sectionauthor:: Eli Bendersky <eliben@gmail.com>
10.. sectionauthor:: Ethan Furman <ethan@stoneleaf.us>
Ethan Furman6b3d64a2013-06-14 16:55:46 -070011
R David Murrayfd1ff1c2013-12-20 14:20:49 -050012.. versionadded:: 3.4
13
Ethan Furman6b3d64a2013-06-14 16:55:46 -070014**Source code:** :source:`Lib/enum.py`
15
16----------------
17
Ethan Furmanc72e6382014-02-06 08:13:14 -080018An enumeration is a set of symbolic names (members) bound to unique,
19constant values. Within an enumeration, the members can be compared
20by identity, and the enumeration itself can be iterated over.
21
Ethan Furman542e1df2020-09-14 13:32:44 -070022.. note:: Case of Enum Members
23
24 Because Enums are used to represent constants we recommend using
25 UPPER_CASE names for enum members, and will be using that style
26 in our examples.
27
Ethan Furmanc72e6382014-02-06 08:13:14 -080028
29Module Contents
30---------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -070031
Ethan Furman65a5a472016-09-01 23:55:19 -070032This module defines four enumeration classes that can be used to define unique
Kartik Anand62658422017-03-01 01:37:19 +053033sets of names and values: :class:`Enum`, :class:`IntEnum`, :class:`Flag`, and
34:class:`IntFlag`. It also defines one decorator, :func:`unique`, and one
Ethan Furmanc16595e2016-09-10 23:36:59 -070035helper, :class:`auto`.
Ethan Furmanc72e6382014-02-06 08:13:14 -080036
37.. class:: Enum
38
39 Base class for creating enumerated constants. See section
Larry Hastingsad88d7a2014-02-10 04:26:10 -080040 `Functional API`_ for an alternate construction syntax.
Ethan Furmanc72e6382014-02-06 08:13:14 -080041
42.. class:: IntEnum
43
44 Base class for creating enumerated constants that are also
45 subclasses of :class:`int`.
46
Ethan Furman0063ff42020-09-21 17:23:13 -070047.. class:: StrEnum
48
49 Base class for creating enumerated constants that are also
50 subclasses of :class:`str`.
51
Ethan Furman65a5a472016-09-01 23:55:19 -070052.. class:: IntFlag
53
54 Base class for creating enumerated constants that can be combined using
55 the bitwise operators without losing their :class:`IntFlag` membership.
56 :class:`IntFlag` members are also subclasses of :class:`int`.
57
58.. class:: Flag
59
60 Base class for creating enumerated constants that can be combined using
61 the bitwise operations without losing their :class:`Flag` membership.
62
Ethan Furmanc72e6382014-02-06 08:13:14 -080063.. function:: unique
Victor Stinnerd3ded082020-08-13 21:41:54 +020064 :noindex:
Ethan Furmanc72e6382014-02-06 08:13:14 -080065
66 Enum class decorator that ensures only one name is bound to any one value.
Ethan Furmanf24bb352013-07-18 17:05:39 -070067
Ethan Furmanc16595e2016-09-10 23:36:59 -070068.. class:: auto
69
YoSTEALTH24bcefc2020-01-06 16:04:43 -060070 Instances are replaced with an appropriate value for Enum members. By default, the initial value starts at 1.
Ethan Furmanc16595e2016-09-10 23:36:59 -070071
72.. versionadded:: 3.6 ``Flag``, ``IntFlag``, ``auto``
Ethan Furman65a5a472016-09-01 23:55:19 -070073
Ethan Furman6b3d64a2013-06-14 16:55:46 -070074
75Creating an Enum
76----------------
77
78Enumerations are created using the :keyword:`class` syntax, which makes them
79easy to read and write. An alternative creation method is described in
Ethan Furman332dbc72016-08-20 00:00:52 -070080`Functional API`_. To define an enumeration, subclass :class:`Enum` as
81follows::
Ethan Furman6b3d64a2013-06-14 16:55:46 -070082
Ethan Furman332dbc72016-08-20 00:00:52 -070083 >>> from enum import Enum
84 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -080085 ... RED = 1
86 ... GREEN = 2
87 ... BLUE = 3
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070088 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -070089
Ethan Furmanc16595e2016-09-10 23:36:59 -070090.. note:: Enum member values
91
92 Member values can be anything: :class:`int`, :class:`str`, etc.. If
93 the exact value is unimportant you may use :class:`auto` instances and an
94 appropriate value will be chosen for you. Care must be taken if you mix
95 :class:`auto` with other values.
96
Ethan Furman455bfde2013-09-08 23:48:34 -070097.. note:: Nomenclature
98
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070099 - The class :class:`Color` is an *enumeration* (or *enum*)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800100 - The attributes :attr:`Color.RED`, :attr:`Color.GREEN`, etc., are
101 *enumeration members* (or *enum members*) and are functionally constants.
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700102 - The enum members have *names* and *values* (the name of
Ethan Furman23bb6f42016-11-21 09:22:05 -0800103 :attr:`Color.RED` is ``RED``, the value of :attr:`Color.BLUE` is
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700104 ``3``, etc.)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700105
Ethan Furman9a1daf52013-09-27 22:58:06 -0700106.. note::
107
108 Even though we use the :keyword:`class` syntax to create Enums, Enums
109 are not normal Python classes. See `How are Enums different?`_ for
110 more details.
111
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700112Enumeration members have human readable string representations::
113
Ethan Furman23bb6f42016-11-21 09:22:05 -0800114 >>> print(Color.RED)
115 Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700116
117...while their ``repr`` has more information::
118
Ethan Furman23bb6f42016-11-21 09:22:05 -0800119 >>> print(repr(Color.RED))
120 <Color.RED: 1>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700121
122The *type* of an enumeration member is the enumeration it belongs to::
123
Ethan Furman23bb6f42016-11-21 09:22:05 -0800124 >>> type(Color.RED)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700125 <enum 'Color'>
Ethan Furman23bb6f42016-11-21 09:22:05 -0800126 >>> isinstance(Color.GREEN, Color)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700127 True
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700128
129Enum members also have a property that contains just their item name::
130
Ethan Furman23bb6f42016-11-21 09:22:05 -0800131 >>> print(Color.RED.name)
132 RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700133
134Enumerations support iteration, in definition order::
135
136 >>> class Shake(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800137 ... VANILLA = 7
138 ... CHOCOLATE = 4
139 ... COOKIES = 9
140 ... MINT = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700141 ...
142 >>> for shake in Shake:
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700143 ... print(shake)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700144 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800145 Shake.VANILLA
146 Shake.CHOCOLATE
147 Shake.COOKIES
148 Shake.MINT
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700149
150Enumeration members are hashable, so they can be used in dictionaries and sets::
151
152 >>> apples = {}
Ethan Furman23bb6f42016-11-21 09:22:05 -0800153 >>> apples[Color.RED] = 'red delicious'
154 >>> apples[Color.GREEN] = 'granny smith'
155 >>> apples == {Color.RED: 'red delicious', Color.GREEN: 'granny smith'}
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700156 True
157
158
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700159Programmatic access to enumeration members and their attributes
160---------------------------------------------------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700161
162Sometimes it's useful to access members in enumerations programmatically (i.e.
Ethan Furman23bb6f42016-11-21 09:22:05 -0800163situations where ``Color.RED`` won't do because the exact color is not known
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700164at program-writing time). ``Enum`` allows such access::
165
166 >>> Color(1)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800167 <Color.RED: 1>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700168 >>> Color(3)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800169 <Color.BLUE: 3>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700170
171If you want to access enum members by *name*, use item access::
172
Ethan Furman23bb6f42016-11-21 09:22:05 -0800173 >>> Color['RED']
174 <Color.RED: 1>
175 >>> Color['GREEN']
176 <Color.GREEN: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700177
Larry Hastings3732ed22014-03-15 21:13:56 -0700178If you have an enum member and need its :attr:`name` or :attr:`value`::
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700179
Ethan Furman23bb6f42016-11-21 09:22:05 -0800180 >>> member = Color.RED
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700181 >>> member.name
Ethan Furman23bb6f42016-11-21 09:22:05 -0800182 'RED'
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700183 >>> member.value
184 1
185
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700186
187Duplicating enum members and values
188-----------------------------------
189
190Having two enum members with the same name is invalid::
191
192 >>> class Shape(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800193 ... SQUARE = 2
194 ... SQUARE = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700195 ...
196 Traceback (most recent call last):
197 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800198 TypeError: Attempted to reuse key: 'SQUARE'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700199
200However, two enum members are allowed to have the same value. Given two members
201A and B with the same value (and A defined first), B is an alias to A. By-value
202lookup of the value of A and B will return A. By-name lookup of B will also
203return A::
204
205 >>> class Shape(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800206 ... SQUARE = 2
207 ... DIAMOND = 1
208 ... CIRCLE = 3
209 ... ALIAS_FOR_SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700210 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800211 >>> Shape.SQUARE
212 <Shape.SQUARE: 2>
213 >>> Shape.ALIAS_FOR_SQUARE
214 <Shape.SQUARE: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700215 >>> Shape(2)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800216 <Shape.SQUARE: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700217
Ethan Furman101e0742013-09-15 12:34:36 -0700218.. note::
219
220 Attempting to create a member with the same name as an already
221 defined attribute (another member, a method, etc.) or attempting to create
222 an attribute with the same name as a member is not allowed.
223
Ethan Furmanf24bb352013-07-18 17:05:39 -0700224
225Ensuring unique enumeration values
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700226----------------------------------
Ethan Furmanf24bb352013-07-18 17:05:39 -0700227
228By default, enumerations allow multiple names as aliases for the same value.
229When this behavior isn't desired, the following decorator can be used to
230ensure each value is used only once in the enumeration:
231
232.. decorator:: unique
233
234A :keyword:`class` decorator specifically for enumerations. It searches an
235enumeration's :attr:`__members__` gathering any aliases it finds; if any are
236found :exc:`ValueError` is raised with the details::
237
238 >>> from enum import Enum, unique
239 >>> @unique
240 ... class Mistake(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800241 ... ONE = 1
242 ... TWO = 2
243 ... THREE = 3
244 ... FOUR = 3
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700245 ...
Ethan Furmanf24bb352013-07-18 17:05:39 -0700246 Traceback (most recent call last):
247 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800248 ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
Ethan Furmanf24bb352013-07-18 17:05:39 -0700249
250
Ethan Furmanc16595e2016-09-10 23:36:59 -0700251Using automatic values
252----------------------
253
254If the exact value is unimportant you can use :class:`auto`::
255
256 >>> from enum import Enum, auto
257 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800258 ... RED = auto()
259 ... BLUE = auto()
260 ... GREEN = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700261 ...
262 >>> list(Color)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800263 [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
Ethan Furmanc16595e2016-09-10 23:36:59 -0700264
265The values are chosen by :func:`_generate_next_value_`, which can be
266overridden::
267
268 >>> class AutoName(Enum):
269 ... def _generate_next_value_(name, start, count, last_values):
270 ... return name
271 ...
272 >>> class Ordinal(AutoName):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800273 ... NORTH = auto()
274 ... SOUTH = auto()
275 ... EAST = auto()
276 ... WEST = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700277 ...
278 >>> list(Ordinal)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800279 [<Ordinal.NORTH: 'NORTH'>, <Ordinal.SOUTH: 'SOUTH'>, <Ordinal.EAST: 'EAST'>, <Ordinal.WEST: 'WEST'>]
Ethan Furmanc16595e2016-09-10 23:36:59 -0700280
281.. note::
282
283 The goal of the default :meth:`_generate_next_value_` methods is to provide
284 the next :class:`int` in sequence with the last :class:`int` provided, but
285 the way it does this is an implementation detail and may change.
286
Ethan Onstottd9a43e22020-04-28 13:20:55 -0400287.. note::
288
289 The :meth:`_generate_next_value_` method must be defined before any members.
290
Ethan Furmanf24bb352013-07-18 17:05:39 -0700291Iteration
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700292---------
Ethan Furmanf24bb352013-07-18 17:05:39 -0700293
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700294Iterating over the members of an enum does not provide the aliases::
295
296 >>> list(Shape)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800297 [<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700298
INADA Naokie57f91a2018-06-19 01:14:26 +0900299The special attribute ``__members__`` is a read-only ordered mapping of names
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700300to members. It includes all names defined in the enumeration, including the
301aliases::
302
303 >>> for name, member in Shape.__members__.items():
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700304 ... name, member
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700305 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800306 ('SQUARE', <Shape.SQUARE: 2>)
307 ('DIAMOND', <Shape.DIAMOND: 1>)
308 ('CIRCLE', <Shape.CIRCLE: 3>)
309 ('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700310
311The ``__members__`` attribute can be used for detailed programmatic access to
312the enumeration members. For example, finding all the aliases::
313
Ethan Furman332dbc72016-08-20 00:00:52 -0700314 >>> [name for name, member in Shape.__members__.items() if member.name != name]
Ethan Furman23bb6f42016-11-21 09:22:05 -0800315 ['ALIAS_FOR_SQUARE']
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700316
Ethan Furmanf24bb352013-07-18 17:05:39 -0700317
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700318Comparisons
319-----------
320
321Enumeration members are compared by identity::
322
Ethan Furman23bb6f42016-11-21 09:22:05 -0800323 >>> Color.RED is Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700324 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800325 >>> Color.RED is Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700326 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800327 >>> Color.RED is not Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700328 True
329
330Ordered comparisons between enumeration values are *not* supported. Enum
331members are not integers (but see `IntEnum`_ below)::
332
Ethan Furman23bb6f42016-11-21 09:22:05 -0800333 >>> Color.RED < Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700334 Traceback (most recent call last):
335 File "<stdin>", line 1, in <module>
Ethan Furmane8e61272016-08-20 07:19:31 -0700336 TypeError: '<' not supported between instances of 'Color' and 'Color'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700337
338Equality comparisons are defined though::
339
Ethan Furman23bb6f42016-11-21 09:22:05 -0800340 >>> Color.BLUE == Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700341 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800342 >>> Color.BLUE != Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700343 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800344 >>> Color.BLUE == Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700345 True
346
347Comparisons against non-enumeration values will always compare not equal
Ezio Melotti93d7dda2013-10-05 04:13:18 +0300348(again, :class:`IntEnum` was explicitly designed to behave differently, see
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700349below)::
350
Ethan Furman23bb6f42016-11-21 09:22:05 -0800351 >>> Color.BLUE == 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700352 False
353
354
355Allowed members and attributes of enumerations
356----------------------------------------------
357
358The examples above use integers for enumeration values. Using integers is
Ethan Furman332dbc72016-08-20 00:00:52 -0700359short and handy (and provided by default by the `Functional API`_), but not
360strictly enforced. In the vast majority of use-cases, one doesn't care what
361the actual value of an enumeration is. But if the value *is* important,
362enumerations can have arbitrary values.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700363
364Enumerations are Python classes, and can have methods and special methods as
365usual. If we have this enumeration::
366
367 >>> class Mood(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800368 ... FUNKY = 1
369 ... HAPPY = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700370 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700371 ... def describe(self):
372 ... # self is the member here
373 ... return self.name, self.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700374 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700375 ... def __str__(self):
376 ... return 'my custom str! {0}'.format(self.value)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700377 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700378 ... @classmethod
379 ... def favorite_mood(cls):
380 ... # cls here is the enumeration
Ethan Furman23bb6f42016-11-21 09:22:05 -0800381 ... return cls.HAPPY
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700382 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700383
384Then::
385
386 >>> Mood.favorite_mood()
Ethan Furman23bb6f42016-11-21 09:22:05 -0800387 <Mood.HAPPY: 3>
388 >>> Mood.HAPPY.describe()
389 ('HAPPY', 3)
390 >>> str(Mood.FUNKY)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700391 'my custom str! 1'
392
Martin Pantera90a4a92016-05-30 04:04:50 +0000393The rules for what is allowed are as follows: names that start and end with
394a single underscore are reserved by enum and cannot be used; all other
Ethan Furman8be6fac2014-11-01 07:40:22 -0700395attributes defined within an enumeration will become members of this
396enumeration, with the exception of special methods (:meth:`__str__`,
Ethan Furmana4b1bb42018-01-22 07:56:37 -0800397:meth:`__add__`, etc.), descriptors (methods are also descriptors), and
398variable names listed in :attr:`_ignore_`.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700399
400Note: if your enumeration defines :meth:`__new__` and/or :meth:`__init__` then
Antoined3c8d732019-08-20 03:41:31 +0200401any value(s) given to the enum member will be passed into those methods.
402See `Planet`_ for an example.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700403
404
Ethan Furman5bdab642018-09-21 19:03:09 -0700405Restricted Enum subclassing
406---------------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700407
Ethan Furman5bdab642018-09-21 19:03:09 -0700408A new :class:`Enum` class must have one base Enum class, up to one concrete
409data type, and as many :class:`object`-based mixin classes as needed. The
410order of these base classes is::
411
nu_nodfc8bb92019-01-27 23:07:47 +0100412 class EnumName([mix-in, ...,] [data-type,] base-enum):
Ethan Furman5bdab642018-09-21 19:03:09 -0700413 pass
414
415Also, subclassing an enumeration is allowed only if the enumeration does not define
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700416any members. So this is forbidden::
417
418 >>> class MoreColor(Color):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800419 ... PINK = 17
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700420 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700421 Traceback (most recent call last):
422 ...
423 TypeError: Cannot extend enumerations
424
425But this is allowed::
426
427 >>> class Foo(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700428 ... def some_behavior(self):
429 ... pass
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700430 ...
431 >>> class Bar(Foo):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800432 ... HAPPY = 1
433 ... SAD = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700434 ...
435
436Allowing subclassing of enums that define members would lead to a violation of
437some important invariants of types and instances. On the other hand, it makes
438sense to allow sharing some common behavior between a group of enumerations.
439(See `OrderedEnum`_ for an example.)
440
441
442Pickling
443--------
444
445Enumerations can be pickled and unpickled::
446
447 >>> from test.test_enum import Fruit
448 >>> from pickle import dumps, loads
Ethan Furman23bb6f42016-11-21 09:22:05 -0800449 >>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO))
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700450 True
451
452The usual restrictions for pickling apply: picklable enums must be defined in
453the top level of a module, since unpickling requires them to be importable
454from that module.
455
Ethan Furmanca1b7942014-02-08 11:36:27 -0800456.. note::
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700457
Ethan Furmanca1b7942014-02-08 11:36:27 -0800458 With pickle protocol version 4 it is possible to easily pickle enums
459 nested in other classes.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700460
Ethan Furman2da95042014-03-03 12:42:52 -0800461It is possible to modify how Enum members are pickled/unpickled by defining
462:meth:`__reduce_ex__` in the enumeration class.
463
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700464
465Functional API
466--------------
467
468The :class:`Enum` class is callable, providing the following functional API::
469
Ethan Furman23bb6f42016-11-21 09:22:05 -0800470 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG')
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700471 >>> Animal
472 <enum 'Animal'>
Ethan Furman23bb6f42016-11-21 09:22:05 -0800473 >>> Animal.ANT
474 <Animal.ANT: 1>
475 >>> Animal.ANT.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700476 1
477 >>> list(Animal)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800478 [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700479
Ethan Furman332dbc72016-08-20 00:00:52 -0700480The semantics of this API resemble :class:`~collections.namedtuple`. The first
481argument of the call to :class:`Enum` is the name of the enumeration.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700482
Ethan Furman332dbc72016-08-20 00:00:52 -0700483The second argument is the *source* of enumeration member names. It can be a
484whitespace-separated string of names, a sequence of names, a sequence of
4852-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to
486values. The last two options enable assigning arbitrary values to
487enumerations; the others auto-assign increasing integers starting with 1 (use
488the ``start`` parameter to specify a different starting value). A
489new class derived from :class:`Enum` is returned. In other words, the above
490assignment to :class:`Animal` is equivalent to::
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700491
Ethan Furman8a123292015-01-14 22:31:50 -0800492 >>> class Animal(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800493 ... ANT = 1
494 ... BEE = 2
495 ... CAT = 3
496 ... DOG = 4
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700497 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700498
Ethan Furmane2563462013-06-28 19:37:17 -0700499The reason for defaulting to ``1`` as the starting number and not ``0`` is
500that ``0`` is ``False`` in a boolean sense, but enum members all evaluate
501to ``True``.
502
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700503Pickling enums created with the functional API can be tricky as frame stack
504implementation details are used to try and figure out which module the
505enumeration is being created in (e.g. it will fail if you use a utility
Ethan Furman332dbc72016-08-20 00:00:52 -0700506function in separate module, and also may not work on IronPython or Jython).
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700507The solution is to specify the module name explicitly as follows::
508
Ethan Furman23bb6f42016-11-21 09:22:05 -0800509 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700510
Ethan Furman2da95042014-03-03 12:42:52 -0800511.. warning::
512
Ethan Furman01cc2d52014-03-03 15:02:04 -0800513 If ``module`` is not supplied, and Enum cannot determine what it is,
Ethan Furman2da95042014-03-03 12:42:52 -0800514 the new Enum members will not be unpicklable; to keep errors closer to
515 the source, pickling will be disabled.
516
Ethan Furmanca1b7942014-02-08 11:36:27 -0800517The new pickle protocol 4 also, in some circumstances, relies on
Martin Panterbae5d812016-06-18 03:57:31 +0000518:attr:`~definition.__qualname__` being set to the location where pickle will be able
Ethan Furmanca1b7942014-02-08 11:36:27 -0800519to find the class. For example, if the class was made available in class
520SomeData in the global scope::
521
Ethan Furman23bb6f42016-11-21 09:22:05 -0800522 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal')
Ethan Furmanca1b7942014-02-08 11:36:27 -0800523
Ethan Furman2da95042014-03-03 12:42:52 -0800524The complete signature is::
525
Ethan Furman332dbc72016-08-20 00:00:52 -0700526 Enum(value='NewEnumName', names=<...>, *, module='...', qualname='...', type=<mixed-in class>, start=1)
Ethan Furman2da95042014-03-03 12:42:52 -0800527
Ethan Furman01cc2d52014-03-03 15:02:04 -0800528:value: What the new Enum class will record as its name.
Ethan Furman2da95042014-03-03 12:42:52 -0800529
Zachary Waredbd1c432014-03-20 10:01:48 -0500530:names: The Enum members. This can be a whitespace or comma separated string
Ethan Furmand9925a12014-09-16 20:35:55 -0700531 (values will start at 1 unless otherwise specified)::
Ethan Furman2da95042014-03-03 12:42:52 -0800532
Ethan Furman23bb6f42016-11-21 09:22:05 -0800533 'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE'
Ethan Furman2da95042014-03-03 12:42:52 -0800534
Ethan Furman8a123292015-01-14 22:31:50 -0800535 or an iterator of names::
536
Ethan Furman23bb6f42016-11-21 09:22:05 -0800537 ['RED', 'GREEN', 'BLUE']
Ethan Furman8a123292015-01-14 22:31:50 -0800538
Ethan Furman01cc2d52014-03-03 15:02:04 -0800539 or an iterator of (name, value) pairs::
Ethan Furman2da95042014-03-03 12:42:52 -0800540
Ethan Furman23bb6f42016-11-21 09:22:05 -0800541 [('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)]
Ethan Furman2da95042014-03-03 12:42:52 -0800542
Ethan Furman01cc2d52014-03-03 15:02:04 -0800543 or a mapping::
Ethan Furman2da95042014-03-03 12:42:52 -0800544
Ethan Furman23bb6f42016-11-21 09:22:05 -0800545 {'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42}
Ethan Furman2da95042014-03-03 12:42:52 -0800546
Ethan Furman01cc2d52014-03-03 15:02:04 -0800547:module: name of module where new Enum class can be found.
Ethan Furman2da95042014-03-03 12:42:52 -0800548
Ethan Furman01cc2d52014-03-03 15:02:04 -0800549:qualname: where in module new Enum class can be found.
Ethan Furman2da95042014-03-03 12:42:52 -0800550
Ethan Furman01cc2d52014-03-03 15:02:04 -0800551:type: type to mix in to new Enum class.
Ethan Furman2da95042014-03-03 12:42:52 -0800552
Yury Selivanov4dde5872015-09-11 00:48:21 -0400553:start: number to start counting at if only names are passed in.
Ethan Furmand9925a12014-09-16 20:35:55 -0700554
Berker Peksag60efd792014-09-18 05:23:14 +0300555.. versionchanged:: 3.5
556 The *start* parameter was added.
557
Ethan Furmanca1b7942014-02-08 11:36:27 -0800558
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700559Derived Enumerations
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700560--------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700561
562IntEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700563^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700564
Ethan Furman65a5a472016-09-01 23:55:19 -0700565The first variation of :class:`Enum` that is provided is also a subclass of
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700566:class:`int`. Members of an :class:`IntEnum` can be compared to integers;
567by extension, integer enumerations of different types can also be compared
568to each other::
569
570 >>> from enum import IntEnum
571 >>> class Shape(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800572 ... CIRCLE = 1
573 ... SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700574 ...
575 >>> class Request(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800576 ... POST = 1
577 ... GET = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700578 ...
579 >>> Shape == 1
580 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800581 >>> Shape.CIRCLE == 1
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700582 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800583 >>> Shape.CIRCLE == Request.POST
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700584 True
585
586However, they still can't be compared to standard :class:`Enum` enumerations::
587
588 >>> class Shape(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800589 ... CIRCLE = 1
590 ... SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700591 ...
592 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800593 ... RED = 1
594 ... GREEN = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700595 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800596 >>> Shape.CIRCLE == Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700597 False
598
599:class:`IntEnum` values behave like integers in other ways you'd expect::
600
Ethan Furman23bb6f42016-11-21 09:22:05 -0800601 >>> int(Shape.CIRCLE)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700602 1
Ethan Furman23bb6f42016-11-21 09:22:05 -0800603 >>> ['a', 'b', 'c'][Shape.CIRCLE]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700604 'b'
Ethan Furman23bb6f42016-11-21 09:22:05 -0800605 >>> [i for i in range(Shape.SQUARE)]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700606 [0, 1]
607
Ethan Furman65a5a472016-09-01 23:55:19 -0700608
Ethan Furman0063ff42020-09-21 17:23:13 -0700609StrEnum
610^^^^^^^
611
612The second variation of :class:`Enum` that is provided is also a subclass of
613:class:`str`. Members of a :class:`StrEnum` can be compared to strings;
614by extension, string enumerations of different types can also be compared
615to each other. :class:`StrEnum` exists to help avoid the problem of getting
616an incorrect member::
617
618 >>> class Directions(StrEnum):
619 ... NORTH = 'north', # notice the trailing comma
620 ... SOUTH = 'south'
621
622Before :class:`StrEnum`, ``Directions.NORTH`` would have been the :class:`tuple`
623``('north',)``.
624
Ethan Furmand986d162020-09-22 13:00:07 -0700625.. note::
626
627 Unlike other Enum's, ``str(StrEnum.member)`` will return the value of the
628 member instead of the usual ``"EnumClass.member"``.
629
Ethan Furman0063ff42020-09-21 17:23:13 -0700630.. versionadded:: 3.10
631
632
Ethan Furman65a5a472016-09-01 23:55:19 -0700633IntFlag
634^^^^^^^
635
636The next variation of :class:`Enum` provided, :class:`IntFlag`, is also based
637on :class:`int`. The difference being :class:`IntFlag` members can be combined
638using the bitwise operators (&, \|, ^, ~) and the result is still an
639:class:`IntFlag` member. However, as the name implies, :class:`IntFlag`
Ethan Furman54924df2016-09-07 23:40:31 -0700640members also subclass :class:`int` and can be used wherever an :class:`int` is
641used. Any operation on an :class:`IntFlag` member besides the bit-wise
642operations will lose the :class:`IntFlag` membership.
Ethan Furman65a5a472016-09-01 23:55:19 -0700643
Ethan Furman25d94bb2016-09-02 16:32:32 -0700644.. versionadded:: 3.6
645
646Sample :class:`IntFlag` class::
647
Ethan Furman65a5a472016-09-01 23:55:19 -0700648 >>> from enum import IntFlag
649 >>> class Perm(IntFlag):
650 ... R = 4
651 ... W = 2
652 ... X = 1
653 ...
654 >>> Perm.R | Perm.W
655 <Perm.R|W: 6>
656 >>> Perm.R + Perm.W
657 6
658 >>> RW = Perm.R | Perm.W
659 >>> Perm.R in RW
660 True
661
Ethan Furman25d94bb2016-09-02 16:32:32 -0700662It is also possible to name the combinations::
663
664 >>> class Perm(IntFlag):
665 ... R = 4
666 ... W = 2
667 ... X = 1
668 ... RWX = 7
669 >>> Perm.RWX
670 <Perm.RWX: 7>
671 >>> ~Perm.RWX
Ethan Furman27682d22016-09-04 11:39:01 -0700672 <Perm.-8: -8>
Ethan Furman25d94bb2016-09-02 16:32:32 -0700673
674Another important difference between :class:`IntFlag` and :class:`Enum` is that
675if no flags are set (the value is 0), its boolean evaluation is :data:`False`::
676
677 >>> Perm.R & Perm.X
678 <Perm.0: 0>
679 >>> bool(Perm.R & Perm.X)
680 False
681
682Because :class:`IntFlag` members are also subclasses of :class:`int` they can
683be combined with them::
684
685 >>> Perm.X | 8
686 <Perm.8|X: 9>
Ethan Furman65a5a472016-09-01 23:55:19 -0700687
Ethan Furman7219e272020-09-16 13:01:00 -0700688:class:`IntFlag` members can also be iterated over::
689
690 >>> list(RW)
691 [<Perm.R: 4>, <Perm.W: 2>]
692
693.. versionadded:: 3.10
694
Ethan Furman65a5a472016-09-01 23:55:19 -0700695
696Flag
697^^^^
698
699The last variation is :class:`Flag`. Like :class:`IntFlag`, :class:`Flag`
Ethan Furman25d94bb2016-09-02 16:32:32 -0700700members can be combined using the bitwise operators (&, \|, ^, ~). Unlike
Ethan Furman65a5a472016-09-01 23:55:19 -0700701:class:`IntFlag`, they cannot be combined with, nor compared against, any
Ethan Furmanc16595e2016-09-10 23:36:59 -0700702other :class:`Flag` enumeration, nor :class:`int`. While it is possible to
703specify the values directly it is recommended to use :class:`auto` as the
704value and let :class:`Flag` select an appropriate value.
Ethan Furman65a5a472016-09-01 23:55:19 -0700705
706.. versionadded:: 3.6
707
Ethan Furman25d94bb2016-09-02 16:32:32 -0700708Like :class:`IntFlag`, if a combination of :class:`Flag` members results in no
709flags being set, the boolean evaluation is :data:`False`::
710
Julian Kahnert0f31c742018-01-13 04:35:57 +0100711 >>> from enum import Flag, auto
Ethan Furman25d94bb2016-09-02 16:32:32 -0700712 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800713 ... RED = auto()
714 ... BLUE = auto()
715 ... GREEN = auto()
Ethan Furman25d94bb2016-09-02 16:32:32 -0700716 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800717 >>> Color.RED & Color.GREEN
Ethan Furman25d94bb2016-09-02 16:32:32 -0700718 <Color.0: 0>
Ethan Furman23bb6f42016-11-21 09:22:05 -0800719 >>> bool(Color.RED & Color.GREEN)
Ethan Furman25d94bb2016-09-02 16:32:32 -0700720 False
721
Ethan Furman27682d22016-09-04 11:39:01 -0700722Individual flags should have values that are powers of two (1, 2, 4, 8, ...),
723while combinations of flags won't::
724
725 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800726 ... RED = auto()
727 ... BLUE = auto()
728 ... GREEN = auto()
729 ... WHITE = RED | BLUE | GREEN
Ethan Furmanc16595e2016-09-10 23:36:59 -0700730 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800731 >>> Color.WHITE
732 <Color.WHITE: 7>
Ethan Furman27682d22016-09-04 11:39:01 -0700733
Ethan Furman25d94bb2016-09-02 16:32:32 -0700734Giving a name to the "no flags set" condition does not change its boolean
735value::
736
737 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800738 ... BLACK = 0
739 ... RED = auto()
740 ... BLUE = auto()
741 ... GREEN = auto()
Ethan Furman25d94bb2016-09-02 16:32:32 -0700742 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800743 >>> Color.BLACK
744 <Color.BLACK: 0>
745 >>> bool(Color.BLACK)
Ethan Furman25d94bb2016-09-02 16:32:32 -0700746 False
747
Ethan Furman7219e272020-09-16 13:01:00 -0700748:class:`Flag` members can also be iterated over::
749
750 >>> purple = Color.RED | Color.BLUE
751 >>> list(purple)
752 [<Color.BLUE: 2>, <Color.RED: 1>]
753
754.. versionadded:: 3.10
755
Ethan Furman65a5a472016-09-01 23:55:19 -0700756.. note::
757
758 For the majority of new code, :class:`Enum` and :class:`Flag` are strongly
759 recommended, since :class:`IntEnum` and :class:`IntFlag` break some
760 semantic promises of an enumeration (by being comparable to integers, and
761 thus by transitivity to other unrelated enumerations). :class:`IntEnum`
762 and :class:`IntFlag` should be used only in cases where :class:`Enum` and
763 :class:`Flag` will not do; for example, when integer constants are replaced
764 with enumerations, or for interoperability with other systems.
Ethan Furman332dbc72016-08-20 00:00:52 -0700765
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700766
767Others
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700768^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700769
770While :class:`IntEnum` is part of the :mod:`enum` module, it would be very
771simple to implement independently::
772
773 class IntEnum(int, Enum):
774 pass
775
776This demonstrates how similar derived enumerations can be defined; for example
Ethan Furman332dbc72016-08-20 00:00:52 -0700777a :class:`StrEnum` that mixes in :class:`str` instead of :class:`int`.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700778
779Some rules:
780
7811. When subclassing :class:`Enum`, mix-in types must appear before
782 :class:`Enum` itself in the sequence of bases, as in the :class:`IntEnum`
783 example above.
7842. While :class:`Enum` can have members of any type, once you mix in an
785 additional type, all the members must have values of that type, e.g.
786 :class:`int` above. This restriction does not apply to mix-ins which only
Antoined3c8d732019-08-20 03:41:31 +0200787 add methods and don't specify another type.
Ethan Furman6b3d64a2013-06-14 16:55:46 -07007883. When another data type is mixed in, the :attr:`value` attribute is *not the
Zachary Waredbd1c432014-03-20 10:01:48 -0500789 same* as the enum member itself, although it is equivalent and will compare
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700790 equal.
Martin Panterd5db1472016-02-08 01:34:09 +00007914. %-style formatting: `%s` and `%r` call the :class:`Enum` class's
792 :meth:`__str__` and :meth:`__repr__` respectively; other codes (such as
793 `%i` or `%h` for IntEnum) treat the enum member as its mixed-in type.
Martin Panterbc1ee462016-02-13 00:41:37 +00007945. :ref:`Formatted string literals <f-strings>`, :meth:`str.format`,
thatneat2f19e822019-07-04 11:28:37 -0700795 and :func:`format` will use the mixed-in type's :meth:`__format__`
796 unless :meth:`__str__` or :meth:`__format__` is overridden in the subclass,
797 in which case the overridden methods or :class:`Enum` methods will be used.
798 Use the !s and !r format codes to force usage of the :class:`Enum` class's
799 :meth:`__str__` and :meth:`__repr__` methods.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700800
Ethan Furmanf5223742018-09-12 10:00:30 -0700801When to use :meth:`__new__` vs. :meth:`__init__`
802------------------------------------------------
803
804:meth:`__new__` must be used whenever you want to customize the actual value of
805the :class:`Enum` member. Any other modifications may go in either
806:meth:`__new__` or :meth:`__init__`, with :meth:`__init__` being preferred.
807
808For example, if you want to pass several items to the constructor, but only
809want one of them to be the value::
810
811 >>> class Coordinate(bytes, Enum):
812 ... """
813 ... Coordinate with binary codes that can be indexed by the int code.
814 ... """
815 ... def __new__(cls, value, label, unit):
816 ... obj = bytes.__new__(cls, [value])
817 ... obj._value_ = value
818 ... obj.label = label
819 ... obj.unit = unit
820 ... return obj
821 ... PX = (0, 'P.X', 'km')
822 ... PY = (1, 'P.Y', 'km')
823 ... VX = (2, 'V.X', 'km/s')
824 ... VY = (3, 'V.Y', 'km/s')
825 ...
826
827 >>> print(Coordinate['PY'])
828 Coordinate.PY
829
830 >>> print(Coordinate(3))
831 Coordinate.VY
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700832
833Interesting examples
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700834--------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700835
Ethan Furman65a5a472016-09-01 23:55:19 -0700836While :class:`Enum`, :class:`IntEnum`, :class:`IntFlag`, and :class:`Flag` are
837expected to cover the majority of use-cases, they cannot cover them all. Here
838are recipes for some different types of enumerations that can be used directly,
839or as examples for creating one's own.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700840
841
Ethan Furman6a137e82016-09-07 08:17:15 -0700842Omitting values
843^^^^^^^^^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700844
Ethan Furman6a137e82016-09-07 08:17:15 -0700845In many use-cases one doesn't care what the actual value of an enumeration
846is. There are several ways to define this type of simple enumeration:
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700847
Ethan Furmanc16595e2016-09-10 23:36:59 -0700848- use instances of :class:`auto` for the value
Ethan Furman6a137e82016-09-07 08:17:15 -0700849- use instances of :class:`object` as the value
850- use a descriptive string as the value
851- use a tuple as the value and a custom :meth:`__new__` to replace the
852 tuple with an :class:`int` value
853
854Using any of these methods signifies to the user that these values are not
855important, and also enables one to add, remove, or reorder members without
856having to renumber the remaining members.
857
858Whichever method you choose, you should provide a :meth:`repr` that also hides
859the (unimportant) value::
860
861 >>> class NoValue(Enum):
862 ... def __repr__(self):
863 ... return '<%s.%s>' % (self.__class__.__name__, self.name)
864 ...
865
866
Ethan Furmanc16595e2016-09-10 23:36:59 -0700867Using :class:`auto`
868"""""""""""""""""""
869
Berker Peksag2a267a12017-01-02 05:51:04 +0300870Using :class:`auto` would look like::
Ethan Furmanc16595e2016-09-10 23:36:59 -0700871
872 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800873 ... RED = auto()
874 ... BLUE = auto()
875 ... GREEN = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700876 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800877 >>> Color.GREEN
878 <Color.GREEN>
Ethan Furmanc16595e2016-09-10 23:36:59 -0700879
880
Ethan Furman6a137e82016-09-07 08:17:15 -0700881Using :class:`object`
882"""""""""""""""""""""
883
884Using :class:`object` would look like::
885
886 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800887 ... RED = object()
888 ... GREEN = object()
889 ... BLUE = object()
Ethan Furman6a137e82016-09-07 08:17:15 -0700890 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800891 >>> Color.GREEN
892 <Color.GREEN>
Ethan Furman6a137e82016-09-07 08:17:15 -0700893
894
895Using a descriptive string
896""""""""""""""""""""""""""
897
898Using a string as the value would look like::
899
900 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800901 ... RED = 'stop'
902 ... GREEN = 'go'
903 ... BLUE = 'too fast!'
Ethan Furman6a137e82016-09-07 08:17:15 -0700904 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800905 >>> Color.GREEN
906 <Color.GREEN>
907 >>> Color.GREEN.value
Ethan Furman6a137e82016-09-07 08:17:15 -0700908 'go'
909
910
911Using a custom :meth:`__new__`
912""""""""""""""""""""""""""""""
913
914Using an auto-numbering :meth:`__new__` would look like::
915
916 >>> class AutoNumber(NoValue):
Ethan Furman332dbc72016-08-20 00:00:52 -0700917 ... def __new__(cls):
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700918 ... value = len(cls.__members__) + 1
919 ... obj = object.__new__(cls)
Ethan Furman90262622013-07-30 12:24:25 -0700920 ... obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700921 ... return obj
922 ...
Ethan Furman332dbc72016-08-20 00:00:52 -0700923 >>> class Color(AutoNumber):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800924 ... RED = ()
925 ... GREEN = ()
926 ... BLUE = ()
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700927 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800928 >>> Color.GREEN
929 <Color.GREEN>
930 >>> Color.GREEN.value
Ethan Furman6a137e82016-09-07 08:17:15 -0700931 2
932
Ethan Furman62e40d82020-09-22 00:05:27 -0700933To make a more general purpose ``AutoNumber``, add ``*args`` to the signature::
934
935 >>> class AutoNumber(NoValue):
936 ... def __new__(cls, *args): # this is the only change from above
937 ... value = len(cls.__members__) + 1
938 ... obj = object.__new__(cls)
939 ... obj._value_ = value
940 ... return obj
941 ...
942
943Then when you inherit from ``AutoNumber`` you can write your own ``__init__``
944to handle any extra arguments::
945
946 >>> class Swatch(AutoNumber):
947 ... def __init__(self, pantone='unknown'):
948 ... self.pantone = pantone
949 ... AUBURN = '3497'
950 ... SEA_GREEN = '1246'
951 ... BLEACHED_CORAL = () # New color, no Pantone code yet!
952 ...
953 >>> Swatch.SEA_GREEN
954 <Swatch.SEA_GREEN: 2>
955 >>> Swatch.SEA_GREEN.pantone
956 '1246'
957 >>> Swatch.BLEACHED_CORAL.pantone
958 'unknown'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700959
Ethan Furman9a1daf52013-09-27 22:58:06 -0700960.. note::
961
962 The :meth:`__new__` method, if defined, is used during creation of the Enum
963 members; it is then replaced by Enum's :meth:`__new__` which is used after
Ethan Furmanf75805e2014-09-16 19:13:31 -0700964 class creation for lookup of existing members.
Ethan Furman9a1daf52013-09-27 22:58:06 -0700965
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700966
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700967OrderedEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700968^^^^^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700969
970An ordered enumeration that is not based on :class:`IntEnum` and so maintains
971the normal :class:`Enum` invariants (such as not being comparable to other
972enumerations)::
973
974 >>> class OrderedEnum(Enum):
975 ... def __ge__(self, other):
976 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700977 ... return self.value >= other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700978 ... return NotImplemented
979 ... def __gt__(self, other):
980 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700981 ... return self.value > other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700982 ... return NotImplemented
983 ... def __le__(self, other):
984 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700985 ... return self.value <= other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700986 ... return NotImplemented
987 ... def __lt__(self, other):
988 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700989 ... return self.value < other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700990 ... return NotImplemented
991 ...
992 >>> class Grade(OrderedEnum):
993 ... A = 5
994 ... B = 4
995 ... C = 3
996 ... D = 2
997 ... F = 1
998 ...
999 >>> Grade.C < Grade.A
1000 True
1001
1002
Ethan Furmanf24bb352013-07-18 17:05:39 -07001003DuplicateFreeEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -07001004^^^^^^^^^^^^^^^^^
Ethan Furmanf24bb352013-07-18 17:05:39 -07001005
1006Raises an error if a duplicate member name is found instead of creating an
1007alias::
1008
1009 >>> class DuplicateFreeEnum(Enum):
1010 ... def __init__(self, *args):
1011 ... cls = self.__class__
1012 ... if any(self.value == e.value for e in cls):
1013 ... a = self.name
1014 ... e = cls(self.value).name
1015 ... raise ValueError(
1016 ... "aliases not allowed in DuplicateFreeEnum: %r --> %r"
1017 ... % (a, e))
1018 ...
1019 >>> class Color(DuplicateFreeEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -08001020 ... RED = 1
1021 ... GREEN = 2
1022 ... BLUE = 3
1023 ... GRENE = 2
Ethan Furmaned0bf8a2013-09-06 19:53:30 -07001024 ...
Ethan Furmanf24bb352013-07-18 17:05:39 -07001025 Traceback (most recent call last):
1026 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -08001027 ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN'
Ethan Furmanf24bb352013-07-18 17:05:39 -07001028
1029.. note::
1030
1031 This is a useful example for subclassing Enum to add or change other
Ezio Melotti93d7dda2013-10-05 04:13:18 +03001032 behaviors as well as disallowing aliases. If the only desired change is
Ezio Melotti17f1edd2013-10-05 04:26:06 +03001033 disallowing aliases, the :func:`unique` decorator can be used instead.
Ethan Furmanf24bb352013-07-18 17:05:39 -07001034
1035
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001036Planet
Ethan Furmaned0bf8a2013-09-06 19:53:30 -07001037^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001038
1039If :meth:`__new__` or :meth:`__init__` is defined the value of the enum member
1040will be passed to those methods::
1041
1042 >>> class Planet(Enum):
1043 ... MERCURY = (3.303e+23, 2.4397e6)
1044 ... VENUS = (4.869e+24, 6.0518e6)
1045 ... EARTH = (5.976e+24, 6.37814e6)
1046 ... MARS = (6.421e+23, 3.3972e6)
1047 ... JUPITER = (1.9e+27, 7.1492e7)
1048 ... SATURN = (5.688e+26, 6.0268e7)
1049 ... URANUS = (8.686e+25, 2.5559e7)
1050 ... NEPTUNE = (1.024e+26, 2.4746e7)
1051 ... def __init__(self, mass, radius):
1052 ... self.mass = mass # in kilograms
1053 ... self.radius = radius # in meters
1054 ... @property
1055 ... def surface_gravity(self):
1056 ... # universal gravitational constant (m3 kg-1 s-2)
1057 ... G = 6.67300E-11
1058 ... return G * self.mass / (self.radius * self.radius)
1059 ...
1060 >>> Planet.EARTH.value
1061 (5.976e+24, 6378140.0)
1062 >>> Planet.EARTH.surface_gravity
1063 9.802652743337129
Ethan Furman9a1daf52013-09-27 22:58:06 -07001064
1065
Ethan Furmana4b1bb42018-01-22 07:56:37 -08001066TimePeriod
1067^^^^^^^^^^
1068
1069An example to show the :attr:`_ignore_` attribute in use::
1070
1071 >>> from datetime import timedelta
1072 >>> class Period(timedelta, Enum):
1073 ... "different lengths of time"
1074 ... _ignore_ = 'Period i'
1075 ... Period = vars()
1076 ... for i in range(367):
1077 ... Period['day_%d' % i] = i
1078 ...
1079 >>> list(Period)[:2]
1080 [<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>]
1081 >>> list(Period)[-2:]
1082 [<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>]
1083
1084
Ethan Furman9a1daf52013-09-27 22:58:06 -07001085How are Enums different?
1086------------------------
1087
1088Enums have a custom metaclass that affects many aspects of both derived Enum
1089classes and their instances (members).
1090
1091
1092Enum Classes
1093^^^^^^^^^^^^
1094
1095The :class:`EnumMeta` metaclass is responsible for providing the
1096:meth:`__contains__`, :meth:`__dir__`, :meth:`__iter__` and other methods that
1097allow one to do things with an :class:`Enum` class that fail on a typical
Rahul Jha94306522018-09-10 23:51:04 +05301098class, such as `list(Color)` or `some_enum_var in Color`. :class:`EnumMeta` is
Ethan Furman9a1daf52013-09-27 22:58:06 -07001099responsible for ensuring that various other methods on the final :class:`Enum`
1100class are correct (such as :meth:`__new__`, :meth:`__getnewargs__`,
Martin Panterd21e0b52015-10-10 10:36:22 +00001101:meth:`__str__` and :meth:`__repr__`).
Ethan Furman9a1daf52013-09-27 22:58:06 -07001102
1103
1104Enum Members (aka instances)
1105^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1106
1107The most interesting thing about Enum members is that they are singletons.
1108:class:`EnumMeta` creates them all while it is creating the :class:`Enum`
1109class itself, and then puts a custom :meth:`__new__` in place to ensure
1110that no new ones are ever instantiated by returning only the existing
1111member instances.
1112
1113
1114Finer Points
1115^^^^^^^^^^^^
1116
Ethan Furman65a5a472016-09-01 23:55:19 -07001117Supported ``__dunder__`` names
Ethan Furman6a137e82016-09-07 08:17:15 -07001118""""""""""""""""""""""""""""""
Ethan Furman9a1daf52013-09-27 22:58:06 -07001119
INADA Naokie57f91a2018-06-19 01:14:26 +09001120:attr:`__members__` is a read-only ordered mapping of ``member_name``:``member``
Ethan Furman65a5a472016-09-01 23:55:19 -07001121items. It is only available on the class.
Ethan Furman9a1daf52013-09-27 22:58:06 -07001122
Ethan Furman65a5a472016-09-01 23:55:19 -07001123:meth:`__new__`, if specified, must create and return the enum members; it is
1124also a very good idea to set the member's :attr:`_value_` appropriately. Once
1125all the members are created it is no longer used.
Ethan Furman748dad52015-11-20 13:12:26 -08001126
Ethan Furman60255b62016-01-15 15:01:33 -08001127
Ethan Furman65a5a472016-09-01 23:55:19 -07001128Supported ``_sunder_`` names
Ethan Furman6a137e82016-09-07 08:17:15 -07001129""""""""""""""""""""""""""""
Ethan Furman60255b62016-01-15 15:01:33 -08001130
Ethan Furman65a5a472016-09-01 23:55:19 -07001131- ``_name_`` -- name of the member
1132- ``_value_`` -- value of the member; can be set / modified in ``__new__``
Ethan Furman9a1daf52013-09-27 22:58:06 -07001133
Ethan Furman65a5a472016-09-01 23:55:19 -07001134- ``_missing_`` -- a lookup function used when a value is not found; may be
1135 overridden
Antoined3c8d732019-08-20 03:41:31 +02001136- ``_ignore_`` -- a list of names, either as a :class:`list` or a :class:`str`,
Ethan Furmana4b1bb42018-01-22 07:56:37 -08001137 that will not be transformed into members, and will be removed from the final
1138 class
Ethan Furman65a5a472016-09-01 23:55:19 -07001139- ``_order_`` -- used in Python 2/3 code to ensure member order is consistent
1140 (class attribute, removed during class creation)
Ethan Furmanc16595e2016-09-10 23:36:59 -07001141- ``_generate_next_value_`` -- used by the `Functional API`_ and by
1142 :class:`auto` to get an appropriate value for an enum member; may be
1143 overridden
Ethan Furman9a1daf52013-09-27 22:58:06 -07001144
Ethan Furmanc16595e2016-09-10 23:36:59 -07001145.. versionadded:: 3.6 ``_missing_``, ``_order_``, ``_generate_next_value_``
Ethan Furmana4b1bb42018-01-22 07:56:37 -08001146.. versionadded:: 3.7 ``_ignore_``
Ethan Furman332dbc72016-08-20 00:00:52 -07001147
Ethan Furman65a5a472016-09-01 23:55:19 -07001148To help keep Python 2 / Python 3 code in sync an :attr:`_order_` attribute can
1149be provided. It will be checked against the actual order of the enumeration
1150and raise an error if the two do not match::
Ethan Furmane8e61272016-08-20 07:19:31 -07001151
1152 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -08001153 ... _order_ = 'RED GREEN BLUE'
1154 ... RED = 1
1155 ... BLUE = 3
1156 ... GREEN = 2
Ethan Furmane8e61272016-08-20 07:19:31 -07001157 ...
1158 Traceback (most recent call last):
1159 ...
1160 TypeError: member order does not match _order_
1161
1162.. note::
1163
1164 In Python 2 code the :attr:`_order_` attribute is necessary as definition
Ethan Furman65a5a472016-09-01 23:55:19 -07001165 order is lost before it can be recorded.
1166
Ethan Furman7cf0aad2020-12-09 17:12:11 -08001167
1168_Private__names
1169"""""""""""""""
1170
1171Private names are not converted to Enum members, but remain normal attributes.
1172
1173.. versionchanged:: 3.10
1174
1175
Ethan Furman65a5a472016-09-01 23:55:19 -07001176``Enum`` member type
Ethan Furman6a137e82016-09-07 08:17:15 -07001177""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001178
Ethan Furman54924df2016-09-07 23:40:31 -07001179:class:`Enum` members are instances of their :class:`Enum` class, and are
1180normally accessed as ``EnumClass.member``. Under certain circumstances they
1181can also be accessed as ``EnumClass.member.member``, but you should never do
1182this as that lookup may fail or, worse, return something besides the
Ethan Furman23bb6f42016-11-21 09:22:05 -08001183:class:`Enum` member you are looking for (this is another good reason to use
1184all-uppercase names for members)::
Ethan Furman65a5a472016-09-01 23:55:19 -07001185
1186 >>> class FieldTypes(Enum):
1187 ... name = 0
1188 ... value = 1
1189 ... size = 2
1190 ...
1191 >>> FieldTypes.value.size
1192 <FieldTypes.size: 2>
1193 >>> FieldTypes.size.value
1194 2
1195
1196.. versionchanged:: 3.5
1197
1198
Ethan Furman0063ff42020-09-21 17:23:13 -07001199Creating members that are mixed with other data types
1200"""""""""""""""""""""""""""""""""""""""""""""""""""""
1201
1202When subclassing other data types, such as :class:`int` or :class:`str`, with
1203an :class:`Enum`, all values after the `=` are passed to that data type's
1204constructor. For example::
1205
1206 >>> class MyEnum(IntEnum):
1207 ... example = '11', 16 # '11' will be interpreted as a hexadecimal
1208 ... # number
1209 >>> MyEnum.example
1210 <MyEnum.example: 17>
1211
1212
Ethan Furman65a5a472016-09-01 23:55:19 -07001213Boolean value of ``Enum`` classes and members
Ethan Furman6a137e82016-09-07 08:17:15 -07001214"""""""""""""""""""""""""""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001215
Ethan Furman54924df2016-09-07 23:40:31 -07001216:class:`Enum` members that are mixed with non-:class:`Enum` types (such as
Ethan Furman65a5a472016-09-01 23:55:19 -07001217:class:`int`, :class:`str`, etc.) are evaluated according to the mixed-in
Ethan Furman54924df2016-09-07 23:40:31 -07001218type's rules; otherwise, all members evaluate as :data:`True`. To make your
1219own Enum's boolean evaluation depend on the member's value add the following to
Ethan Furman65a5a472016-09-01 23:55:19 -07001220your class::
1221
1222 def __bool__(self):
1223 return bool(self.value)
1224
Ethan Furman54924df2016-09-07 23:40:31 -07001225:class:`Enum` classes always evaluate as :data:`True`.
Ethan Furman65a5a472016-09-01 23:55:19 -07001226
1227
1228``Enum`` classes with methods
Ethan Furman6a137e82016-09-07 08:17:15 -07001229"""""""""""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001230
1231If you give your :class:`Enum` subclass extra methods, like the `Planet`_
1232class above, those methods will show up in a :func:`dir` of the member,
1233but not of the class::
1234
1235 >>> dir(Planet)
1236 ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__']
1237 >>> dir(Planet.EARTH)
1238 ['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value']
1239
Ethan Furman3515dcc2016-09-18 13:15:41 -07001240
1241Combining members of ``Flag``
1242"""""""""""""""""""""""""""""
1243
1244If a combination of Flag members is not named, the :func:`repr` will include
1245all named flags and all named combinations of flags that are in the value::
1246
1247 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -08001248 ... RED = auto()
1249 ... GREEN = auto()
1250 ... BLUE = auto()
1251 ... MAGENTA = RED | BLUE
1252 ... YELLOW = RED | GREEN
1253 ... CYAN = GREEN | BLUE
Ethan Furman3515dcc2016-09-18 13:15:41 -07001254 ...
1255 >>> Color(3) # named combination
Ethan Furman23bb6f42016-11-21 09:22:05 -08001256 <Color.YELLOW: 3>
Ethan Furman3515dcc2016-09-18 13:15:41 -07001257 >>> Color(7) # not named combination
Ethan Furman23bb6f42016-11-21 09:22:05 -08001258 <Color.CYAN|MAGENTA|BLUE|YELLOW|GREEN|RED: 7>
Ethan Furman3515dcc2016-09-18 13:15:41 -07001259
Ethan Furmand986d162020-09-22 13:00:07 -07001260``StrEnum`` and :meth:`str.__str__`
1261"""""""""""""""""""""""""""""""""""
1262
1263An important difference between :class:`StrEnum` and other Enums is the
1264:meth:`__str__` method; because :class:`StrEnum` members are strings, some
1265parts of Python will read the string data directly, while others will call
1266:meth:`str()`. To make those two operations have the same result,
1267:meth:`StrEnum.__str__` will be the same as :meth:`str.__str__` so that
1268``str(StrEnum.member) == StrEnum.member`` is true.
1269