blob: 54defeba1b4e07625f0d3695645f59aa8f1faf7f [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
Ethan Furman6b3d64a2013-06-14 16:55:46 -07007.. :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>
11
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
22
23Module Contents
24---------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -070025
26This module defines two enumeration classes that can be used to define unique
Ethan Furmanf24bb352013-07-18 17:05:39 -070027sets of names and values: :class:`Enum` and :class:`IntEnum`. It also defines
Ethan Furmanc72e6382014-02-06 08:13:14 -080028one decorator, :func:`unique`.
29
30.. class:: Enum
31
32 Base class for creating enumerated constants. See section
Larry Hastingsad88d7a2014-02-10 04:26:10 -080033 `Functional API`_ for an alternate construction syntax.
Ethan Furmanc72e6382014-02-06 08:13:14 -080034
35.. class:: IntEnum
36
37 Base class for creating enumerated constants that are also
38 subclasses of :class:`int`.
39
Ethan Furman73fc5862016-08-05 16:03:16 -070040.. class:: AutoEnum
41
42 Base class for creating automatically numbered members (may
43 be combined with IntEnum if desired).
44
45 .. versionadded:: 3.6
46
Ethan Furmanc72e6382014-02-06 08:13:14 -080047.. function:: unique
48
49 Enum class decorator that ensures only one name is bound to any one value.
Ethan Furmanf24bb352013-07-18 17:05:39 -070050
Ethan Furman6b3d64a2013-06-14 16:55:46 -070051
52Creating an Enum
53----------------
54
55Enumerations are created using the :keyword:`class` syntax, which makes them
56easy to read and write. An alternative creation method is described in
Ethan Furman73fc5862016-08-05 16:03:16 -070057`Functional API`_. To define a simple enumeration, subclass :class:`AutoEnum`
58as follows::
Ethan Furman6b3d64a2013-06-14 16:55:46 -070059
Ethan Furman73fc5862016-08-05 16:03:16 -070060 >>> from enum import AutoEnum
61 >>> class Color(AutoEnum):
62 ... red
63 ... green
64 ... blue
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070065 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -070066
Ethan Furman455bfde2013-09-08 23:48:34 -070067.. note:: Nomenclature
68
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070069 - The class :class:`Color` is an *enumeration* (or *enum*)
70 - The attributes :attr:`Color.red`, :attr:`Color.green`, etc., are
71 *enumeration members* (or *enum members*).
72 - The enum members have *names* and *values* (the name of
73 :attr:`Color.red` is ``red``, the value of :attr:`Color.blue` is
74 ``3``, etc.)
Ethan Furman6b3d64a2013-06-14 16:55:46 -070075
Ethan Furman9a1daf52013-09-27 22:58:06 -070076.. note::
77
78 Even though we use the :keyword:`class` syntax to create Enums, Enums
79 are not normal Python classes. See `How are Enums different?`_ for
80 more details.
81
Ethan Furman73fc5862016-08-05 16:03:16 -070082To create your own automatic :class:`Enum` classes, you need to add a
83:meth:`_generate_next_value_` method; it will be used to create missing values
84for any members after its definition.
85
86.. versionadded:: 3.6
87
88If you need full control of the member values, use :class:`Enum` as the base
89class and specify the values manually::
90
91 >>> from enum import Enum
92 >>> class Color(Enum):
93 ... red = 19
94 ... green = 7.9182
95 ... blue = 'periwinkle'
96 ...
97
98We'll use the following Enum for the examples below::
99
100 >>> class Color(Enum):
101 ... red = 1
102 ... green = 2
103 ... blue = 3
104 ...
105
106Enum Details
107------------
108
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700109Enumeration members have human readable string representations::
110
111 >>> print(Color.red)
112 Color.red
113
114...while their ``repr`` has more information::
115
116 >>> print(repr(Color.red))
117 <Color.red: 1>
118
119The *type* of an enumeration member is the enumeration it belongs to::
120
121 >>> type(Color.red)
122 <enum 'Color'>
123 >>> isinstance(Color.green, Color)
124 True
125 >>>
126
127Enum members also have a property that contains just their item name::
128
129 >>> print(Color.red.name)
130 red
131
132Enumerations support iteration, in definition order::
133
134 >>> class Shake(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700135 ... vanilla = 7
136 ... chocolate = 4
137 ... cookies = 9
138 ... mint = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700139 ...
140 >>> for shake in Shake:
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700141 ... print(shake)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700142 ...
143 Shake.vanilla
144 Shake.chocolate
145 Shake.cookies
146 Shake.mint
147
148Enumeration members are hashable, so they can be used in dictionaries and sets::
149
150 >>> apples = {}
151 >>> apples[Color.red] = 'red delicious'
152 >>> apples[Color.green] = 'granny smith'
153 >>> apples == {Color.red: 'red delicious', Color.green: 'granny smith'}
154 True
155
156
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700157Programmatic access to enumeration members and their attributes
158---------------------------------------------------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700159
160Sometimes it's useful to access members in enumerations programmatically (i.e.
161situations where ``Color.red`` won't do because the exact color is not known
162at program-writing time). ``Enum`` allows such access::
163
164 >>> Color(1)
165 <Color.red: 1>
166 >>> Color(3)
167 <Color.blue: 3>
168
169If you want to access enum members by *name*, use item access::
170
171 >>> Color['red']
172 <Color.red: 1>
173 >>> Color['green']
174 <Color.green: 2>
175
Larry Hastings3732ed22014-03-15 21:13:56 -0700176If you have an enum member and need its :attr:`name` or :attr:`value`::
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700177
178 >>> member = Color.red
179 >>> member.name
180 'red'
181 >>> member.value
182 1
183
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700184
185Duplicating enum members and values
186-----------------------------------
187
188Having two enum members with the same name is invalid::
189
190 >>> class Shape(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700191 ... square = 2
192 ... square = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700193 ...
194 Traceback (most recent call last):
195 ...
196 TypeError: Attempted to reuse key: 'square'
197
198However, two enum members are allowed to have the same value. Given two members
199A and B with the same value (and A defined first), B is an alias to A. By-value
200lookup of the value of A and B will return A. By-name lookup of B will also
201return A::
202
203 >>> class Shape(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700204 ... square = 2
205 ... diamond = 1
206 ... circle = 3
207 ... alias_for_square = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700208 ...
209 >>> Shape.square
210 <Shape.square: 2>
211 >>> Shape.alias_for_square
212 <Shape.square: 2>
213 >>> Shape(2)
214 <Shape.square: 2>
215
Ethan Furman101e0742013-09-15 12:34:36 -0700216.. note::
217
218 Attempting to create a member with the same name as an already
219 defined attribute (another member, a method, etc.) or attempting to create
220 an attribute with the same name as a member is not allowed.
221
Ethan Furmanf24bb352013-07-18 17:05:39 -0700222
223Ensuring unique enumeration values
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700224----------------------------------
Ethan Furmanf24bb352013-07-18 17:05:39 -0700225
226By default, enumerations allow multiple names as aliases for the same value.
227When this behavior isn't desired, the following decorator can be used to
228ensure each value is used only once in the enumeration:
229
230.. decorator:: unique
231
232A :keyword:`class` decorator specifically for enumerations. It searches an
233enumeration's :attr:`__members__` gathering any aliases it finds; if any are
234found :exc:`ValueError` is raised with the details::
235
236 >>> from enum import Enum, unique
237 >>> @unique
238 ... class Mistake(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700239 ... one = 1
240 ... two = 2
241 ... three = 3
242 ... four = 3
243 ...
Ethan Furmanf24bb352013-07-18 17:05:39 -0700244 Traceback (most recent call last):
245 ...
246 ValueError: duplicate values found in <enum 'Mistake'>: four -> three
247
248
249Iteration
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700250---------
Ethan Furmanf24bb352013-07-18 17:05:39 -0700251
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700252Iterating over the members of an enum does not provide the aliases::
253
254 >>> list(Shape)
255 [<Shape.square: 2>, <Shape.diamond: 1>, <Shape.circle: 3>]
256
257The special attribute ``__members__`` is an ordered dictionary mapping names
258to members. It includes all names defined in the enumeration, including the
259aliases::
260
261 >>> for name, member in Shape.__members__.items():
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700262 ... name, member
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700263 ...
264 ('square', <Shape.square: 2>)
265 ('diamond', <Shape.diamond: 1>)
266 ('circle', <Shape.circle: 3>)
267 ('alias_for_square', <Shape.square: 2>)
268
269The ``__members__`` attribute can be used for detailed programmatic access to
270the enumeration members. For example, finding all the aliases::
271
Ethan Furman73fc5862016-08-05 16:03:16 -0700272 >>> [
273 ... name
274 ... for name, member in Shape.__members__.items()
275 ... if member.name != name
276 ... ]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700277 ['alias_for_square']
278
Ethan Furmanf24bb352013-07-18 17:05:39 -0700279
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700280Comparisons
281-----------
282
283Enumeration members are compared by identity::
284
285 >>> Color.red is Color.red
286 True
287 >>> Color.red is Color.blue
288 False
289 >>> Color.red is not Color.blue
290 True
291
292Ordered comparisons between enumeration values are *not* supported. Enum
293members are not integers (but see `IntEnum`_ below)::
294
295 >>> Color.red < Color.blue
296 Traceback (most recent call last):
297 File "<stdin>", line 1, in <module>
Ethan Furman73fc5862016-08-05 16:03:16 -0700298 TypeError: '<' not supported between instances of 'Color' and 'Color'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700299
300Equality comparisons are defined though::
301
302 >>> Color.blue == Color.red
303 False
304 >>> Color.blue != Color.red
305 True
306 >>> Color.blue == Color.blue
307 True
308
309Comparisons against non-enumeration values will always compare not equal
Ezio Melotti93d7dda2013-10-05 04:13:18 +0300310(again, :class:`IntEnum` was explicitly designed to behave differently, see
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700311below)::
312
313 >>> Color.blue == 2
314 False
315
316
317Allowed members and attributes of enumerations
318----------------------------------------------
319
320The examples above use integers for enumeration values. Using integers is
Ethan Furman73fc5862016-08-05 16:03:16 -0700321short and handy (and provided by default by :class:`AutoEnum` and the
322`Functional API`_), but not strictly enforced. In the vast majority of
323use-cases, one doesn't care what the actual value of an enumeration is.
324But if the value *is* important, enumerations can have arbitrary values.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700325
326Enumerations are Python classes, and can have methods and special methods as
327usual. If we have this enumeration::
328
329 >>> class Mood(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700330 ... funky = 1
331 ... happy = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700332 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700333 ... def describe(self):
334 ... # self is the member here
335 ... return self.name, self.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700336 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700337 ... def __str__(self):
338 ... return 'my custom str! {0}'.format(self.value)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700339 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700340 ... @classmethod
341 ... def favorite_mood(cls):
342 ... # cls here is the enumeration
343 ... return cls.happy
344 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700345
346Then::
347
348 >>> Mood.favorite_mood()
349 <Mood.happy: 3>
350 >>> Mood.happy.describe()
351 ('happy', 3)
352 >>> str(Mood.funky)
353 'my custom str! 1'
354
Martin Pantera90a4a92016-05-30 04:04:50 +0000355The rules for what is allowed are as follows: names that start and end with
356a single underscore are reserved by enum and cannot be used; all other
Ethan Furman8be6fac2014-11-01 07:40:22 -0700357attributes defined within an enumeration will become members of this
358enumeration, with the exception of special methods (:meth:`__str__`,
359:meth:`__add__`, etc.) and descriptors (methods are also descriptors).
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700360
361Note: if your enumeration defines :meth:`__new__` and/or :meth:`__init__` then
362whatever value(s) were given to the enum member will be passed into those
363methods. See `Planet`_ for an example.
364
365
366Restricted subclassing of enumerations
367--------------------------------------
368
369Subclassing an enumeration is allowed only if the enumeration does not define
370any members. So this is forbidden::
371
372 >>> class MoreColor(Color):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700373 ... pink = 17
374 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700375 Traceback (most recent call last):
376 ...
377 TypeError: Cannot extend enumerations
378
379But this is allowed::
380
381 >>> class Foo(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700382 ... def some_behavior(self):
383 ... pass
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700384 ...
385 >>> class Bar(Foo):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700386 ... happy = 1
387 ... sad = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700388 ...
389
390Allowing subclassing of enums that define members would lead to a violation of
391some important invariants of types and instances. On the other hand, it makes
392sense to allow sharing some common behavior between a group of enumerations.
393(See `OrderedEnum`_ for an example.)
394
395
396Pickling
397--------
398
399Enumerations can be pickled and unpickled::
400
401 >>> from test.test_enum import Fruit
402 >>> from pickle import dumps, loads
403 >>> Fruit.tomato is loads(dumps(Fruit.tomato))
404 True
405
406The usual restrictions for pickling apply: picklable enums must be defined in
407the top level of a module, since unpickling requires them to be importable
408from that module.
409
Ethan Furmanca1b7942014-02-08 11:36:27 -0800410.. note::
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700411
Ethan Furmanca1b7942014-02-08 11:36:27 -0800412 With pickle protocol version 4 it is possible to easily pickle enums
413 nested in other classes.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700414
Ethan Furman2da95042014-03-03 12:42:52 -0800415It is possible to modify how Enum members are pickled/unpickled by defining
416:meth:`__reduce_ex__` in the enumeration class.
417
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700418
419Functional API
420--------------
421
422The :class:`Enum` class is callable, providing the following functional API::
423
424 >>> Animal = Enum('Animal', 'ant bee cat dog')
425 >>> Animal
426 <enum 'Animal'>
427 >>> Animal.ant
428 <Animal.ant: 1>
429 >>> Animal.ant.value
430 1
431 >>> list(Animal)
432 [<Animal.ant: 1>, <Animal.bee: 2>, <Animal.cat: 3>, <Animal.dog: 4>]
433
Ethan Furman73fc5862016-08-05 16:03:16 -0700434The semantics of this API resemble :class:`~collections.namedtuple`.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700435
Ethan Furman73fc5862016-08-05 16:03:16 -0700436- the first argument of the call to :class:`Enum` is the name of the
437 enumeration;
438
439- the second argument is the *source* of enumeration member names. It can be a
440 whitespace-separated string of names, a sequence of names, a sequence of
441 2-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to
442 values;
443
444- the last two options enable assigning arbitrary values to enumerations; the
445 others auto-assign increasing integers starting with 1 (use the ``start``
446 parameter to specify a different starting value). A new class derived from
447 :class:`Enum` is returned. In other words, the above assignment to
448 :class:`Animal` is equivalent to::
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700449
Ethan Furman8a123292015-01-14 22:31:50 -0800450 >>> class Animal(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700451 ... ant = 1
452 ... bee = 2
453 ... cat = 3
454 ... dog = 4
455 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700456
Ethan Furmane2563462013-06-28 19:37:17 -0700457The reason for defaulting to ``1`` as the starting number and not ``0`` is
458that ``0`` is ``False`` in a boolean sense, but enum members all evaluate
459to ``True``.
460
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700461Pickling enums created with the functional API can be tricky as frame stack
462implementation details are used to try and figure out which module the
463enumeration is being created in (e.g. it will fail if you use a utility
Ethan Furman73fc5862016-08-05 16:03:16 -0700464function in a separate module, and also may not work on IronPython or Jython).
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700465The solution is to specify the module name explicitly as follows::
466
Ethan Furman8a123292015-01-14 22:31:50 -0800467 >>> Animal = Enum('Animal', 'ant bee cat dog', module=__name__)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700468
Ethan Furman2da95042014-03-03 12:42:52 -0800469.. warning::
470
Ethan Furman01cc2d52014-03-03 15:02:04 -0800471 If ``module`` is not supplied, and Enum cannot determine what it is,
Ethan Furman2da95042014-03-03 12:42:52 -0800472 the new Enum members will not be unpicklable; to keep errors closer to
473 the source, pickling will be disabled.
474
Ethan Furmanca1b7942014-02-08 11:36:27 -0800475The new pickle protocol 4 also, in some circumstances, relies on
Martin Panterbae5d812016-06-18 03:57:31 +0000476:attr:`~definition.__qualname__` being set to the location where pickle will be able
Ethan Furmanca1b7942014-02-08 11:36:27 -0800477to find the class. For example, if the class was made available in class
478SomeData in the global scope::
479
Ethan Furman8a123292015-01-14 22:31:50 -0800480 >>> Animal = Enum('Animal', 'ant bee cat dog', qualname='SomeData.Animal')
Ethan Furmanca1b7942014-02-08 11:36:27 -0800481
Ethan Furman2da95042014-03-03 12:42:52 -0800482The complete signature is::
483
Ethan Furman73fc5862016-08-05 16:03:16 -0700484 Enum(
485 value='NewEnumName',
486 names=<...>,
487 *,
488 module='...',
489 qualname='...',
490 type=<mixed-in class>,
491 start=1,
492 )
Ethan Furman2da95042014-03-03 12:42:52 -0800493
Ethan Furman01cc2d52014-03-03 15:02:04 -0800494:value: What the new Enum class will record as its name.
Ethan Furman2da95042014-03-03 12:42:52 -0800495
Zachary Waredbd1c432014-03-20 10:01:48 -0500496:names: The Enum members. This can be a whitespace or comma separated string
Ethan Furmand9925a12014-09-16 20:35:55 -0700497 (values will start at 1 unless otherwise specified)::
Ethan Furman2da95042014-03-03 12:42:52 -0800498
Ethan Furman01cc2d52014-03-03 15:02:04 -0800499 'red green blue' | 'red,green,blue' | 'red, green, blue'
Ethan Furman2da95042014-03-03 12:42:52 -0800500
Ethan Furman8a123292015-01-14 22:31:50 -0800501 or an iterator of names::
502
503 ['red', 'green', 'blue']
504
Ethan Furman01cc2d52014-03-03 15:02:04 -0800505 or an iterator of (name, value) pairs::
Ethan Furman2da95042014-03-03 12:42:52 -0800506
507 [('cyan', 4), ('magenta', 5), ('yellow', 6)]
508
Ethan Furman01cc2d52014-03-03 15:02:04 -0800509 or a mapping::
Ethan Furman2da95042014-03-03 12:42:52 -0800510
Zachary Waredbd1c432014-03-20 10:01:48 -0500511 {'chartreuse': 7, 'sea_green': 11, 'rosemary': 42}
Ethan Furman2da95042014-03-03 12:42:52 -0800512
Ethan Furman01cc2d52014-03-03 15:02:04 -0800513:module: name of module where new Enum class can be found.
Ethan Furman2da95042014-03-03 12:42:52 -0800514
Ethan Furman01cc2d52014-03-03 15:02:04 -0800515:qualname: where in module new Enum class can be found.
Ethan Furman2da95042014-03-03 12:42:52 -0800516
Ethan Furman01cc2d52014-03-03 15:02:04 -0800517:type: type to mix in to new Enum class.
Ethan Furman2da95042014-03-03 12:42:52 -0800518
Yury Selivanov4dde5872015-09-11 00:48:21 -0400519:start: number to start counting at if only names are passed in.
Ethan Furmand9925a12014-09-16 20:35:55 -0700520
Berker Peksag60efd792014-09-18 05:23:14 +0300521.. versionchanged:: 3.5
522 The *start* parameter was added.
523
Ethan Furmanca1b7942014-02-08 11:36:27 -0800524
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700525Derived Enumerations
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700526--------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700527
Ethan Furman73fc5862016-08-05 16:03:16 -0700528AutoEnum
529^^^^^^^^
530
531This version of :class:`Enum` automatically assigns numbers as the values
532for the enumeration members, while still allowing values to be specified
533when needed::
534
535 >>> from enum import AutoEnum
536 >>> class Color(AutoEnum):
537 ... red
538 ... green = 5
539 ... blue
540 ...
541 >>> list(Color)
542 [<Color.red: 1>, <Color.green: 5>, <Color.blue: 6>]
543
544.. note:: Name Lookup
545
546 By default the names :func:`property`, :func:`classmethod`, and
547 :func:`staticmethod` are shielded from becoming members. To enable
548 them, or to specify a different set of shielded names, specify the
549 ignore parameter::
550
551 >>> class AddressType(AutoEnum, ignore='classmethod staticmethod'):
552 ... pobox
553 ... mailbox
554 ... property
555 ...
556
557.. versionadded:: 3.6
558
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700559IntEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700560^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700561
Ethan Furman73fc5862016-08-05 16:03:16 -0700562Another variation of :class:`Enum` which is also a subclass of
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700563:class:`int`. Members of an :class:`IntEnum` can be compared to integers;
564by extension, integer enumerations of different types can also be compared
565to each other::
566
567 >>> from enum import IntEnum
568 >>> class Shape(IntEnum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700569 ... circle = 1
570 ... square = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700571 ...
572 >>> class Request(IntEnum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700573 ... post = 1
574 ... get = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700575 ...
576 >>> Shape == 1
577 False
578 >>> Shape.circle == 1
579 True
580 >>> Shape.circle == Request.post
581 True
582
583However, they still can't be compared to standard :class:`Enum` enumerations::
584
585 >>> class Shape(IntEnum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700586 ... circle = 1
587 ... square = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700588 ...
589 >>> class Color(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700590 ... red = 1
591 ... green = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700592 ...
593 >>> Shape.circle == Color.red
594 False
595
596:class:`IntEnum` values behave like integers in other ways you'd expect::
597
598 >>> int(Shape.circle)
599 1
600 >>> ['a', 'b', 'c'][Shape.circle]
601 'b'
602 >>> [i for i in range(Shape.square)]
603 [0, 1]
604
Ethan Furman73fc5862016-08-05 16:03:16 -0700605For the vast majority of code, :class:`Enum` and :class:`AutoEnum` are strongly
606recommended, since :class:`IntEnum` breaks some semantic promises of an
607enumeration (by being comparable to integers, and thus by transitivity to other
608unrelated ``IntEnum`` enumerations). It should be used only in special cases
609where there's no other choice; for example, when integer constants are replaced
610with enumerations and backwards compatibility is required with code that still
611expects integers.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700612
613Others
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700614^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700615
616While :class:`IntEnum` is part of the :mod:`enum` module, it would be very
617simple to implement independently::
618
619 class IntEnum(int, Enum):
620 pass
621
622This demonstrates how similar derived enumerations can be defined; for example
Ethan Furman73fc5862016-08-05 16:03:16 -0700623an :class:`AutoIntEnum` that mixes in :class:`int` with :class:`AutoEnum`
624to get members that are :class:`int` (but keep in mind the warnings for
625:class:`IntEnum`).
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700626
627Some rules:
628
6291. When subclassing :class:`Enum`, mix-in types must appear before
630 :class:`Enum` itself in the sequence of bases, as in the :class:`IntEnum`
631 example above.
6322. While :class:`Enum` can have members of any type, once you mix in an
633 additional type, all the members must have values of that type, e.g.
634 :class:`int` above. This restriction does not apply to mix-ins which only
635 add methods and don't specify another data type such as :class:`int` or
636 :class:`str`.
6373. When another data type is mixed in, the :attr:`value` attribute is *not the
Zachary Waredbd1c432014-03-20 10:01:48 -0500638 same* as the enum member itself, although it is equivalent and will compare
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700639 equal.
Martin Panterd5db1472016-02-08 01:34:09 +00006404. %-style formatting: `%s` and `%r` call the :class:`Enum` class's
641 :meth:`__str__` and :meth:`__repr__` respectively; other codes (such as
642 `%i` or `%h` for IntEnum) treat the enum member as its mixed-in type.
Martin Panterbc1ee462016-02-13 00:41:37 +00006435. :ref:`Formatted string literals <f-strings>`, :meth:`str.format`,
644 and :func:`format` will use the mixed-in
Martin Panterd5db1472016-02-08 01:34:09 +0000645 type's :meth:`__format__`. If the :class:`Enum` class's :func:`str` or
646 :func:`repr` is desired, use the `!s` or `!r` format codes.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700647
648
649Interesting examples
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700650--------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700651
Ethan Furman73fc5862016-08-05 16:03:16 -0700652While :class:`Enum`, :class:`AutoEnum`, and :class:`IntEnum` are expected
653to cover the majority of use-cases, they cannot cover them all. Here are
654recipes for some different types of enumerations that can be used directly,
655or as examples for creating one's own.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700656
657
Ethan Furman73fc5862016-08-05 16:03:16 -0700658AutoDocEnum
659^^^^^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700660
Ethan Furman73fc5862016-08-05 16:03:16 -0700661Automatically numbers the members, and uses the given value as the
662:attr:`__doc__` string::
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700663
Ethan Furman73fc5862016-08-05 16:03:16 -0700664 >>> class AutoDocEnum(Enum):
665 ... def __new__(cls, doc):
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700666 ... value = len(cls.__members__) + 1
667 ... obj = object.__new__(cls)
Ethan Furman90262622013-07-30 12:24:25 -0700668 ... obj._value_ = value
Ethan Furman73fc5862016-08-05 16:03:16 -0700669 ... obj.__doc__ = doc
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700670 ... return obj
671 ...
Ethan Furman73fc5862016-08-05 16:03:16 -0700672 >>> class Color(AutoDocEnum):
673 ... red = 'stop'
674 ... green = 'go'
675 ... blue = 'what?'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700676 ...
677 >>> Color.green.value == 2
678 True
Ethan Furman73fc5862016-08-05 16:03:16 -0700679 >>> Color.green.__doc__
680 'go'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700681
Ethan Furman9a1daf52013-09-27 22:58:06 -0700682.. note::
683
684 The :meth:`__new__` method, if defined, is used during creation of the Enum
685 members; it is then replaced by Enum's :meth:`__new__` which is used after
Ethan Furmanf75805e2014-09-16 19:13:31 -0700686 class creation for lookup of existing members.
Ethan Furman9a1daf52013-09-27 22:58:06 -0700687
Ethan Furman73fc5862016-08-05 16:03:16 -0700688AutoNameEnum
689^^^^^^^^^^^^
690
691Automatically sets the member's value to its name::
692
693 >>> class AutoNameEnum(Enum):
694 ... def _generate_next_value_(name, start, count, last_value):
695 ... return name
696 ...
697 >>> class Color(AutoNameEnum):
698 ... red
699 ... green
700 ... blue
701 ...
702 >>> Color.green.value == 'green'
703 True
704
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700705
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700706OrderedEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700707^^^^^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700708
709An ordered enumeration that is not based on :class:`IntEnum` and so maintains
710the normal :class:`Enum` invariants (such as not being comparable to other
711enumerations)::
712
713 >>> class OrderedEnum(Enum):
714 ... def __ge__(self, other):
715 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700716 ... return self.value >= other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700717 ... return NotImplemented
718 ... def __gt__(self, other):
719 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700720 ... return self.value > other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700721 ... return NotImplemented
722 ... def __le__(self, other):
723 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700724 ... return self.value <= other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700725 ... return NotImplemented
726 ... def __lt__(self, other):
727 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700728 ... return self.value < other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700729 ... return NotImplemented
730 ...
731 >>> class Grade(OrderedEnum):
732 ... A = 5
733 ... B = 4
734 ... C = 3
735 ... D = 2
736 ... F = 1
737 ...
738 >>> Grade.C < Grade.A
739 True
740
741
Ethan Furmanf24bb352013-07-18 17:05:39 -0700742DuplicateFreeEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700743^^^^^^^^^^^^^^^^^
Ethan Furmanf24bb352013-07-18 17:05:39 -0700744
745Raises an error if a duplicate member name is found instead of creating an
746alias::
747
748 >>> class DuplicateFreeEnum(Enum):
749 ... def __init__(self, *args):
750 ... cls = self.__class__
751 ... if any(self.value == e.value for e in cls):
752 ... a = self.name
753 ... e = cls(self.value).name
754 ... raise ValueError(
755 ... "aliases not allowed in DuplicateFreeEnum: %r --> %r"
756 ... % (a, e))
757 ...
758 >>> class Color(DuplicateFreeEnum):
759 ... red = 1
760 ... green = 2
761 ... blue = 3
762 ... grene = 2
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700763 ...
Ethan Furmanf24bb352013-07-18 17:05:39 -0700764 Traceback (most recent call last):
765 ...
766 ValueError: aliases not allowed in DuplicateFreeEnum: 'grene' --> 'green'
767
768.. note::
769
770 This is a useful example for subclassing Enum to add or change other
Ezio Melotti93d7dda2013-10-05 04:13:18 +0300771 behaviors as well as disallowing aliases. If the only desired change is
Ezio Melotti17f1edd2013-10-05 04:26:06 +0300772 disallowing aliases, the :func:`unique` decorator can be used instead.
Ethan Furmanf24bb352013-07-18 17:05:39 -0700773
774
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700775Planet
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700776^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700777
778If :meth:`__new__` or :meth:`__init__` is defined the value of the enum member
779will be passed to those methods::
780
781 >>> class Planet(Enum):
782 ... MERCURY = (3.303e+23, 2.4397e6)
783 ... VENUS = (4.869e+24, 6.0518e6)
784 ... EARTH = (5.976e+24, 6.37814e6)
785 ... MARS = (6.421e+23, 3.3972e6)
786 ... JUPITER = (1.9e+27, 7.1492e7)
787 ... SATURN = (5.688e+26, 6.0268e7)
788 ... URANUS = (8.686e+25, 2.5559e7)
789 ... NEPTUNE = (1.024e+26, 2.4746e7)
790 ... def __init__(self, mass, radius):
791 ... self.mass = mass # in kilograms
792 ... self.radius = radius # in meters
793 ... @property
794 ... def surface_gravity(self):
795 ... # universal gravitational constant (m3 kg-1 s-2)
796 ... G = 6.67300E-11
797 ... return G * self.mass / (self.radius * self.radius)
798 ...
799 >>> Planet.EARTH.value
800 (5.976e+24, 6378140.0)
801 >>> Planet.EARTH.surface_gravity
802 9.802652743337129
Ethan Furman9a1daf52013-09-27 22:58:06 -0700803
804
805How are Enums different?
806------------------------
807
808Enums have a custom metaclass that affects many aspects of both derived Enum
809classes and their instances (members).
810
811
812Enum Classes
813^^^^^^^^^^^^
814
815The :class:`EnumMeta` metaclass is responsible for providing the
816:meth:`__contains__`, :meth:`__dir__`, :meth:`__iter__` and other methods that
817allow one to do things with an :class:`Enum` class that fail on a typical
818class, such as `list(Color)` or `some_var in Color`. :class:`EnumMeta` is
819responsible for ensuring that various other methods on the final :class:`Enum`
820class are correct (such as :meth:`__new__`, :meth:`__getnewargs__`,
Martin Panterd21e0b52015-10-10 10:36:22 +0000821:meth:`__str__` and :meth:`__repr__`).
Ethan Furman9a1daf52013-09-27 22:58:06 -0700822
823
824Enum Members (aka instances)
825^^^^^^^^^^^^^^^^^^^^^^^^^^^^
826
827The most interesting thing about Enum members is that they are singletons.
828:class:`EnumMeta` creates them all while it is creating the :class:`Enum`
829class itself, and then puts a custom :meth:`__new__` in place to ensure
830that no new ones are ever instantiated by returning only the existing
831member instances.
832
833
834Finer Points
835^^^^^^^^^^^^
836
Ethan Furman73fc5862016-08-05 16:03:16 -0700837Enum class signature
838~~~~~~~~~~~~~~~~~~~~
839
840 ``class SomeName(
841 AnEnum,
842 start=None,
843 ignore='staticmethod classmethod property',
844 ):``
845
846``start`` can be used by a :meth:`_generate_next_value_` method to specify a
847starting value.
848
849``ignore`` specifies which names, if any, will not attempt to auto-generate
850a new value (they will also be removed from the class body).
851
852
853Supported ``__dunder__`` names
854~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
855
856The :attr:`__members__` attribute is only available on the class.
857
858:meth:`__new__`, if specified, must create and return the enum members; it is
859also a very good idea to set the member's :attr:`_value_` appropriately. Once
860all the members are created it is no longer used.
861
862
863Supported ``_sunder_`` names
864~~~~~~~~~~~~~~~~~~~~~~~~~~~~
865
866- ``_order_`` -- used in Python 2/3 code to ensure member order is consistent [class attribute]
867
868- ``_name_`` -- name of the member (but use ``name`` for normal access)
869- ``_value_`` -- value of the member; can be set / modified in ``__new__`` (see ``_name_``)
870- ``_missing_`` -- a lookup function used when a value is not found (only after class creation)
871- ``_generate_next_value_`` -- a function to generate missing values (only during class creation)
872
873
874:meth:`_generate_next_value_` signature
875~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
876
877 ``def _generate_next_value_(name, start, count, last_value):``
878
879- ``name`` is the name of the member
880- ``start`` is the initital start value (if any) or None
881- ``count`` is the number of existing members in the enumeration
882- ``last_value`` is the value of the last enum member (if any) or None
883
884
885Enum member type
886~~~~~~~~~~~~~~~~
887
888``Enum`` members are instances of an ``Enum`` class, and even
889though they are accessible as ``EnumClass.member``, they should not be accessed
Ethan Furman748dad52015-11-20 13:12:26 -0800890directly from the member as that lookup may fail or, worse, return something
Ethan Furman73fc5862016-08-05 16:03:16 -0700891besides the ``Enum`` member you are looking for::
Ethan Furman9a1daf52013-09-27 22:58:06 -0700892
Ethan Furman748dad52015-11-20 13:12:26 -0800893 >>> class FieldTypes(Enum):
894 ... name = 0
895 ... value = 1
896 ... size = 2
Ethan Furman9a1daf52013-09-27 22:58:06 -0700897 ...
Ethan Furman748dad52015-11-20 13:12:26 -0800898 >>> FieldTypes.value.size
899 <FieldTypes.size: 2>
900 >>> FieldTypes.size.value
901 2
Ethan Furman9a1daf52013-09-27 22:58:06 -0700902
Ethan Furman748dad52015-11-20 13:12:26 -0800903.. versionchanged:: 3.5
904
Ethan Furman73fc5862016-08-05 16:03:16 -0700905
906Boolean value of ``Enum`` classes and members
907~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
908
909Enum classes that are mixed with non-Enum types (such as
Ethan Furman60255b62016-01-15 15:01:33 -0800910:class:`int`, :class:`str`, etc.) are evaluated according to the mixed-in
Ethan Furman73fc5862016-08-05 16:03:16 -0700911type's rules; otherwise, all members evaluate as :data:`True`. To make your own
Ethan Furman60255b62016-01-15 15:01:33 -0800912Enum's boolean evaluation depend on the member's value add the following to
913your class::
914
915 def __bool__(self):
Ethan Furman2ae4ea52016-01-16 12:39:53 -0800916 return bool(self.value)
Ethan Furman60255b62016-01-15 15:01:33 -0800917
Ethan Furman9a1daf52013-09-27 22:58:06 -0700918
Ethan Furman73fc5862016-08-05 16:03:16 -0700919Enum classes with methods
920~~~~~~~~~~~~~~~~~~~~~~~~~
921
922If you give your ``Enum`` subclass extra methods, like the `Planet`_
Ezio Melotti93d7dda2013-10-05 04:13:18 +0300923class above, those methods will show up in a :func:`dir` of the member,
924but not of the class::
Ethan Furman9a1daf52013-09-27 22:58:06 -0700925
926 >>> dir(Planet)
927 ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__']
928 >>> dir(Planet.EARTH)
929 ['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value']