blob: 89a427c5e84fe0700aa44be29bbdcd492273dbb2 [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
Ethan Furman65a5a472016-09-01 23:55:19 -070026This module defines four enumeration classes that can be used to define unique
27sets of names and values: :class:`Enum`, :class:`IntEnum`, and
28:class:`IntFlags`. It also defines one decorator, :func:`unique`.
Ethan Furmanc72e6382014-02-06 08:13:14 -080029
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 Furman65a5a472016-09-01 23:55:19 -070040.. class:: IntFlag
41
42 Base class for creating enumerated constants that can be combined using
43 the bitwise operators without losing their :class:`IntFlag` membership.
44 :class:`IntFlag` members are also subclasses of :class:`int`.
45
46.. class:: Flag
47
48 Base class for creating enumerated constants that can be combined using
49 the bitwise operations without losing their :class:`Flag` membership.
50
Ethan Furmanc72e6382014-02-06 08:13:14 -080051.. function:: unique
52
53 Enum class decorator that ensures only one name is bound to any one value.
Ethan Furmanf24bb352013-07-18 17:05:39 -070054
Ethan Furman65a5a472016-09-01 23:55:19 -070055.. versionadded:: 3.6 ``Flag``, ``IntFlag``
56
Ethan Furman6b3d64a2013-06-14 16:55:46 -070057
58Creating an Enum
59----------------
60
61Enumerations are created using the :keyword:`class` syntax, which makes them
62easy to read and write. An alternative creation method is described in
Ethan Furman332dbc72016-08-20 00:00:52 -070063`Functional API`_. To define an enumeration, subclass :class:`Enum` as
64follows::
Ethan Furman6b3d64a2013-06-14 16:55:46 -070065
Ethan Furman332dbc72016-08-20 00:00:52 -070066 >>> from enum import Enum
67 >>> class Color(Enum):
68 ... red = 1
69 ... green = 2
70 ... blue = 3
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070071 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -070072
Ethan Furman455bfde2013-09-08 23:48:34 -070073.. note:: Nomenclature
74
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070075 - The class :class:`Color` is an *enumeration* (or *enum*)
76 - The attributes :attr:`Color.red`, :attr:`Color.green`, etc., are
77 *enumeration members* (or *enum members*).
78 - The enum members have *names* and *values* (the name of
79 :attr:`Color.red` is ``red``, the value of :attr:`Color.blue` is
80 ``3``, etc.)
Ethan Furman6b3d64a2013-06-14 16:55:46 -070081
Ethan Furman9a1daf52013-09-27 22:58:06 -070082.. note::
83
84 Even though we use the :keyword:`class` syntax to create Enums, Enums
85 are not normal Python classes. See `How are Enums different?`_ for
86 more details.
87
Ethan Furman6b3d64a2013-06-14 16:55:46 -070088Enumeration members have human readable string representations::
89
90 >>> print(Color.red)
91 Color.red
92
93...while their ``repr`` has more information::
94
95 >>> print(repr(Color.red))
96 <Color.red: 1>
97
98The *type* of an enumeration member is the enumeration it belongs to::
99
100 >>> type(Color.red)
101 <enum 'Color'>
102 >>> isinstance(Color.green, Color)
103 True
104 >>>
105
106Enum members also have a property that contains just their item name::
107
108 >>> print(Color.red.name)
109 red
110
111Enumerations support iteration, in definition order::
112
113 >>> class Shake(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700114 ... vanilla = 7
115 ... chocolate = 4
116 ... cookies = 9
117 ... mint = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700118 ...
119 >>> for shake in Shake:
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700120 ... print(shake)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700121 ...
122 Shake.vanilla
123 Shake.chocolate
124 Shake.cookies
125 Shake.mint
126
127Enumeration members are hashable, so they can be used in dictionaries and sets::
128
129 >>> apples = {}
130 >>> apples[Color.red] = 'red delicious'
131 >>> apples[Color.green] = 'granny smith'
132 >>> apples == {Color.red: 'red delicious', Color.green: 'granny smith'}
133 True
134
135
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700136Programmatic access to enumeration members and their attributes
137---------------------------------------------------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700138
139Sometimes it's useful to access members in enumerations programmatically (i.e.
140situations where ``Color.red`` won't do because the exact color is not known
141at program-writing time). ``Enum`` allows such access::
142
143 >>> Color(1)
144 <Color.red: 1>
145 >>> Color(3)
146 <Color.blue: 3>
147
148If you want to access enum members by *name*, use item access::
149
150 >>> Color['red']
151 <Color.red: 1>
152 >>> Color['green']
153 <Color.green: 2>
154
Larry Hastings3732ed22014-03-15 21:13:56 -0700155If you have an enum member and need its :attr:`name` or :attr:`value`::
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700156
157 >>> member = Color.red
158 >>> member.name
159 'red'
160 >>> member.value
161 1
162
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700163
164Duplicating enum members and values
165-----------------------------------
166
167Having two enum members with the same name is invalid::
168
169 >>> class Shape(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700170 ... square = 2
171 ... square = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700172 ...
173 Traceback (most recent call last):
174 ...
175 TypeError: Attempted to reuse key: 'square'
176
177However, two enum members are allowed to have the same value. Given two members
178A and B with the same value (and A defined first), B is an alias to A. By-value
179lookup of the value of A and B will return A. By-name lookup of B will also
180return A::
181
182 >>> class Shape(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700183 ... square = 2
184 ... diamond = 1
185 ... circle = 3
186 ... alias_for_square = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700187 ...
188 >>> Shape.square
189 <Shape.square: 2>
190 >>> Shape.alias_for_square
191 <Shape.square: 2>
192 >>> Shape(2)
193 <Shape.square: 2>
194
Ethan Furman101e0742013-09-15 12:34:36 -0700195.. note::
196
197 Attempting to create a member with the same name as an already
198 defined attribute (another member, a method, etc.) or attempting to create
199 an attribute with the same name as a member is not allowed.
200
Ethan Furmanf24bb352013-07-18 17:05:39 -0700201
202Ensuring unique enumeration values
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700203----------------------------------
Ethan Furmanf24bb352013-07-18 17:05:39 -0700204
205By default, enumerations allow multiple names as aliases for the same value.
206When this behavior isn't desired, the following decorator can be used to
207ensure each value is used only once in the enumeration:
208
209.. decorator:: unique
210
211A :keyword:`class` decorator specifically for enumerations. It searches an
212enumeration's :attr:`__members__` gathering any aliases it finds; if any are
213found :exc:`ValueError` is raised with the details::
214
215 >>> from enum import Enum, unique
216 >>> @unique
217 ... class Mistake(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700218 ... one = 1
219 ... two = 2
220 ... three = 3
221 ... four = 3
222 ...
Ethan Furmanf24bb352013-07-18 17:05:39 -0700223 Traceback (most recent call last):
224 ...
225 ValueError: duplicate values found in <enum 'Mistake'>: four -> three
226
227
228Iteration
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700229---------
Ethan Furmanf24bb352013-07-18 17:05:39 -0700230
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700231Iterating over the members of an enum does not provide the aliases::
232
233 >>> list(Shape)
234 [<Shape.square: 2>, <Shape.diamond: 1>, <Shape.circle: 3>]
235
236The special attribute ``__members__`` is an ordered dictionary mapping names
237to members. It includes all names defined in the enumeration, including the
238aliases::
239
240 >>> for name, member in Shape.__members__.items():
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700241 ... name, member
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700242 ...
243 ('square', <Shape.square: 2>)
244 ('diamond', <Shape.diamond: 1>)
245 ('circle', <Shape.circle: 3>)
246 ('alias_for_square', <Shape.square: 2>)
247
248The ``__members__`` attribute can be used for detailed programmatic access to
249the enumeration members. For example, finding all the aliases::
250
Ethan Furman332dbc72016-08-20 00:00:52 -0700251 >>> [name for name, member in Shape.__members__.items() if member.name != name]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700252 ['alias_for_square']
253
Ethan Furmanf24bb352013-07-18 17:05:39 -0700254
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700255Comparisons
256-----------
257
258Enumeration members are compared by identity::
259
260 >>> Color.red is Color.red
261 True
262 >>> Color.red is Color.blue
263 False
264 >>> Color.red is not Color.blue
265 True
266
267Ordered comparisons between enumeration values are *not* supported. Enum
268members are not integers (but see `IntEnum`_ below)::
269
270 >>> Color.red < Color.blue
271 Traceback (most recent call last):
272 File "<stdin>", line 1, in <module>
Ethan Furmane8e61272016-08-20 07:19:31 -0700273 TypeError: '<' not supported between instances of 'Color' and 'Color'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700274
275Equality comparisons are defined though::
276
277 >>> Color.blue == Color.red
278 False
279 >>> Color.blue != Color.red
280 True
281 >>> Color.blue == Color.blue
282 True
283
284Comparisons against non-enumeration values will always compare not equal
Ezio Melotti93d7dda2013-10-05 04:13:18 +0300285(again, :class:`IntEnum` was explicitly designed to behave differently, see
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700286below)::
287
288 >>> Color.blue == 2
289 False
290
291
292Allowed members and attributes of enumerations
293----------------------------------------------
294
295The examples above use integers for enumeration values. Using integers is
Ethan Furman332dbc72016-08-20 00:00:52 -0700296short and handy (and provided by default by the `Functional API`_), but not
297strictly enforced. In the vast majority of use-cases, one doesn't care what
298the actual value of an enumeration is. But if the value *is* important,
299enumerations can have arbitrary values.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700300
301Enumerations are Python classes, and can have methods and special methods as
302usual. If we have this enumeration::
303
304 >>> class Mood(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700305 ... funky = 1
306 ... happy = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700307 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700308 ... def describe(self):
309 ... # self is the member here
310 ... return self.name, self.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700311 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700312 ... def __str__(self):
313 ... return 'my custom str! {0}'.format(self.value)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700314 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700315 ... @classmethod
316 ... def favorite_mood(cls):
317 ... # cls here is the enumeration
318 ... return cls.happy
319 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700320
321Then::
322
323 >>> Mood.favorite_mood()
324 <Mood.happy: 3>
325 >>> Mood.happy.describe()
326 ('happy', 3)
327 >>> str(Mood.funky)
328 'my custom str! 1'
329
Martin Pantera90a4a92016-05-30 04:04:50 +0000330The rules for what is allowed are as follows: names that start and end with
331a single underscore are reserved by enum and cannot be used; all other
Ethan Furman8be6fac2014-11-01 07:40:22 -0700332attributes defined within an enumeration will become members of this
333enumeration, with the exception of special methods (:meth:`__str__`,
334:meth:`__add__`, etc.) and descriptors (methods are also descriptors).
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700335
336Note: if your enumeration defines :meth:`__new__` and/or :meth:`__init__` then
337whatever value(s) were given to the enum member will be passed into those
338methods. See `Planet`_ for an example.
339
340
341Restricted subclassing of enumerations
342--------------------------------------
343
344Subclassing an enumeration is allowed only if the enumeration does not define
345any members. So this is forbidden::
346
347 >>> class MoreColor(Color):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700348 ... pink = 17
349 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700350 Traceback (most recent call last):
351 ...
352 TypeError: Cannot extend enumerations
353
354But this is allowed::
355
356 >>> class Foo(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700357 ... def some_behavior(self):
358 ... pass
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700359 ...
360 >>> class Bar(Foo):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700361 ... happy = 1
362 ... sad = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700363 ...
364
365Allowing subclassing of enums that define members would lead to a violation of
366some important invariants of types and instances. On the other hand, it makes
367sense to allow sharing some common behavior between a group of enumerations.
368(See `OrderedEnum`_ for an example.)
369
370
371Pickling
372--------
373
374Enumerations can be pickled and unpickled::
375
376 >>> from test.test_enum import Fruit
377 >>> from pickle import dumps, loads
378 >>> Fruit.tomato is loads(dumps(Fruit.tomato))
379 True
380
381The usual restrictions for pickling apply: picklable enums must be defined in
382the top level of a module, since unpickling requires them to be importable
383from that module.
384
Ethan Furmanca1b7942014-02-08 11:36:27 -0800385.. note::
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700386
Ethan Furmanca1b7942014-02-08 11:36:27 -0800387 With pickle protocol version 4 it is possible to easily pickle enums
388 nested in other classes.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700389
Ethan Furman2da95042014-03-03 12:42:52 -0800390It is possible to modify how Enum members are pickled/unpickled by defining
391:meth:`__reduce_ex__` in the enumeration class.
392
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700393
394Functional API
395--------------
396
397The :class:`Enum` class is callable, providing the following functional API::
398
399 >>> Animal = Enum('Animal', 'ant bee cat dog')
400 >>> Animal
401 <enum 'Animal'>
402 >>> Animal.ant
403 <Animal.ant: 1>
404 >>> Animal.ant.value
405 1
406 >>> list(Animal)
407 [<Animal.ant: 1>, <Animal.bee: 2>, <Animal.cat: 3>, <Animal.dog: 4>]
408
Ethan Furman332dbc72016-08-20 00:00:52 -0700409The semantics of this API resemble :class:`~collections.namedtuple`. The first
410argument of the call to :class:`Enum` is the name of the enumeration.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700411
Ethan Furman332dbc72016-08-20 00:00:52 -0700412The second argument is the *source* of enumeration member names. It can be a
413whitespace-separated string of names, a sequence of names, a sequence of
4142-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to
415values. The last two options enable assigning arbitrary values to
416enumerations; the others auto-assign increasing integers starting with 1 (use
417the ``start`` parameter to specify a different starting value). A
418new class derived from :class:`Enum` is returned. In other words, the above
419assignment to :class:`Animal` is equivalent to::
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700420
Ethan Furman8a123292015-01-14 22:31:50 -0800421 >>> class Animal(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700422 ... ant = 1
423 ... bee = 2
424 ... cat = 3
425 ... dog = 4
426 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700427
Ethan Furmane2563462013-06-28 19:37:17 -0700428The reason for defaulting to ``1`` as the starting number and not ``0`` is
429that ``0`` is ``False`` in a boolean sense, but enum members all evaluate
430to ``True``.
431
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700432Pickling enums created with the functional API can be tricky as frame stack
433implementation details are used to try and figure out which module the
434enumeration is being created in (e.g. it will fail if you use a utility
Ethan Furman332dbc72016-08-20 00:00:52 -0700435function in separate module, and also may not work on IronPython or Jython).
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700436The solution is to specify the module name explicitly as follows::
437
Ethan Furman8a123292015-01-14 22:31:50 -0800438 >>> Animal = Enum('Animal', 'ant bee cat dog', module=__name__)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700439
Ethan Furman2da95042014-03-03 12:42:52 -0800440.. warning::
441
Ethan Furman01cc2d52014-03-03 15:02:04 -0800442 If ``module`` is not supplied, and Enum cannot determine what it is,
Ethan Furman2da95042014-03-03 12:42:52 -0800443 the new Enum members will not be unpicklable; to keep errors closer to
444 the source, pickling will be disabled.
445
Ethan Furmanca1b7942014-02-08 11:36:27 -0800446The new pickle protocol 4 also, in some circumstances, relies on
Martin Panterbae5d812016-06-18 03:57:31 +0000447:attr:`~definition.__qualname__` being set to the location where pickle will be able
Ethan Furmanca1b7942014-02-08 11:36:27 -0800448to find the class. For example, if the class was made available in class
449SomeData in the global scope::
450
Ethan Furman8a123292015-01-14 22:31:50 -0800451 >>> Animal = Enum('Animal', 'ant bee cat dog', qualname='SomeData.Animal')
Ethan Furmanca1b7942014-02-08 11:36:27 -0800452
Ethan Furman2da95042014-03-03 12:42:52 -0800453The complete signature is::
454
Ethan Furman332dbc72016-08-20 00:00:52 -0700455 Enum(value='NewEnumName', names=<...>, *, module='...', qualname='...', type=<mixed-in class>, start=1)
Ethan Furman2da95042014-03-03 12:42:52 -0800456
Ethan Furman01cc2d52014-03-03 15:02:04 -0800457:value: What the new Enum class will record as its name.
Ethan Furman2da95042014-03-03 12:42:52 -0800458
Zachary Waredbd1c432014-03-20 10:01:48 -0500459:names: The Enum members. This can be a whitespace or comma separated string
Ethan Furmand9925a12014-09-16 20:35:55 -0700460 (values will start at 1 unless otherwise specified)::
Ethan Furman2da95042014-03-03 12:42:52 -0800461
Ethan Furman01cc2d52014-03-03 15:02:04 -0800462 'red green blue' | 'red,green,blue' | 'red, green, blue'
Ethan Furman2da95042014-03-03 12:42:52 -0800463
Ethan Furman8a123292015-01-14 22:31:50 -0800464 or an iterator of names::
465
466 ['red', 'green', 'blue']
467
Ethan Furman01cc2d52014-03-03 15:02:04 -0800468 or an iterator of (name, value) pairs::
Ethan Furman2da95042014-03-03 12:42:52 -0800469
470 [('cyan', 4), ('magenta', 5), ('yellow', 6)]
471
Ethan Furman01cc2d52014-03-03 15:02:04 -0800472 or a mapping::
Ethan Furman2da95042014-03-03 12:42:52 -0800473
Zachary Waredbd1c432014-03-20 10:01:48 -0500474 {'chartreuse': 7, 'sea_green': 11, 'rosemary': 42}
Ethan Furman2da95042014-03-03 12:42:52 -0800475
Ethan Furman01cc2d52014-03-03 15:02:04 -0800476:module: name of module where new Enum class can be found.
Ethan Furman2da95042014-03-03 12:42:52 -0800477
Ethan Furman01cc2d52014-03-03 15:02:04 -0800478:qualname: where in module new Enum class can be found.
Ethan Furman2da95042014-03-03 12:42:52 -0800479
Ethan Furman01cc2d52014-03-03 15:02:04 -0800480:type: type to mix in to new Enum class.
Ethan Furman2da95042014-03-03 12:42:52 -0800481
Yury Selivanov4dde5872015-09-11 00:48:21 -0400482:start: number to start counting at if only names are passed in.
Ethan Furmand9925a12014-09-16 20:35:55 -0700483
Berker Peksag60efd792014-09-18 05:23:14 +0300484.. versionchanged:: 3.5
485 The *start* parameter was added.
486
Ethan Furmanca1b7942014-02-08 11:36:27 -0800487
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700488Derived Enumerations
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700489--------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700490
491IntEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700492^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700493
Ethan Furman65a5a472016-09-01 23:55:19 -0700494The first variation of :class:`Enum` that is provided is also a subclass of
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700495:class:`int`. Members of an :class:`IntEnum` can be compared to integers;
496by extension, integer enumerations of different types can also be compared
497to each other::
498
499 >>> from enum import IntEnum
500 >>> class Shape(IntEnum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700501 ... circle = 1
502 ... square = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700503 ...
504 >>> class Request(IntEnum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700505 ... post = 1
506 ... get = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700507 ...
508 >>> Shape == 1
509 False
510 >>> Shape.circle == 1
511 True
512 >>> Shape.circle == Request.post
513 True
514
515However, they still can't be compared to standard :class:`Enum` enumerations::
516
517 >>> class Shape(IntEnum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700518 ... circle = 1
519 ... square = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700520 ...
521 >>> class Color(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700522 ... red = 1
523 ... green = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700524 ...
525 >>> Shape.circle == Color.red
526 False
527
528:class:`IntEnum` values behave like integers in other ways you'd expect::
529
530 >>> int(Shape.circle)
531 1
532 >>> ['a', 'b', 'c'][Shape.circle]
533 'b'
534 >>> [i for i in range(Shape.square)]
535 [0, 1]
536
Ethan Furman65a5a472016-09-01 23:55:19 -0700537
538IntFlag
539^^^^^^^
540
541The next variation of :class:`Enum` provided, :class:`IntFlag`, is also based
542on :class:`int`. The difference being :class:`IntFlag` members can be combined
543using the bitwise operators (&, \|, ^, ~) and the result is still an
544:class:`IntFlag` member. However, as the name implies, :class:`IntFlag`
545members also subclass :class:`int` and can be used wherever an :class:`int` is.
546Any operation on an :class:`IntFlag` member besides the bit-wise operations
547will lose the :class:`IntFlag` membership.
548
Ethan Furman25d94bb2016-09-02 16:32:32 -0700549.. versionadded:: 3.6
550
551Sample :class:`IntFlag` class::
552
Ethan Furman65a5a472016-09-01 23:55:19 -0700553 >>> from enum import IntFlag
554 >>> class Perm(IntFlag):
555 ... R = 4
556 ... W = 2
557 ... X = 1
558 ...
559 >>> Perm.R | Perm.W
560 <Perm.R|W: 6>
561 >>> Perm.R + Perm.W
562 6
563 >>> RW = Perm.R | Perm.W
564 >>> Perm.R in RW
565 True
566
Ethan Furman25d94bb2016-09-02 16:32:32 -0700567It is also possible to name the combinations::
568
569 >>> class Perm(IntFlag):
570 ... R = 4
571 ... W = 2
572 ... X = 1
573 ... RWX = 7
574 >>> Perm.RWX
575 <Perm.RWX: 7>
576 >>> ~Perm.RWX
Ethan Furman27682d22016-09-04 11:39:01 -0700577 <Perm.-8: -8>
Ethan Furman25d94bb2016-09-02 16:32:32 -0700578
579Another important difference between :class:`IntFlag` and :class:`Enum` is that
580if no flags are set (the value is 0), its boolean evaluation is :data:`False`::
581
582 >>> Perm.R & Perm.X
583 <Perm.0: 0>
584 >>> bool(Perm.R & Perm.X)
585 False
586
587Because :class:`IntFlag` members are also subclasses of :class:`int` they can
588be combined with them::
589
590 >>> Perm.X | 8
591 <Perm.8|X: 9>
Ethan Furman65a5a472016-09-01 23:55:19 -0700592
593
594Flag
595^^^^
596
597The last variation is :class:`Flag`. Like :class:`IntFlag`, :class:`Flag`
Ethan Furman25d94bb2016-09-02 16:32:32 -0700598members can be combined using the bitwise operators (&, \|, ^, ~). Unlike
Ethan Furman65a5a472016-09-01 23:55:19 -0700599:class:`IntFlag`, they cannot be combined with, nor compared against, any
Ethan Furman25d94bb2016-09-02 16:32:32 -0700600other :class:`Flag` enumeration, nor :class:`int`.
Ethan Furman65a5a472016-09-01 23:55:19 -0700601
602.. versionadded:: 3.6
603
Ethan Furman25d94bb2016-09-02 16:32:32 -0700604Like :class:`IntFlag`, if a combination of :class:`Flag` members results in no
605flags being set, the boolean evaluation is :data:`False`::
606
607 >>> from enum import Flag
608 >>> class Color(Flag):
609 ... red = 1
610 ... blue = 2
611 ... green = 4
612 ...
613 >>> Color.red & Color.green
614 <Color.0: 0>
615 >>> bool(Color.red & Color.green)
616 False
617
Ethan Furman27682d22016-09-04 11:39:01 -0700618Individual flags should have values that are powers of two (1, 2, 4, 8, ...),
619while combinations of flags won't::
620
621 >>> class Color(Flag):
622 ... red = 1
623 ... blue = 2
624 ... green = 4
625 ... white = 7
626 ... # or
627 ... # white = red | blue | green
628
Ethan Furman25d94bb2016-09-02 16:32:32 -0700629Giving a name to the "no flags set" condition does not change its boolean
630value::
631
632 >>> class Color(Flag):
633 ... black = 0
634 ... red = 1
635 ... blue = 2
636 ... green = 4
637 ...
638 >>> Color.black
639 <Color.black: 0>
640 >>> bool(Color.black)
641 False
642
Ethan Furman65a5a472016-09-01 23:55:19 -0700643.. note::
644
645 For the majority of new code, :class:`Enum` and :class:`Flag` are strongly
646 recommended, since :class:`IntEnum` and :class:`IntFlag` break some
647 semantic promises of an enumeration (by being comparable to integers, and
648 thus by transitivity to other unrelated enumerations). :class:`IntEnum`
649 and :class:`IntFlag` should be used only in cases where :class:`Enum` and
650 :class:`Flag` will not do; for example, when integer constants are replaced
651 with enumerations, or for interoperability with other systems.
Ethan Furman332dbc72016-08-20 00:00:52 -0700652
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700653
654Others
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700655^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700656
657While :class:`IntEnum` is part of the :mod:`enum` module, it would be very
658simple to implement independently::
659
660 class IntEnum(int, Enum):
661 pass
662
663This demonstrates how similar derived enumerations can be defined; for example
Ethan Furman332dbc72016-08-20 00:00:52 -0700664a :class:`StrEnum` that mixes in :class:`str` instead of :class:`int`.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700665
666Some rules:
667
6681. When subclassing :class:`Enum`, mix-in types must appear before
669 :class:`Enum` itself in the sequence of bases, as in the :class:`IntEnum`
670 example above.
6712. While :class:`Enum` can have members of any type, once you mix in an
672 additional type, all the members must have values of that type, e.g.
673 :class:`int` above. This restriction does not apply to mix-ins which only
674 add methods and don't specify another data type such as :class:`int` or
675 :class:`str`.
6763. When another data type is mixed in, the :attr:`value` attribute is *not the
Zachary Waredbd1c432014-03-20 10:01:48 -0500677 same* as the enum member itself, although it is equivalent and will compare
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700678 equal.
Martin Panterd5db1472016-02-08 01:34:09 +00006794. %-style formatting: `%s` and `%r` call the :class:`Enum` class's
680 :meth:`__str__` and :meth:`__repr__` respectively; other codes (such as
681 `%i` or `%h` for IntEnum) treat the enum member as its mixed-in type.
Martin Panterbc1ee462016-02-13 00:41:37 +00006825. :ref:`Formatted string literals <f-strings>`, :meth:`str.format`,
683 and :func:`format` will use the mixed-in
Martin Panterd5db1472016-02-08 01:34:09 +0000684 type's :meth:`__format__`. If the :class:`Enum` class's :func:`str` or
685 :func:`repr` is desired, use the `!s` or `!r` format codes.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700686
687
688Interesting examples
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700689--------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700690
Ethan Furman65a5a472016-09-01 23:55:19 -0700691While :class:`Enum`, :class:`IntEnum`, :class:`IntFlag`, and :class:`Flag` are
692expected to cover the majority of use-cases, they cannot cover them all. Here
693are recipes for some different types of enumerations that can be used directly,
694or as examples for creating one's own.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700695
696
Ethan Furman6a137e82016-09-07 08:17:15 -0700697Omitting values
698^^^^^^^^^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700699
Ethan Furman6a137e82016-09-07 08:17:15 -0700700In many use-cases one doesn't care what the actual value of an enumeration
701is. There are several ways to define this type of simple enumeration:
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700702
Ethan Furman6a137e82016-09-07 08:17:15 -0700703- use instances of :class:`object` as the value
704- use a descriptive string as the value
705- use a tuple as the value and a custom :meth:`__new__` to replace the
706 tuple with an :class:`int` value
707
708Using any of these methods signifies to the user that these values are not
709important, and also enables one to add, remove, or reorder members without
710having to renumber the remaining members.
711
712Whichever method you choose, you should provide a :meth:`repr` that also hides
713the (unimportant) value::
714
715 >>> class NoValue(Enum):
716 ... def __repr__(self):
717 ... return '<%s.%s>' % (self.__class__.__name__, self.name)
718 ...
719
720
721Using :class:`object`
722"""""""""""""""""""""
723
724Using :class:`object` would look like::
725
726 >>> class Color(NoValue):
727 ... red = object()
728 ... green = object()
729 ... blue = object()
730 ...
731 >>> Color.green
732 <Color.green>
733
734
735Using a descriptive string
736""""""""""""""""""""""""""
737
738Using a string as the value would look like::
739
740 >>> class Color(NoValue):
741 ... red = 'stop'
742 ... green = 'go'
743 ... blue = 'too fast!'
744 ...
745 >>> Color.green
746 <Color.green>
747 >>> Color.green.value
748 'go'
749
750
751Using a custom :meth:`__new__`
752""""""""""""""""""""""""""""""
753
754Using an auto-numbering :meth:`__new__` would look like::
755
756 >>> class AutoNumber(NoValue):
Ethan Furman332dbc72016-08-20 00:00:52 -0700757 ... def __new__(cls):
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700758 ... value = len(cls.__members__) + 1
759 ... obj = object.__new__(cls)
Ethan Furman90262622013-07-30 12:24:25 -0700760 ... obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700761 ... return obj
762 ...
Ethan Furman332dbc72016-08-20 00:00:52 -0700763 >>> class Color(AutoNumber):
764 ... red = ()
765 ... green = ()
766 ... blue = ()
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700767 ...
Ethan Furman6a137e82016-09-07 08:17:15 -0700768 >>> Color.green
769 <Color.green>
770 >>> Color.green.value
771 2
772
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700773
Ethan Furman9a1daf52013-09-27 22:58:06 -0700774.. note::
775
776 The :meth:`__new__` method, if defined, is used during creation of the Enum
777 members; it is then replaced by Enum's :meth:`__new__` which is used after
Ethan Furmanf75805e2014-09-16 19:13:31 -0700778 class creation for lookup of existing members.
Ethan Furman9a1daf52013-09-27 22:58:06 -0700779
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700780
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700781OrderedEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700782^^^^^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700783
784An ordered enumeration that is not based on :class:`IntEnum` and so maintains
785the normal :class:`Enum` invariants (such as not being comparable to other
786enumerations)::
787
788 >>> class OrderedEnum(Enum):
789 ... def __ge__(self, other):
790 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700791 ... return self.value >= other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700792 ... return NotImplemented
793 ... def __gt__(self, other):
794 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700795 ... return self.value > other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700796 ... return NotImplemented
797 ... def __le__(self, other):
798 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700799 ... return self.value <= other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700800 ... return NotImplemented
801 ... def __lt__(self, other):
802 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700803 ... return self.value < other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700804 ... return NotImplemented
805 ...
806 >>> class Grade(OrderedEnum):
807 ... A = 5
808 ... B = 4
809 ... C = 3
810 ... D = 2
811 ... F = 1
812 ...
813 >>> Grade.C < Grade.A
814 True
815
816
Ethan Furmanf24bb352013-07-18 17:05:39 -0700817DuplicateFreeEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700818^^^^^^^^^^^^^^^^^
Ethan Furmanf24bb352013-07-18 17:05:39 -0700819
820Raises an error if a duplicate member name is found instead of creating an
821alias::
822
823 >>> class DuplicateFreeEnum(Enum):
824 ... def __init__(self, *args):
825 ... cls = self.__class__
826 ... if any(self.value == e.value for e in cls):
827 ... a = self.name
828 ... e = cls(self.value).name
829 ... raise ValueError(
830 ... "aliases not allowed in DuplicateFreeEnum: %r --> %r"
831 ... % (a, e))
832 ...
833 >>> class Color(DuplicateFreeEnum):
834 ... red = 1
835 ... green = 2
836 ... blue = 3
837 ... grene = 2
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700838 ...
Ethan Furmanf24bb352013-07-18 17:05:39 -0700839 Traceback (most recent call last):
840 ...
841 ValueError: aliases not allowed in DuplicateFreeEnum: 'grene' --> 'green'
842
843.. note::
844
845 This is a useful example for subclassing Enum to add or change other
Ezio Melotti93d7dda2013-10-05 04:13:18 +0300846 behaviors as well as disallowing aliases. If the only desired change is
Ezio Melotti17f1edd2013-10-05 04:26:06 +0300847 disallowing aliases, the :func:`unique` decorator can be used instead.
Ethan Furmanf24bb352013-07-18 17:05:39 -0700848
849
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700850Planet
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700851^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700852
853If :meth:`__new__` or :meth:`__init__` is defined the value of the enum member
854will be passed to those methods::
855
856 >>> class Planet(Enum):
857 ... MERCURY = (3.303e+23, 2.4397e6)
858 ... VENUS = (4.869e+24, 6.0518e6)
859 ... EARTH = (5.976e+24, 6.37814e6)
860 ... MARS = (6.421e+23, 3.3972e6)
861 ... JUPITER = (1.9e+27, 7.1492e7)
862 ... SATURN = (5.688e+26, 6.0268e7)
863 ... URANUS = (8.686e+25, 2.5559e7)
864 ... NEPTUNE = (1.024e+26, 2.4746e7)
865 ... def __init__(self, mass, radius):
866 ... self.mass = mass # in kilograms
867 ... self.radius = radius # in meters
868 ... @property
869 ... def surface_gravity(self):
870 ... # universal gravitational constant (m3 kg-1 s-2)
871 ... G = 6.67300E-11
872 ... return G * self.mass / (self.radius * self.radius)
873 ...
874 >>> Planet.EARTH.value
875 (5.976e+24, 6378140.0)
876 >>> Planet.EARTH.surface_gravity
877 9.802652743337129
Ethan Furman9a1daf52013-09-27 22:58:06 -0700878
879
880How are Enums different?
881------------------------
882
883Enums have a custom metaclass that affects many aspects of both derived Enum
884classes and their instances (members).
885
886
887Enum Classes
888^^^^^^^^^^^^
889
890The :class:`EnumMeta` metaclass is responsible for providing the
891:meth:`__contains__`, :meth:`__dir__`, :meth:`__iter__` and other methods that
892allow one to do things with an :class:`Enum` class that fail on a typical
893class, such as `list(Color)` or `some_var in Color`. :class:`EnumMeta` is
894responsible for ensuring that various other methods on the final :class:`Enum`
895class are correct (such as :meth:`__new__`, :meth:`__getnewargs__`,
Martin Panterd21e0b52015-10-10 10:36:22 +0000896:meth:`__str__` and :meth:`__repr__`).
Ethan Furman9a1daf52013-09-27 22:58:06 -0700897
898
899Enum Members (aka instances)
900^^^^^^^^^^^^^^^^^^^^^^^^^^^^
901
902The most interesting thing about Enum members is that they are singletons.
903:class:`EnumMeta` creates them all while it is creating the :class:`Enum`
904class itself, and then puts a custom :meth:`__new__` in place to ensure
905that no new ones are ever instantiated by returning only the existing
906member instances.
907
908
909Finer Points
910^^^^^^^^^^^^
911
Ethan Furman65a5a472016-09-01 23:55:19 -0700912Supported ``__dunder__`` names
Ethan Furman6a137e82016-09-07 08:17:15 -0700913""""""""""""""""""""""""""""""
Ethan Furman9a1daf52013-09-27 22:58:06 -0700914
Ethan Furman65a5a472016-09-01 23:55:19 -0700915:attr:`__members__` is an :class:`OrderedDict` of ``member_name``:``member``
916items. It is only available on the class.
Ethan Furman9a1daf52013-09-27 22:58:06 -0700917
Ethan Furman65a5a472016-09-01 23:55:19 -0700918:meth:`__new__`, if specified, must create and return the enum members; it is
919also a very good idea to set the member's :attr:`_value_` appropriately. Once
920all the members are created it is no longer used.
Ethan Furman748dad52015-11-20 13:12:26 -0800921
Ethan Furman60255b62016-01-15 15:01:33 -0800922
Ethan Furman65a5a472016-09-01 23:55:19 -0700923Supported ``_sunder_`` names
Ethan Furman6a137e82016-09-07 08:17:15 -0700924""""""""""""""""""""""""""""
Ethan Furman60255b62016-01-15 15:01:33 -0800925
Ethan Furman65a5a472016-09-01 23:55:19 -0700926- ``_name_`` -- name of the member
927- ``_value_`` -- value of the member; can be set / modified in ``__new__``
Ethan Furman9a1daf52013-09-27 22:58:06 -0700928
Ethan Furman65a5a472016-09-01 23:55:19 -0700929- ``_missing_`` -- a lookup function used when a value is not found; may be
930 overridden
931- ``_order_`` -- used in Python 2/3 code to ensure member order is consistent
932 (class attribute, removed during class creation)
Ethan Furman9a1daf52013-09-27 22:58:06 -0700933
Ethan Furman65a5a472016-09-01 23:55:19 -0700934.. versionadded:: 3.6 ``_missing_``, ``_order_``
Ethan Furman332dbc72016-08-20 00:00:52 -0700935
Ethan Furman65a5a472016-09-01 23:55:19 -0700936To help keep Python 2 / Python 3 code in sync an :attr:`_order_` attribute can
937be provided. It will be checked against the actual order of the enumeration
938and raise an error if the two do not match::
Ethan Furmane8e61272016-08-20 07:19:31 -0700939
940 >>> class Color(Enum):
941 ... _order_ = 'red green blue'
942 ... red = 1
943 ... blue = 3
944 ... green = 2
945 ...
946 Traceback (most recent call last):
947 ...
948 TypeError: member order does not match _order_
949
950.. note::
951
952 In Python 2 code the :attr:`_order_` attribute is necessary as definition
Ethan Furman65a5a472016-09-01 23:55:19 -0700953 order is lost before it can be recorded.
954
955``Enum`` member type
Ethan Furman6a137e82016-09-07 08:17:15 -0700956""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -0700957
958:class:`Enum` members are instances of an :class:`Enum` class, and even
959though they are accessible as `EnumClass.member`, they should not be accessed
960directly from the member as that lookup may fail or, worse, return something
961besides the ``Enum`` member you looking for::
962
963 >>> class FieldTypes(Enum):
964 ... name = 0
965 ... value = 1
966 ... size = 2
967 ...
968 >>> FieldTypes.value.size
969 <FieldTypes.size: 2>
970 >>> FieldTypes.size.value
971 2
972
973.. versionchanged:: 3.5
974
975
976Boolean value of ``Enum`` classes and members
Ethan Furman6a137e82016-09-07 08:17:15 -0700977"""""""""""""""""""""""""""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -0700978
979``Enum`` members that are mixed with non-Enum types (such as
980:class:`int`, :class:`str`, etc.) are evaluated according to the mixed-in
981type's rules; otherwise, all members evaluate as :data:`True`. To make your own
982Enum's boolean evaluation depend on the member's value add the following to
983your class::
984
985 def __bool__(self):
986 return bool(self.value)
987
988``Enum`` classes always evaluate as :data:`True`.
989
990
991``Enum`` classes with methods
Ethan Furman6a137e82016-09-07 08:17:15 -0700992"""""""""""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -0700993
994If you give your :class:`Enum` subclass extra methods, like the `Planet`_
995class above, those methods will show up in a :func:`dir` of the member,
996but not of the class::
997
998 >>> dir(Planet)
999 ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__']
1000 >>> dir(Planet.EARTH)
1001 ['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value']
1002