blob: a3c51655576ba5f8000786eadac79ce8f7c7e3dd [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
Miss Islington (bot)b502c762020-09-14 13:49:29 -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 Furman65a5a472016-09-01 23:55:19 -070047.. class:: IntFlag
48
49 Base class for creating enumerated constants that can be combined using
50 the bitwise operators without losing their :class:`IntFlag` membership.
51 :class:`IntFlag` members are also subclasses of :class:`int`.
52
53.. class:: Flag
54
55 Base class for creating enumerated constants that can be combined using
56 the bitwise operations without losing their :class:`Flag` membership.
57
Ethan Furmanc72e6382014-02-06 08:13:14 -080058.. function:: unique
Victor Stinner8f881902020-08-19 19:25:22 +020059 :noindex:
Ethan Furmanc72e6382014-02-06 08:13:14 -080060
61 Enum class decorator that ensures only one name is bound to any one value.
Ethan Furmanf24bb352013-07-18 17:05:39 -070062
Ethan Furmanc16595e2016-09-10 23:36:59 -070063.. class:: auto
64
YoSTEALTH24bcefc2020-01-06 16:04:43 -060065 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 -070066
67.. versionadded:: 3.6 ``Flag``, ``IntFlag``, ``auto``
Ethan Furman65a5a472016-09-01 23:55:19 -070068
Ethan Furman6b3d64a2013-06-14 16:55:46 -070069
70Creating an Enum
71----------------
72
73Enumerations are created using the :keyword:`class` syntax, which makes them
74easy to read and write. An alternative creation method is described in
Ethan Furman332dbc72016-08-20 00:00:52 -070075`Functional API`_. To define an enumeration, subclass :class:`Enum` as
76follows::
Ethan Furman6b3d64a2013-06-14 16:55:46 -070077
Ethan Furman332dbc72016-08-20 00:00:52 -070078 >>> from enum import Enum
79 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -080080 ... RED = 1
81 ... GREEN = 2
82 ... BLUE = 3
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070083 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -070084
Ethan Furmanc16595e2016-09-10 23:36:59 -070085.. note:: Enum member values
86
87 Member values can be anything: :class:`int`, :class:`str`, etc.. If
88 the exact value is unimportant you may use :class:`auto` instances and an
89 appropriate value will be chosen for you. Care must be taken if you mix
90 :class:`auto` with other values.
91
Ethan Furman455bfde2013-09-08 23:48:34 -070092.. note:: Nomenclature
93
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070094 - The class :class:`Color` is an *enumeration* (or *enum*)
Ethan Furman23bb6f42016-11-21 09:22:05 -080095 - The attributes :attr:`Color.RED`, :attr:`Color.GREEN`, etc., are
96 *enumeration members* (or *enum members*) and are functionally constants.
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070097 - The enum members have *names* and *values* (the name of
Ethan Furman23bb6f42016-11-21 09:22:05 -080098 :attr:`Color.RED` is ``RED``, the value of :attr:`Color.BLUE` is
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070099 ``3``, etc.)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700100
Ethan Furman9a1daf52013-09-27 22:58:06 -0700101.. note::
102
103 Even though we use the :keyword:`class` syntax to create Enums, Enums
104 are not normal Python classes. See `How are Enums different?`_ for
105 more details.
106
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700107Enumeration members have human readable string representations::
108
Ethan Furman23bb6f42016-11-21 09:22:05 -0800109 >>> print(Color.RED)
110 Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700111
112...while their ``repr`` has more information::
113
Ethan Furman23bb6f42016-11-21 09:22:05 -0800114 >>> print(repr(Color.RED))
115 <Color.RED: 1>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700116
117The *type* of an enumeration member is the enumeration it belongs to::
118
Ethan Furman23bb6f42016-11-21 09:22:05 -0800119 >>> type(Color.RED)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700120 <enum 'Color'>
Ethan Furman23bb6f42016-11-21 09:22:05 -0800121 >>> isinstance(Color.GREEN, Color)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700122 True
123 >>>
124
125Enum members also have a property that contains just their item name::
126
Ethan Furman23bb6f42016-11-21 09:22:05 -0800127 >>> print(Color.RED.name)
128 RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700129
130Enumerations support iteration, in definition order::
131
132 >>> class Shake(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800133 ... VANILLA = 7
134 ... CHOCOLATE = 4
135 ... COOKIES = 9
136 ... MINT = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700137 ...
138 >>> for shake in Shake:
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700139 ... print(shake)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700140 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800141 Shake.VANILLA
142 Shake.CHOCOLATE
143 Shake.COOKIES
144 Shake.MINT
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700145
146Enumeration members are hashable, so they can be used in dictionaries and sets::
147
148 >>> apples = {}
Ethan Furman23bb6f42016-11-21 09:22:05 -0800149 >>> apples[Color.RED] = 'red delicious'
150 >>> apples[Color.GREEN] = 'granny smith'
151 >>> apples == {Color.RED: 'red delicious', Color.GREEN: 'granny smith'}
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700152 True
153
154
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700155Programmatic access to enumeration members and their attributes
156---------------------------------------------------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700157
158Sometimes it's useful to access members in enumerations programmatically (i.e.
Ethan Furman23bb6f42016-11-21 09:22:05 -0800159situations where ``Color.RED`` won't do because the exact color is not known
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700160at program-writing time). ``Enum`` allows such access::
161
162 >>> Color(1)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800163 <Color.RED: 1>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700164 >>> Color(3)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800165 <Color.BLUE: 3>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700166
167If you want to access enum members by *name*, use item access::
168
Ethan Furman23bb6f42016-11-21 09:22:05 -0800169 >>> Color['RED']
170 <Color.RED: 1>
171 >>> Color['GREEN']
172 <Color.GREEN: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700173
Larry Hastings3732ed22014-03-15 21:13:56 -0700174If you have an enum member and need its :attr:`name` or :attr:`value`::
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700175
Ethan Furman23bb6f42016-11-21 09:22:05 -0800176 >>> member = Color.RED
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700177 >>> member.name
Ethan Furman23bb6f42016-11-21 09:22:05 -0800178 'RED'
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700179 >>> member.value
180 1
181
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700182
183Duplicating enum members and values
184-----------------------------------
185
186Having two enum members with the same name is invalid::
187
188 >>> class Shape(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800189 ... SQUARE = 2
190 ... SQUARE = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700191 ...
192 Traceback (most recent call last):
193 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800194 TypeError: Attempted to reuse key: 'SQUARE'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700195
196However, two enum members are allowed to have the same value. Given two members
197A and B with the same value (and A defined first), B is an alias to A. By-value
198lookup of the value of A and B will return A. By-name lookup of B will also
199return A::
200
201 >>> class Shape(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800202 ... SQUARE = 2
203 ... DIAMOND = 1
204 ... CIRCLE = 3
205 ... ALIAS_FOR_SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700206 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800207 >>> Shape.SQUARE
208 <Shape.SQUARE: 2>
209 >>> Shape.ALIAS_FOR_SQUARE
210 <Shape.SQUARE: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700211 >>> Shape(2)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800212 <Shape.SQUARE: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700213
Ethan Furman101e0742013-09-15 12:34:36 -0700214.. note::
215
216 Attempting to create a member with the same name as an already
217 defined attribute (another member, a method, etc.) or attempting to create
218 an attribute with the same name as a member is not allowed.
219
Ethan Furmanf24bb352013-07-18 17:05:39 -0700220
221Ensuring unique enumeration values
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700222----------------------------------
Ethan Furmanf24bb352013-07-18 17:05:39 -0700223
224By default, enumerations allow multiple names as aliases for the same value.
225When this behavior isn't desired, the following decorator can be used to
226ensure each value is used only once in the enumeration:
227
228.. decorator:: unique
229
230A :keyword:`class` decorator specifically for enumerations. It searches an
231enumeration's :attr:`__members__` gathering any aliases it finds; if any are
232found :exc:`ValueError` is raised with the details::
233
234 >>> from enum import Enum, unique
235 >>> @unique
236 ... class Mistake(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800237 ... ONE = 1
238 ... TWO = 2
239 ... THREE = 3
240 ... FOUR = 3
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700241 ...
Ethan Furmanf24bb352013-07-18 17:05:39 -0700242 Traceback (most recent call last):
243 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800244 ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
Ethan Furmanf24bb352013-07-18 17:05:39 -0700245
246
Ethan Furmanc16595e2016-09-10 23:36:59 -0700247Using automatic values
248----------------------
249
250If the exact value is unimportant you can use :class:`auto`::
251
252 >>> from enum import Enum, auto
253 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800254 ... RED = auto()
255 ... BLUE = auto()
256 ... GREEN = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700257 ...
258 >>> list(Color)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800259 [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
Ethan Furmanc16595e2016-09-10 23:36:59 -0700260
261The values are chosen by :func:`_generate_next_value_`, which can be
262overridden::
263
264 >>> class AutoName(Enum):
265 ... def _generate_next_value_(name, start, count, last_values):
266 ... return name
267 ...
268 >>> class Ordinal(AutoName):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800269 ... NORTH = auto()
270 ... SOUTH = auto()
271 ... EAST = auto()
272 ... WEST = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700273 ...
274 >>> list(Ordinal)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800275 [<Ordinal.NORTH: 'NORTH'>, <Ordinal.SOUTH: 'SOUTH'>, <Ordinal.EAST: 'EAST'>, <Ordinal.WEST: 'WEST'>]
Ethan Furmanc16595e2016-09-10 23:36:59 -0700276
277.. note::
278
279 The goal of the default :meth:`_generate_next_value_` methods is to provide
280 the next :class:`int` in sequence with the last :class:`int` provided, but
281 the way it does this is an implementation detail and may change.
282
Ethan Onstottd9a43e22020-04-28 13:20:55 -0400283.. note::
284
285 The :meth:`_generate_next_value_` method must be defined before any members.
286
Ethan Furmanf24bb352013-07-18 17:05:39 -0700287Iteration
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700288---------
Ethan Furmanf24bb352013-07-18 17:05:39 -0700289
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700290Iterating over the members of an enum does not provide the aliases::
291
292 >>> list(Shape)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800293 [<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700294
INADA Naokie57f91a2018-06-19 01:14:26 +0900295The special attribute ``__members__`` is a read-only ordered mapping of names
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700296to members. It includes all names defined in the enumeration, including the
297aliases::
298
299 >>> for name, member in Shape.__members__.items():
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700300 ... name, member
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700301 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800302 ('SQUARE', <Shape.SQUARE: 2>)
303 ('DIAMOND', <Shape.DIAMOND: 1>)
304 ('CIRCLE', <Shape.CIRCLE: 3>)
305 ('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700306
307The ``__members__`` attribute can be used for detailed programmatic access to
308the enumeration members. For example, finding all the aliases::
309
Ethan Furman332dbc72016-08-20 00:00:52 -0700310 >>> [name for name, member in Shape.__members__.items() if member.name != name]
Ethan Furman23bb6f42016-11-21 09:22:05 -0800311 ['ALIAS_FOR_SQUARE']
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700312
Ethan Furmanf24bb352013-07-18 17:05:39 -0700313
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700314Comparisons
315-----------
316
317Enumeration members are compared by identity::
318
Ethan Furman23bb6f42016-11-21 09:22:05 -0800319 >>> Color.RED is Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700320 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800321 >>> Color.RED is Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700322 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800323 >>> Color.RED is not Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700324 True
325
326Ordered comparisons between enumeration values are *not* supported. Enum
327members are not integers (but see `IntEnum`_ below)::
328
Ethan Furman23bb6f42016-11-21 09:22:05 -0800329 >>> Color.RED < Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700330 Traceback (most recent call last):
331 File "<stdin>", line 1, in <module>
Ethan Furmane8e61272016-08-20 07:19:31 -0700332 TypeError: '<' not supported between instances of 'Color' and 'Color'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700333
334Equality comparisons are defined though::
335
Ethan Furman23bb6f42016-11-21 09:22:05 -0800336 >>> Color.BLUE == Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700337 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800338 >>> Color.BLUE != Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700339 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800340 >>> Color.BLUE == Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700341 True
342
343Comparisons against non-enumeration values will always compare not equal
Ezio Melotti93d7dda2013-10-05 04:13:18 +0300344(again, :class:`IntEnum` was explicitly designed to behave differently, see
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700345below)::
346
Ethan Furman23bb6f42016-11-21 09:22:05 -0800347 >>> Color.BLUE == 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700348 False
349
350
351Allowed members and attributes of enumerations
352----------------------------------------------
353
354The examples above use integers for enumeration values. Using integers is
Ethan Furman332dbc72016-08-20 00:00:52 -0700355short and handy (and provided by default by the `Functional API`_), but not
356strictly enforced. In the vast majority of use-cases, one doesn't care what
357the actual value of an enumeration is. But if the value *is* important,
358enumerations can have arbitrary values.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700359
360Enumerations are Python classes, and can have methods and special methods as
361usual. If we have this enumeration::
362
363 >>> class Mood(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800364 ... FUNKY = 1
365 ... HAPPY = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700366 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700367 ... def describe(self):
368 ... # self is the member here
369 ... return self.name, self.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700370 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700371 ... def __str__(self):
372 ... return 'my custom str! {0}'.format(self.value)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700373 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700374 ... @classmethod
375 ... def favorite_mood(cls):
376 ... # cls here is the enumeration
Ethan Furman23bb6f42016-11-21 09:22:05 -0800377 ... return cls.HAPPY
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700378 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700379
380Then::
381
382 >>> Mood.favorite_mood()
Ethan Furman23bb6f42016-11-21 09:22:05 -0800383 <Mood.HAPPY: 3>
384 >>> Mood.HAPPY.describe()
385 ('HAPPY', 3)
386 >>> str(Mood.FUNKY)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700387 'my custom str! 1'
388
Martin Pantera90a4a92016-05-30 04:04:50 +0000389The rules for what is allowed are as follows: names that start and end with
390a single underscore are reserved by enum and cannot be used; all other
Ethan Furman8be6fac2014-11-01 07:40:22 -0700391attributes defined within an enumeration will become members of this
392enumeration, with the exception of special methods (:meth:`__str__`,
Ethan Furmana4b1bb42018-01-22 07:56:37 -0800393:meth:`__add__`, etc.), descriptors (methods are also descriptors), and
394variable names listed in :attr:`_ignore_`.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700395
396Note: if your enumeration defines :meth:`__new__` and/or :meth:`__init__` then
Antoined3c8d732019-08-20 03:41:31 +0200397any value(s) given to the enum member will be passed into those methods.
398See `Planet`_ for an example.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700399
400
Ethan Furman5bdab642018-09-21 19:03:09 -0700401Restricted Enum subclassing
402---------------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700403
Ethan Furman5bdab642018-09-21 19:03:09 -0700404A new :class:`Enum` class must have one base Enum class, up to one concrete
405data type, and as many :class:`object`-based mixin classes as needed. The
406order of these base classes is::
407
nu_nodfc8bb92019-01-27 23:07:47 +0100408 class EnumName([mix-in, ...,] [data-type,] base-enum):
Ethan Furman5bdab642018-09-21 19:03:09 -0700409 pass
410
411Also, subclassing an enumeration is allowed only if the enumeration does not define
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700412any members. So this is forbidden::
413
414 >>> class MoreColor(Color):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800415 ... PINK = 17
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700416 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700417 Traceback (most recent call last):
418 ...
419 TypeError: Cannot extend enumerations
420
421But this is allowed::
422
423 >>> class Foo(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700424 ... def some_behavior(self):
425 ... pass
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700426 ...
427 >>> class Bar(Foo):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800428 ... HAPPY = 1
429 ... SAD = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700430 ...
431
432Allowing subclassing of enums that define members would lead to a violation of
433some important invariants of types and instances. On the other hand, it makes
434sense to allow sharing some common behavior between a group of enumerations.
435(See `OrderedEnum`_ for an example.)
436
437
438Pickling
439--------
440
441Enumerations can be pickled and unpickled::
442
443 >>> from test.test_enum import Fruit
444 >>> from pickle import dumps, loads
Ethan Furman23bb6f42016-11-21 09:22:05 -0800445 >>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO))
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700446 True
447
448The usual restrictions for pickling apply: picklable enums must be defined in
449the top level of a module, since unpickling requires them to be importable
450from that module.
451
Ethan Furmanca1b7942014-02-08 11:36:27 -0800452.. note::
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700453
Ethan Furmanca1b7942014-02-08 11:36:27 -0800454 With pickle protocol version 4 it is possible to easily pickle enums
455 nested in other classes.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700456
Ethan Furman2da95042014-03-03 12:42:52 -0800457It is possible to modify how Enum members are pickled/unpickled by defining
458:meth:`__reduce_ex__` in the enumeration class.
459
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700460
461Functional API
462--------------
463
464The :class:`Enum` class is callable, providing the following functional API::
465
Ethan Furman23bb6f42016-11-21 09:22:05 -0800466 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG')
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700467 >>> Animal
468 <enum 'Animal'>
Ethan Furman23bb6f42016-11-21 09:22:05 -0800469 >>> Animal.ANT
470 <Animal.ANT: 1>
471 >>> Animal.ANT.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700472 1
473 >>> list(Animal)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800474 [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700475
Ethan Furman332dbc72016-08-20 00:00:52 -0700476The semantics of this API resemble :class:`~collections.namedtuple`. The first
477argument of the call to :class:`Enum` is the name of the enumeration.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700478
Ethan Furman332dbc72016-08-20 00:00:52 -0700479The second argument is the *source* of enumeration member names. It can be a
480whitespace-separated string of names, a sequence of names, a sequence of
4812-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to
482values. The last two options enable assigning arbitrary values to
483enumerations; the others auto-assign increasing integers starting with 1 (use
484the ``start`` parameter to specify a different starting value). A
485new class derived from :class:`Enum` is returned. In other words, the above
486assignment to :class:`Animal` is equivalent to::
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700487
Ethan Furman8a123292015-01-14 22:31:50 -0800488 >>> class Animal(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800489 ... ANT = 1
490 ... BEE = 2
491 ... CAT = 3
492 ... DOG = 4
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700493 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700494
Ethan Furmane2563462013-06-28 19:37:17 -0700495The reason for defaulting to ``1`` as the starting number and not ``0`` is
496that ``0`` is ``False`` in a boolean sense, but enum members all evaluate
497to ``True``.
498
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700499Pickling enums created with the functional API can be tricky as frame stack
500implementation details are used to try and figure out which module the
501enumeration is being created in (e.g. it will fail if you use a utility
Ethan Furman332dbc72016-08-20 00:00:52 -0700502function in separate module, and also may not work on IronPython or Jython).
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700503The solution is to specify the module name explicitly as follows::
504
Ethan Furman23bb6f42016-11-21 09:22:05 -0800505 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700506
Ethan Furman2da95042014-03-03 12:42:52 -0800507.. warning::
508
Ethan Furman01cc2d52014-03-03 15:02:04 -0800509 If ``module`` is not supplied, and Enum cannot determine what it is,
Ethan Furman2da95042014-03-03 12:42:52 -0800510 the new Enum members will not be unpicklable; to keep errors closer to
511 the source, pickling will be disabled.
512
Ethan Furmanca1b7942014-02-08 11:36:27 -0800513The new pickle protocol 4 also, in some circumstances, relies on
Martin Panterbae5d812016-06-18 03:57:31 +0000514:attr:`~definition.__qualname__` being set to the location where pickle will be able
Ethan Furmanca1b7942014-02-08 11:36:27 -0800515to find the class. For example, if the class was made available in class
516SomeData in the global scope::
517
Ethan Furman23bb6f42016-11-21 09:22:05 -0800518 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal')
Ethan Furmanca1b7942014-02-08 11:36:27 -0800519
Ethan Furman2da95042014-03-03 12:42:52 -0800520The complete signature is::
521
Ethan Furman332dbc72016-08-20 00:00:52 -0700522 Enum(value='NewEnumName', names=<...>, *, module='...', qualname='...', type=<mixed-in class>, start=1)
Ethan Furman2da95042014-03-03 12:42:52 -0800523
Ethan Furman01cc2d52014-03-03 15:02:04 -0800524:value: What the new Enum class will record as its name.
Ethan Furman2da95042014-03-03 12:42:52 -0800525
Zachary Waredbd1c432014-03-20 10:01:48 -0500526:names: The Enum members. This can be a whitespace or comma separated string
Ethan Furmand9925a12014-09-16 20:35:55 -0700527 (values will start at 1 unless otherwise specified)::
Ethan Furman2da95042014-03-03 12:42:52 -0800528
Ethan Furman23bb6f42016-11-21 09:22:05 -0800529 'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE'
Ethan Furman2da95042014-03-03 12:42:52 -0800530
Ethan Furman8a123292015-01-14 22:31:50 -0800531 or an iterator of names::
532
Ethan Furman23bb6f42016-11-21 09:22:05 -0800533 ['RED', 'GREEN', 'BLUE']
Ethan Furman8a123292015-01-14 22:31:50 -0800534
Ethan Furman01cc2d52014-03-03 15:02:04 -0800535 or an iterator of (name, value) pairs::
Ethan Furman2da95042014-03-03 12:42:52 -0800536
Ethan Furman23bb6f42016-11-21 09:22:05 -0800537 [('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)]
Ethan Furman2da95042014-03-03 12:42:52 -0800538
Ethan Furman01cc2d52014-03-03 15:02:04 -0800539 or a mapping::
Ethan Furman2da95042014-03-03 12:42:52 -0800540
Ethan Furman23bb6f42016-11-21 09:22:05 -0800541 {'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42}
Ethan Furman2da95042014-03-03 12:42:52 -0800542
Ethan Furman01cc2d52014-03-03 15:02:04 -0800543:module: name of module where new Enum class can be found.
Ethan Furman2da95042014-03-03 12:42:52 -0800544
Ethan Furman01cc2d52014-03-03 15:02:04 -0800545:qualname: where in module new Enum class can be found.
Ethan Furman2da95042014-03-03 12:42:52 -0800546
Ethan Furman01cc2d52014-03-03 15:02:04 -0800547:type: type to mix in to new Enum class.
Ethan Furman2da95042014-03-03 12:42:52 -0800548
Yury Selivanov4dde5872015-09-11 00:48:21 -0400549:start: number to start counting at if only names are passed in.
Ethan Furmand9925a12014-09-16 20:35:55 -0700550
Berker Peksag60efd792014-09-18 05:23:14 +0300551.. versionchanged:: 3.5
552 The *start* parameter was added.
553
Ethan Furmanca1b7942014-02-08 11:36:27 -0800554
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700555Derived Enumerations
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700556--------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700557
558IntEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700559^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700560
Ethan Furman65a5a472016-09-01 23:55:19 -0700561The first variation of :class:`Enum` that is provided is also a subclass of
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700562:class:`int`. Members of an :class:`IntEnum` can be compared to integers;
563by extension, integer enumerations of different types can also be compared
564to each other::
565
566 >>> from enum import IntEnum
567 >>> class Shape(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800568 ... CIRCLE = 1
569 ... SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700570 ...
571 >>> class Request(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800572 ... POST = 1
573 ... GET = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700574 ...
575 >>> Shape == 1
576 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800577 >>> Shape.CIRCLE == 1
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700578 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800579 >>> Shape.CIRCLE == Request.POST
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700580 True
581
582However, they still can't be compared to standard :class:`Enum` enumerations::
583
584 >>> class Shape(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800585 ... CIRCLE = 1
586 ... SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700587 ...
588 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800589 ... RED = 1
590 ... GREEN = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700591 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800592 >>> Shape.CIRCLE == Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700593 False
594
595:class:`IntEnum` values behave like integers in other ways you'd expect::
596
Ethan Furman23bb6f42016-11-21 09:22:05 -0800597 >>> int(Shape.CIRCLE)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700598 1
Ethan Furman23bb6f42016-11-21 09:22:05 -0800599 >>> ['a', 'b', 'c'][Shape.CIRCLE]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700600 'b'
Ethan Furman23bb6f42016-11-21 09:22:05 -0800601 >>> [i for i in range(Shape.SQUARE)]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700602 [0, 1]
603
Ethan Furman65a5a472016-09-01 23:55:19 -0700604
605IntFlag
606^^^^^^^
607
608The next variation of :class:`Enum` provided, :class:`IntFlag`, is also based
609on :class:`int`. The difference being :class:`IntFlag` members can be combined
610using the bitwise operators (&, \|, ^, ~) and the result is still an
611:class:`IntFlag` member. However, as the name implies, :class:`IntFlag`
Ethan Furman54924df2016-09-07 23:40:31 -0700612members also subclass :class:`int` and can be used wherever an :class:`int` is
613used. Any operation on an :class:`IntFlag` member besides the bit-wise
614operations will lose the :class:`IntFlag` membership.
Ethan Furman65a5a472016-09-01 23:55:19 -0700615
Ethan Furman25d94bb2016-09-02 16:32:32 -0700616.. versionadded:: 3.6
617
618Sample :class:`IntFlag` class::
619
Ethan Furman65a5a472016-09-01 23:55:19 -0700620 >>> from enum import IntFlag
621 >>> class Perm(IntFlag):
622 ... R = 4
623 ... W = 2
624 ... X = 1
625 ...
626 >>> Perm.R | Perm.W
627 <Perm.R|W: 6>
628 >>> Perm.R + Perm.W
629 6
630 >>> RW = Perm.R | Perm.W
631 >>> Perm.R in RW
632 True
633
Ethan Furman25d94bb2016-09-02 16:32:32 -0700634It is also possible to name the combinations::
635
636 >>> class Perm(IntFlag):
637 ... R = 4
638 ... W = 2
639 ... X = 1
640 ... RWX = 7
641 >>> Perm.RWX
642 <Perm.RWX: 7>
643 >>> ~Perm.RWX
Ethan Furman27682d22016-09-04 11:39:01 -0700644 <Perm.-8: -8>
Ethan Furman25d94bb2016-09-02 16:32:32 -0700645
646Another important difference between :class:`IntFlag` and :class:`Enum` is that
647if no flags are set (the value is 0), its boolean evaluation is :data:`False`::
648
649 >>> Perm.R & Perm.X
650 <Perm.0: 0>
651 >>> bool(Perm.R & Perm.X)
652 False
653
654Because :class:`IntFlag` members are also subclasses of :class:`int` they can
655be combined with them::
656
657 >>> Perm.X | 8
658 <Perm.8|X: 9>
Ethan Furman65a5a472016-09-01 23:55:19 -0700659
660
661Flag
662^^^^
663
664The last variation is :class:`Flag`. Like :class:`IntFlag`, :class:`Flag`
Ethan Furman25d94bb2016-09-02 16:32:32 -0700665members can be combined using the bitwise operators (&, \|, ^, ~). Unlike
Ethan Furman65a5a472016-09-01 23:55:19 -0700666:class:`IntFlag`, they cannot be combined with, nor compared against, any
Ethan Furmanc16595e2016-09-10 23:36:59 -0700667other :class:`Flag` enumeration, nor :class:`int`. While it is possible to
668specify the values directly it is recommended to use :class:`auto` as the
669value and let :class:`Flag` select an appropriate value.
Ethan Furman65a5a472016-09-01 23:55:19 -0700670
671.. versionadded:: 3.6
672
Ethan Furman25d94bb2016-09-02 16:32:32 -0700673Like :class:`IntFlag`, if a combination of :class:`Flag` members results in no
674flags being set, the boolean evaluation is :data:`False`::
675
Julian Kahnert0f31c742018-01-13 04:35:57 +0100676 >>> from enum import Flag, auto
Ethan Furman25d94bb2016-09-02 16:32:32 -0700677 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800678 ... RED = auto()
679 ... BLUE = auto()
680 ... GREEN = auto()
Ethan Furman25d94bb2016-09-02 16:32:32 -0700681 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800682 >>> Color.RED & Color.GREEN
Ethan Furman25d94bb2016-09-02 16:32:32 -0700683 <Color.0: 0>
Ethan Furman23bb6f42016-11-21 09:22:05 -0800684 >>> bool(Color.RED & Color.GREEN)
Ethan Furman25d94bb2016-09-02 16:32:32 -0700685 False
686
Ethan Furman27682d22016-09-04 11:39:01 -0700687Individual flags should have values that are powers of two (1, 2, 4, 8, ...),
688while combinations of flags won't::
689
690 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800691 ... RED = auto()
692 ... BLUE = auto()
693 ... GREEN = auto()
694 ... WHITE = RED | BLUE | GREEN
Ethan Furmanc16595e2016-09-10 23:36:59 -0700695 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800696 >>> Color.WHITE
697 <Color.WHITE: 7>
Ethan Furman27682d22016-09-04 11:39:01 -0700698
Ethan Furman25d94bb2016-09-02 16:32:32 -0700699Giving a name to the "no flags set" condition does not change its boolean
700value::
701
702 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800703 ... BLACK = 0
704 ... RED = auto()
705 ... BLUE = auto()
706 ... GREEN = auto()
Ethan Furman25d94bb2016-09-02 16:32:32 -0700707 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800708 >>> Color.BLACK
709 <Color.BLACK: 0>
710 >>> bool(Color.BLACK)
Ethan Furman25d94bb2016-09-02 16:32:32 -0700711 False
712
Ethan Furman65a5a472016-09-01 23:55:19 -0700713.. note::
714
715 For the majority of new code, :class:`Enum` and :class:`Flag` are strongly
716 recommended, since :class:`IntEnum` and :class:`IntFlag` break some
717 semantic promises of an enumeration (by being comparable to integers, and
718 thus by transitivity to other unrelated enumerations). :class:`IntEnum`
719 and :class:`IntFlag` should be used only in cases where :class:`Enum` and
720 :class:`Flag` will not do; for example, when integer constants are replaced
721 with enumerations, or for interoperability with other systems.
Ethan Furman332dbc72016-08-20 00:00:52 -0700722
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700723
724Others
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700725^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700726
727While :class:`IntEnum` is part of the :mod:`enum` module, it would be very
728simple to implement independently::
729
730 class IntEnum(int, Enum):
731 pass
732
733This demonstrates how similar derived enumerations can be defined; for example
Ethan Furman332dbc72016-08-20 00:00:52 -0700734a :class:`StrEnum` that mixes in :class:`str` instead of :class:`int`.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700735
736Some rules:
737
7381. When subclassing :class:`Enum`, mix-in types must appear before
739 :class:`Enum` itself in the sequence of bases, as in the :class:`IntEnum`
740 example above.
7412. While :class:`Enum` can have members of any type, once you mix in an
742 additional type, all the members must have values of that type, e.g.
743 :class:`int` above. This restriction does not apply to mix-ins which only
Antoined3c8d732019-08-20 03:41:31 +0200744 add methods and don't specify another type.
Ethan Furman6b3d64a2013-06-14 16:55:46 -07007453. When another data type is mixed in, the :attr:`value` attribute is *not the
Zachary Waredbd1c432014-03-20 10:01:48 -0500746 same* as the enum member itself, although it is equivalent and will compare
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700747 equal.
Martin Panterd5db1472016-02-08 01:34:09 +00007484. %-style formatting: `%s` and `%r` call the :class:`Enum` class's
749 :meth:`__str__` and :meth:`__repr__` respectively; other codes (such as
750 `%i` or `%h` for IntEnum) treat the enum member as its mixed-in type.
Martin Panterbc1ee462016-02-13 00:41:37 +00007515. :ref:`Formatted string literals <f-strings>`, :meth:`str.format`,
thatneat2f19e822019-07-04 11:28:37 -0700752 and :func:`format` will use the mixed-in type's :meth:`__format__`
753 unless :meth:`__str__` or :meth:`__format__` is overridden in the subclass,
754 in which case the overridden methods or :class:`Enum` methods will be used.
755 Use the !s and !r format codes to force usage of the :class:`Enum` class's
756 :meth:`__str__` and :meth:`__repr__` methods.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700757
Ethan Furmanf5223742018-09-12 10:00:30 -0700758When to use :meth:`__new__` vs. :meth:`__init__`
759------------------------------------------------
760
761:meth:`__new__` must be used whenever you want to customize the actual value of
762the :class:`Enum` member. Any other modifications may go in either
763:meth:`__new__` or :meth:`__init__`, with :meth:`__init__` being preferred.
764
765For example, if you want to pass several items to the constructor, but only
766want one of them to be the value::
767
768 >>> class Coordinate(bytes, Enum):
769 ... """
770 ... Coordinate with binary codes that can be indexed by the int code.
771 ... """
772 ... def __new__(cls, value, label, unit):
773 ... obj = bytes.__new__(cls, [value])
774 ... obj._value_ = value
775 ... obj.label = label
776 ... obj.unit = unit
777 ... return obj
778 ... PX = (0, 'P.X', 'km')
779 ... PY = (1, 'P.Y', 'km')
780 ... VX = (2, 'V.X', 'km/s')
781 ... VY = (3, 'V.Y', 'km/s')
782 ...
783
784 >>> print(Coordinate['PY'])
785 Coordinate.PY
786
787 >>> print(Coordinate(3))
788 Coordinate.VY
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700789
790Interesting examples
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700791--------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700792
Ethan Furman65a5a472016-09-01 23:55:19 -0700793While :class:`Enum`, :class:`IntEnum`, :class:`IntFlag`, and :class:`Flag` are
794expected to cover the majority of use-cases, they cannot cover them all. Here
795are recipes for some different types of enumerations that can be used directly,
796or as examples for creating one's own.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700797
798
Ethan Furman6a137e82016-09-07 08:17:15 -0700799Omitting values
800^^^^^^^^^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700801
Ethan Furman6a137e82016-09-07 08:17:15 -0700802In many use-cases one doesn't care what the actual value of an enumeration
803is. There are several ways to define this type of simple enumeration:
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700804
Ethan Furmanc16595e2016-09-10 23:36:59 -0700805- use instances of :class:`auto` for the value
Ethan Furman6a137e82016-09-07 08:17:15 -0700806- use instances of :class:`object` as the value
807- use a descriptive string as the value
808- use a tuple as the value and a custom :meth:`__new__` to replace the
809 tuple with an :class:`int` value
810
811Using any of these methods signifies to the user that these values are not
812important, and also enables one to add, remove, or reorder members without
813having to renumber the remaining members.
814
815Whichever method you choose, you should provide a :meth:`repr` that also hides
816the (unimportant) value::
817
818 >>> class NoValue(Enum):
819 ... def __repr__(self):
820 ... return '<%s.%s>' % (self.__class__.__name__, self.name)
821 ...
822
823
Ethan Furmanc16595e2016-09-10 23:36:59 -0700824Using :class:`auto`
825"""""""""""""""""""
826
Berker Peksag2a267a12017-01-02 05:51:04 +0300827Using :class:`auto` would look like::
Ethan Furmanc16595e2016-09-10 23:36:59 -0700828
829 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800830 ... RED = auto()
831 ... BLUE = auto()
832 ... GREEN = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700833 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800834 >>> Color.GREEN
835 <Color.GREEN>
Ethan Furmanc16595e2016-09-10 23:36:59 -0700836
837
Ethan Furman6a137e82016-09-07 08:17:15 -0700838Using :class:`object`
839"""""""""""""""""""""
840
841Using :class:`object` would look like::
842
843 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800844 ... RED = object()
845 ... GREEN = object()
846 ... BLUE = object()
Ethan Furman6a137e82016-09-07 08:17:15 -0700847 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800848 >>> Color.GREEN
849 <Color.GREEN>
Ethan Furman6a137e82016-09-07 08:17:15 -0700850
851
852Using a descriptive string
853""""""""""""""""""""""""""
854
855Using a string as the value would look like::
856
857 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800858 ... RED = 'stop'
859 ... GREEN = 'go'
860 ... BLUE = 'too fast!'
Ethan Furman6a137e82016-09-07 08:17:15 -0700861 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800862 >>> Color.GREEN
863 <Color.GREEN>
864 >>> Color.GREEN.value
Ethan Furman6a137e82016-09-07 08:17:15 -0700865 'go'
866
867
868Using a custom :meth:`__new__`
869""""""""""""""""""""""""""""""
870
871Using an auto-numbering :meth:`__new__` would look like::
872
873 >>> class AutoNumber(NoValue):
Ethan Furman332dbc72016-08-20 00:00:52 -0700874 ... def __new__(cls):
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700875 ... value = len(cls.__members__) + 1
876 ... obj = object.__new__(cls)
Ethan Furman90262622013-07-30 12:24:25 -0700877 ... obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700878 ... return obj
879 ...
Ethan Furman332dbc72016-08-20 00:00:52 -0700880 >>> class Color(AutoNumber):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800881 ... RED = ()
882 ... GREEN = ()
883 ... BLUE = ()
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700884 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800885 >>> Color.GREEN
886 <Color.GREEN>
887 >>> Color.GREEN.value
Ethan Furman6a137e82016-09-07 08:17:15 -0700888 2
889
Miss Islington (bot)64362c22020-09-22 20:58:32 -0700890To make a more general purpose ``AutoNumber``, add ``*args`` to the signature::
891
892 >>> class AutoNumber(NoValue):
893 ... def __new__(cls, *args): # this is the only change from above
894 ... value = len(cls.__members__) + 1
895 ... obj = object.__new__(cls)
896 ... obj._value_ = value
897 ... return obj
898 ...
899
900Then when you inherit from ``AutoNumber`` you can write your own ``__init__``
901to handle any extra arguments::
902
903 >>> class Swatch(AutoNumber):
904 ... def __init__(self, pantone='unknown'):
905 ... self.pantone = pantone
906 ... AUBURN = '3497'
907 ... SEA_GREEN = '1246'
908 ... BLEACHED_CORAL = () # New color, no Pantone code yet!
909 ...
910 >>> Swatch.SEA_GREEN
911 <Swatch.SEA_GREEN: 2>
912 >>> Swatch.SEA_GREEN.pantone
913 '1246'
914 >>> Swatch.BLEACHED_CORAL.pantone
915 'unknown'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700916
Ethan Furman9a1daf52013-09-27 22:58:06 -0700917.. note::
918
919 The :meth:`__new__` method, if defined, is used during creation of the Enum
920 members; it is then replaced by Enum's :meth:`__new__` which is used after
Ethan Furmanf75805e2014-09-16 19:13:31 -0700921 class creation for lookup of existing members.
Ethan Furman9a1daf52013-09-27 22:58:06 -0700922
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700923
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700924OrderedEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700925^^^^^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700926
927An ordered enumeration that is not based on :class:`IntEnum` and so maintains
928the normal :class:`Enum` invariants (such as not being comparable to other
929enumerations)::
930
931 >>> class OrderedEnum(Enum):
932 ... def __ge__(self, other):
933 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700934 ... return self.value >= other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700935 ... return NotImplemented
936 ... def __gt__(self, other):
937 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700938 ... return self.value > other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700939 ... return NotImplemented
940 ... def __le__(self, other):
941 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700942 ... return self.value <= other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700943 ... return NotImplemented
944 ... def __lt__(self, other):
945 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700946 ... return self.value < other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700947 ... return NotImplemented
948 ...
949 >>> class Grade(OrderedEnum):
950 ... A = 5
951 ... B = 4
952 ... C = 3
953 ... D = 2
954 ... F = 1
955 ...
956 >>> Grade.C < Grade.A
957 True
958
959
Ethan Furmanf24bb352013-07-18 17:05:39 -0700960DuplicateFreeEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700961^^^^^^^^^^^^^^^^^
Ethan Furmanf24bb352013-07-18 17:05:39 -0700962
963Raises an error if a duplicate member name is found instead of creating an
964alias::
965
966 >>> class DuplicateFreeEnum(Enum):
967 ... def __init__(self, *args):
968 ... cls = self.__class__
969 ... if any(self.value == e.value for e in cls):
970 ... a = self.name
971 ... e = cls(self.value).name
972 ... raise ValueError(
973 ... "aliases not allowed in DuplicateFreeEnum: %r --> %r"
974 ... % (a, e))
975 ...
976 >>> class Color(DuplicateFreeEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800977 ... RED = 1
978 ... GREEN = 2
979 ... BLUE = 3
980 ... GRENE = 2
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700981 ...
Ethan Furmanf24bb352013-07-18 17:05:39 -0700982 Traceback (most recent call last):
983 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800984 ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN'
Ethan Furmanf24bb352013-07-18 17:05:39 -0700985
986.. note::
987
988 This is a useful example for subclassing Enum to add or change other
Ezio Melotti93d7dda2013-10-05 04:13:18 +0300989 behaviors as well as disallowing aliases. If the only desired change is
Ezio Melotti17f1edd2013-10-05 04:26:06 +0300990 disallowing aliases, the :func:`unique` decorator can be used instead.
Ethan Furmanf24bb352013-07-18 17:05:39 -0700991
992
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700993Planet
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700994^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700995
996If :meth:`__new__` or :meth:`__init__` is defined the value of the enum member
997will be passed to those methods::
998
999 >>> class Planet(Enum):
1000 ... MERCURY = (3.303e+23, 2.4397e6)
1001 ... VENUS = (4.869e+24, 6.0518e6)
1002 ... EARTH = (5.976e+24, 6.37814e6)
1003 ... MARS = (6.421e+23, 3.3972e6)
1004 ... JUPITER = (1.9e+27, 7.1492e7)
1005 ... SATURN = (5.688e+26, 6.0268e7)
1006 ... URANUS = (8.686e+25, 2.5559e7)
1007 ... NEPTUNE = (1.024e+26, 2.4746e7)
1008 ... def __init__(self, mass, radius):
1009 ... self.mass = mass # in kilograms
1010 ... self.radius = radius # in meters
1011 ... @property
1012 ... def surface_gravity(self):
1013 ... # universal gravitational constant (m3 kg-1 s-2)
1014 ... G = 6.67300E-11
1015 ... return G * self.mass / (self.radius * self.radius)
1016 ...
1017 >>> Planet.EARTH.value
1018 (5.976e+24, 6378140.0)
1019 >>> Planet.EARTH.surface_gravity
1020 9.802652743337129
Ethan Furman9a1daf52013-09-27 22:58:06 -07001021
1022
Ethan Furmana4b1bb42018-01-22 07:56:37 -08001023TimePeriod
1024^^^^^^^^^^
1025
1026An example to show the :attr:`_ignore_` attribute in use::
1027
1028 >>> from datetime import timedelta
1029 >>> class Period(timedelta, Enum):
1030 ... "different lengths of time"
1031 ... _ignore_ = 'Period i'
1032 ... Period = vars()
1033 ... for i in range(367):
1034 ... Period['day_%d' % i] = i
1035 ...
1036 >>> list(Period)[:2]
1037 [<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>]
1038 >>> list(Period)[-2:]
1039 [<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>]
1040
1041
Ethan Furman9a1daf52013-09-27 22:58:06 -07001042How are Enums different?
1043------------------------
1044
1045Enums have a custom metaclass that affects many aspects of both derived Enum
1046classes and their instances (members).
1047
1048
1049Enum Classes
1050^^^^^^^^^^^^
1051
1052The :class:`EnumMeta` metaclass is responsible for providing the
1053:meth:`__contains__`, :meth:`__dir__`, :meth:`__iter__` and other methods that
1054allow one to do things with an :class:`Enum` class that fail on a typical
Rahul Jha94306522018-09-10 23:51:04 +05301055class, such as `list(Color)` or `some_enum_var in Color`. :class:`EnumMeta` is
Ethan Furman9a1daf52013-09-27 22:58:06 -07001056responsible for ensuring that various other methods on the final :class:`Enum`
1057class are correct (such as :meth:`__new__`, :meth:`__getnewargs__`,
Martin Panterd21e0b52015-10-10 10:36:22 +00001058:meth:`__str__` and :meth:`__repr__`).
Ethan Furman9a1daf52013-09-27 22:58:06 -07001059
1060
1061Enum Members (aka instances)
1062^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1063
1064The most interesting thing about Enum members is that they are singletons.
1065:class:`EnumMeta` creates them all while it is creating the :class:`Enum`
1066class itself, and then puts a custom :meth:`__new__` in place to ensure
1067that no new ones are ever instantiated by returning only the existing
1068member instances.
1069
1070
1071Finer Points
1072^^^^^^^^^^^^
1073
Ethan Furman65a5a472016-09-01 23:55:19 -07001074Supported ``__dunder__`` names
Ethan Furman6a137e82016-09-07 08:17:15 -07001075""""""""""""""""""""""""""""""
Ethan Furman9a1daf52013-09-27 22:58:06 -07001076
INADA Naokie57f91a2018-06-19 01:14:26 +09001077:attr:`__members__` is a read-only ordered mapping of ``member_name``:``member``
Ethan Furman65a5a472016-09-01 23:55:19 -07001078items. It is only available on the class.
Ethan Furman9a1daf52013-09-27 22:58:06 -07001079
Ethan Furman65a5a472016-09-01 23:55:19 -07001080:meth:`__new__`, if specified, must create and return the enum members; it is
1081also a very good idea to set the member's :attr:`_value_` appropriately. Once
1082all the members are created it is no longer used.
Ethan Furman748dad52015-11-20 13:12:26 -08001083
Ethan Furman60255b62016-01-15 15:01:33 -08001084
Ethan Furman65a5a472016-09-01 23:55:19 -07001085Supported ``_sunder_`` names
Ethan Furman6a137e82016-09-07 08:17:15 -07001086""""""""""""""""""""""""""""
Ethan Furman60255b62016-01-15 15:01:33 -08001087
Ethan Furman65a5a472016-09-01 23:55:19 -07001088- ``_name_`` -- name of the member
1089- ``_value_`` -- value of the member; can be set / modified in ``__new__``
Ethan Furman9a1daf52013-09-27 22:58:06 -07001090
Ethan Furman65a5a472016-09-01 23:55:19 -07001091- ``_missing_`` -- a lookup function used when a value is not found; may be
1092 overridden
Antoined3c8d732019-08-20 03:41:31 +02001093- ``_ignore_`` -- a list of names, either as a :class:`list` or a :class:`str`,
Ethan Furmana4b1bb42018-01-22 07:56:37 -08001094 that will not be transformed into members, and will be removed from the final
1095 class
Ethan Furman65a5a472016-09-01 23:55:19 -07001096- ``_order_`` -- used in Python 2/3 code to ensure member order is consistent
1097 (class attribute, removed during class creation)
Ethan Furmanc16595e2016-09-10 23:36:59 -07001098- ``_generate_next_value_`` -- used by the `Functional API`_ and by
1099 :class:`auto` to get an appropriate value for an enum member; may be
1100 overridden
Ethan Furman9a1daf52013-09-27 22:58:06 -07001101
Ethan Furmanc16595e2016-09-10 23:36:59 -07001102.. versionadded:: 3.6 ``_missing_``, ``_order_``, ``_generate_next_value_``
Ethan Furmana4b1bb42018-01-22 07:56:37 -08001103.. versionadded:: 3.7 ``_ignore_``
Ethan Furman332dbc72016-08-20 00:00:52 -07001104
Ethan Furman65a5a472016-09-01 23:55:19 -07001105To help keep Python 2 / Python 3 code in sync an :attr:`_order_` attribute can
1106be provided. It will be checked against the actual order of the enumeration
1107and raise an error if the two do not match::
Ethan Furmane8e61272016-08-20 07:19:31 -07001108
1109 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -08001110 ... _order_ = 'RED GREEN BLUE'
1111 ... RED = 1
1112 ... BLUE = 3
1113 ... GREEN = 2
Ethan Furmane8e61272016-08-20 07:19:31 -07001114 ...
1115 Traceback (most recent call last):
1116 ...
1117 TypeError: member order does not match _order_
1118
1119.. note::
1120
1121 In Python 2 code the :attr:`_order_` attribute is necessary as definition
Ethan Furman65a5a472016-09-01 23:55:19 -07001122 order is lost before it can be recorded.
1123
1124``Enum`` member type
Ethan Furman6a137e82016-09-07 08:17:15 -07001125""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001126
Ethan Furman54924df2016-09-07 23:40:31 -07001127:class:`Enum` members are instances of their :class:`Enum` class, and are
1128normally accessed as ``EnumClass.member``. Under certain circumstances they
1129can also be accessed as ``EnumClass.member.member``, but you should never do
1130this as that lookup may fail or, worse, return something besides the
Ethan Furman23bb6f42016-11-21 09:22:05 -08001131:class:`Enum` member you are looking for (this is another good reason to use
1132all-uppercase names for members)::
Ethan Furman65a5a472016-09-01 23:55:19 -07001133
1134 >>> class FieldTypes(Enum):
1135 ... name = 0
1136 ... value = 1
1137 ... size = 2
1138 ...
1139 >>> FieldTypes.value.size
1140 <FieldTypes.size: 2>
1141 >>> FieldTypes.size.value
1142 2
1143
1144.. versionchanged:: 3.5
1145
1146
1147Boolean value of ``Enum`` classes and members
Ethan Furman6a137e82016-09-07 08:17:15 -07001148"""""""""""""""""""""""""""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001149
Ethan Furman54924df2016-09-07 23:40:31 -07001150:class:`Enum` members that are mixed with non-:class:`Enum` types (such as
Ethan Furman65a5a472016-09-01 23:55:19 -07001151:class:`int`, :class:`str`, etc.) are evaluated according to the mixed-in
Ethan Furman54924df2016-09-07 23:40:31 -07001152type's rules; otherwise, all members evaluate as :data:`True`. To make your
1153own Enum's boolean evaluation depend on the member's value add the following to
Ethan Furman65a5a472016-09-01 23:55:19 -07001154your class::
1155
1156 def __bool__(self):
1157 return bool(self.value)
1158
Ethan Furman54924df2016-09-07 23:40:31 -07001159:class:`Enum` classes always evaluate as :data:`True`.
Ethan Furman65a5a472016-09-01 23:55:19 -07001160
1161
1162``Enum`` classes with methods
Ethan Furman6a137e82016-09-07 08:17:15 -07001163"""""""""""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001164
1165If you give your :class:`Enum` subclass extra methods, like the `Planet`_
1166class above, those methods will show up in a :func:`dir` of the member,
1167but not of the class::
1168
1169 >>> dir(Planet)
1170 ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__']
1171 >>> dir(Planet.EARTH)
1172 ['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value']
1173
Ethan Furman3515dcc2016-09-18 13:15:41 -07001174
1175Combining members of ``Flag``
1176"""""""""""""""""""""""""""""
1177
1178If a combination of Flag members is not named, the :func:`repr` will include
1179all named flags and all named combinations of flags that are in the value::
1180
1181 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -08001182 ... RED = auto()
1183 ... GREEN = auto()
1184 ... BLUE = auto()
1185 ... MAGENTA = RED | BLUE
1186 ... YELLOW = RED | GREEN
1187 ... CYAN = GREEN | BLUE
Ethan Furman3515dcc2016-09-18 13:15:41 -07001188 ...
1189 >>> Color(3) # named combination
Ethan Furman23bb6f42016-11-21 09:22:05 -08001190 <Color.YELLOW: 3>
Ethan Furman3515dcc2016-09-18 13:15:41 -07001191 >>> Color(7) # not named combination
Ethan Furman23bb6f42016-11-21 09:22:05 -08001192 <Color.CYAN|MAGENTA|BLUE|YELLOW|GREEN|RED: 7>
Ethan Furman3515dcc2016-09-18 13:15:41 -07001193