blob: 4b4f5eb1944cc572c3399894b52486f9456d203f [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
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
Kartik Anand62658422017-03-01 01:37:19 +053027sets of names and values: :class:`Enum`, :class:`IntEnum`, :class:`Flag`, and
28:class:`IntFlag`. It also defines one decorator, :func:`unique`, and one
Ethan Furmanc16595e2016-09-10 23:36:59 -070029helper, :class:`auto`.
Ethan Furmanc72e6382014-02-06 08:13:14 -080030
31.. class:: Enum
32
33 Base class for creating enumerated constants. See section
Larry Hastingsad88d7a2014-02-10 04:26:10 -080034 `Functional API`_ for an alternate construction syntax.
Ethan Furmanc72e6382014-02-06 08:13:14 -080035
36.. class:: IntEnum
37
38 Base class for creating enumerated constants that are also
39 subclasses of :class:`int`.
40
Ethan Furman65a5a472016-09-01 23:55:19 -070041.. class:: IntFlag
42
43 Base class for creating enumerated constants that can be combined using
44 the bitwise operators without losing their :class:`IntFlag` membership.
45 :class:`IntFlag` members are also subclasses of :class:`int`.
46
47.. class:: Flag
48
49 Base class for creating enumerated constants that can be combined using
50 the bitwise operations without losing their :class:`Flag` membership.
51
Ethan Furmanc72e6382014-02-06 08:13:14 -080052.. function:: unique
53
54 Enum class decorator that ensures only one name is bound to any one value.
Ethan Furmanf24bb352013-07-18 17:05:39 -070055
Ethan Furmanc16595e2016-09-10 23:36:59 -070056.. class:: auto
57
YoSTEALTH24bcefc2020-01-06 16:04:43 -060058 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 -070059
60.. versionadded:: 3.6 ``Flag``, ``IntFlag``, ``auto``
Ethan Furman65a5a472016-09-01 23:55:19 -070061
Ethan Furman6b3d64a2013-06-14 16:55:46 -070062
63Creating an Enum
64----------------
65
66Enumerations are created using the :keyword:`class` syntax, which makes them
67easy to read and write. An alternative creation method is described in
Ethan Furman332dbc72016-08-20 00:00:52 -070068`Functional API`_. To define an enumeration, subclass :class:`Enum` as
69follows::
Ethan Furman6b3d64a2013-06-14 16:55:46 -070070
Ethan Furman332dbc72016-08-20 00:00:52 -070071 >>> from enum import Enum
72 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -080073 ... RED = 1
74 ... GREEN = 2
75 ... BLUE = 3
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070076 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -070077
Ethan Furmanc16595e2016-09-10 23:36:59 -070078.. note:: Enum member values
79
80 Member values can be anything: :class:`int`, :class:`str`, etc.. If
81 the exact value is unimportant you may use :class:`auto` instances and an
82 appropriate value will be chosen for you. Care must be taken if you mix
83 :class:`auto` with other values.
84
Ethan Furman455bfde2013-09-08 23:48:34 -070085.. note:: Nomenclature
86
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070087 - The class :class:`Color` is an *enumeration* (or *enum*)
Ethan Furman23bb6f42016-11-21 09:22:05 -080088 - The attributes :attr:`Color.RED`, :attr:`Color.GREEN`, etc., are
89 *enumeration members* (or *enum members*) and are functionally constants.
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070090 - The enum members have *names* and *values* (the name of
Ethan Furman23bb6f42016-11-21 09:22:05 -080091 :attr:`Color.RED` is ``RED``, the value of :attr:`Color.BLUE` is
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070092 ``3``, etc.)
Ethan Furman6b3d64a2013-06-14 16:55:46 -070093
Ethan Furman9a1daf52013-09-27 22:58:06 -070094.. note::
95
96 Even though we use the :keyword:`class` syntax to create Enums, Enums
97 are not normal Python classes. See `How are Enums different?`_ for
98 more details.
99
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700100Enumeration members have human readable string representations::
101
Ethan Furman23bb6f42016-11-21 09:22:05 -0800102 >>> print(Color.RED)
103 Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700104
105...while their ``repr`` has more information::
106
Ethan Furman23bb6f42016-11-21 09:22:05 -0800107 >>> print(repr(Color.RED))
108 <Color.RED: 1>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700109
110The *type* of an enumeration member is the enumeration it belongs to::
111
Ethan Furman23bb6f42016-11-21 09:22:05 -0800112 >>> type(Color.RED)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700113 <enum 'Color'>
Ethan Furman23bb6f42016-11-21 09:22:05 -0800114 >>> isinstance(Color.GREEN, Color)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700115 True
116 >>>
117
118Enum members also have a property that contains just their item name::
119
Ethan Furman23bb6f42016-11-21 09:22:05 -0800120 >>> print(Color.RED.name)
121 RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700122
123Enumerations support iteration, in definition order::
124
125 >>> class Shake(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800126 ... VANILLA = 7
127 ... CHOCOLATE = 4
128 ... COOKIES = 9
129 ... MINT = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700130 ...
131 >>> for shake in Shake:
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700132 ... print(shake)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700133 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800134 Shake.VANILLA
135 Shake.CHOCOLATE
136 Shake.COOKIES
137 Shake.MINT
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700138
139Enumeration members are hashable, so they can be used in dictionaries and sets::
140
141 >>> apples = {}
Ethan Furman23bb6f42016-11-21 09:22:05 -0800142 >>> apples[Color.RED] = 'red delicious'
143 >>> apples[Color.GREEN] = 'granny smith'
144 >>> apples == {Color.RED: 'red delicious', Color.GREEN: 'granny smith'}
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700145 True
146
147
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700148Programmatic access to enumeration members and their attributes
149---------------------------------------------------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700150
151Sometimes it's useful to access members in enumerations programmatically (i.e.
Ethan Furman23bb6f42016-11-21 09:22:05 -0800152situations where ``Color.RED`` won't do because the exact color is not known
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700153at program-writing time). ``Enum`` allows such access::
154
155 >>> Color(1)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800156 <Color.RED: 1>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700157 >>> Color(3)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800158 <Color.BLUE: 3>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700159
160If you want to access enum members by *name*, use item access::
161
Ethan Furman23bb6f42016-11-21 09:22:05 -0800162 >>> Color['RED']
163 <Color.RED: 1>
164 >>> Color['GREEN']
165 <Color.GREEN: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700166
Larry Hastings3732ed22014-03-15 21:13:56 -0700167If you have an enum member and need its :attr:`name` or :attr:`value`::
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700168
Ethan Furman23bb6f42016-11-21 09:22:05 -0800169 >>> member = Color.RED
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700170 >>> member.name
Ethan Furman23bb6f42016-11-21 09:22:05 -0800171 'RED'
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700172 >>> member.value
173 1
174
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700175
176Duplicating enum members and values
177-----------------------------------
178
179Having two enum members with the same name is invalid::
180
181 >>> class Shape(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800182 ... SQUARE = 2
183 ... SQUARE = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700184 ...
185 Traceback (most recent call last):
186 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800187 TypeError: Attempted to reuse key: 'SQUARE'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700188
189However, two enum members are allowed to have the same value. Given two members
190A and B with the same value (and A defined first), B is an alias to A. By-value
191lookup of the value of A and B will return A. By-name lookup of B will also
192return A::
193
194 >>> class Shape(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800195 ... SQUARE = 2
196 ... DIAMOND = 1
197 ... CIRCLE = 3
198 ... ALIAS_FOR_SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700199 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800200 >>> Shape.SQUARE
201 <Shape.SQUARE: 2>
202 >>> Shape.ALIAS_FOR_SQUARE
203 <Shape.SQUARE: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700204 >>> Shape(2)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800205 <Shape.SQUARE: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700206
Ethan Furman101e0742013-09-15 12:34:36 -0700207.. note::
208
209 Attempting to create a member with the same name as an already
210 defined attribute (another member, a method, etc.) or attempting to create
211 an attribute with the same name as a member is not allowed.
212
Ethan Furmanf24bb352013-07-18 17:05:39 -0700213
214Ensuring unique enumeration values
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700215----------------------------------
Ethan Furmanf24bb352013-07-18 17:05:39 -0700216
217By default, enumerations allow multiple names as aliases for the same value.
218When this behavior isn't desired, the following decorator can be used to
219ensure each value is used only once in the enumeration:
220
221.. decorator:: unique
222
223A :keyword:`class` decorator specifically for enumerations. It searches an
224enumeration's :attr:`__members__` gathering any aliases it finds; if any are
225found :exc:`ValueError` is raised with the details::
226
227 >>> from enum import Enum, unique
228 >>> @unique
229 ... class Mistake(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800230 ... ONE = 1
231 ... TWO = 2
232 ... THREE = 3
233 ... FOUR = 3
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700234 ...
Ethan Furmanf24bb352013-07-18 17:05:39 -0700235 Traceback (most recent call last):
236 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800237 ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
Ethan Furmanf24bb352013-07-18 17:05:39 -0700238
239
Ethan Furmanc16595e2016-09-10 23:36:59 -0700240Using automatic values
241----------------------
242
243If the exact value is unimportant you can use :class:`auto`::
244
245 >>> from enum import Enum, auto
246 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800247 ... RED = auto()
248 ... BLUE = auto()
249 ... GREEN = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700250 ...
251 >>> list(Color)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800252 [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
Ethan Furmanc16595e2016-09-10 23:36:59 -0700253
254The values are chosen by :func:`_generate_next_value_`, which can be
255overridden::
256
257 >>> class AutoName(Enum):
258 ... def _generate_next_value_(name, start, count, last_values):
259 ... return name
260 ...
261 >>> class Ordinal(AutoName):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800262 ... NORTH = auto()
263 ... SOUTH = auto()
264 ... EAST = auto()
265 ... WEST = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700266 ...
267 >>> list(Ordinal)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800268 [<Ordinal.NORTH: 'NORTH'>, <Ordinal.SOUTH: 'SOUTH'>, <Ordinal.EAST: 'EAST'>, <Ordinal.WEST: 'WEST'>]
Ethan Furmanc16595e2016-09-10 23:36:59 -0700269
270.. note::
271
272 The goal of the default :meth:`_generate_next_value_` methods is to provide
273 the next :class:`int` in sequence with the last :class:`int` provided, but
274 the way it does this is an implementation detail and may change.
275
Ethan Onstottd9a43e22020-04-28 13:20:55 -0400276.. note::
277
278 The :meth:`_generate_next_value_` method must be defined before any members.
279
Ethan Furmanf24bb352013-07-18 17:05:39 -0700280Iteration
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700281---------
Ethan Furmanf24bb352013-07-18 17:05:39 -0700282
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700283Iterating over the members of an enum does not provide the aliases::
284
285 >>> list(Shape)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800286 [<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700287
INADA Naokie57f91a2018-06-19 01:14:26 +0900288The special attribute ``__members__`` is a read-only ordered mapping of names
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700289to members. It includes all names defined in the enumeration, including the
290aliases::
291
292 >>> for name, member in Shape.__members__.items():
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700293 ... name, member
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700294 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800295 ('SQUARE', <Shape.SQUARE: 2>)
296 ('DIAMOND', <Shape.DIAMOND: 1>)
297 ('CIRCLE', <Shape.CIRCLE: 3>)
298 ('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700299
300The ``__members__`` attribute can be used for detailed programmatic access to
301the enumeration members. For example, finding all the aliases::
302
Ethan Furman332dbc72016-08-20 00:00:52 -0700303 >>> [name for name, member in Shape.__members__.items() if member.name != name]
Ethan Furman23bb6f42016-11-21 09:22:05 -0800304 ['ALIAS_FOR_SQUARE']
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700305
Ethan Furmanf24bb352013-07-18 17:05:39 -0700306
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700307Comparisons
308-----------
309
310Enumeration members are compared by identity::
311
Ethan Furman23bb6f42016-11-21 09:22:05 -0800312 >>> Color.RED is Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700313 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800314 >>> Color.RED is Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700315 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800316 >>> Color.RED is not Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700317 True
318
319Ordered comparisons between enumeration values are *not* supported. Enum
320members are not integers (but see `IntEnum`_ below)::
321
Ethan Furman23bb6f42016-11-21 09:22:05 -0800322 >>> Color.RED < Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700323 Traceback (most recent call last):
324 File "<stdin>", line 1, in <module>
Ethan Furmane8e61272016-08-20 07:19:31 -0700325 TypeError: '<' not supported between instances of 'Color' and 'Color'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700326
327Equality comparisons are defined though::
328
Ethan Furman23bb6f42016-11-21 09:22:05 -0800329 >>> Color.BLUE == Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700330 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800331 >>> Color.BLUE != Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700332 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800333 >>> Color.BLUE == Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700334 True
335
336Comparisons against non-enumeration values will always compare not equal
Ezio Melotti93d7dda2013-10-05 04:13:18 +0300337(again, :class:`IntEnum` was explicitly designed to behave differently, see
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700338below)::
339
Ethan Furman23bb6f42016-11-21 09:22:05 -0800340 >>> Color.BLUE == 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700341 False
342
343
344Allowed members and attributes of enumerations
345----------------------------------------------
346
347The examples above use integers for enumeration values. Using integers is
Ethan Furman332dbc72016-08-20 00:00:52 -0700348short and handy (and provided by default by the `Functional API`_), but not
349strictly enforced. In the vast majority of use-cases, one doesn't care what
350the actual value of an enumeration is. But if the value *is* important,
351enumerations can have arbitrary values.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700352
353Enumerations are Python classes, and can have methods and special methods as
354usual. If we have this enumeration::
355
356 >>> class Mood(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800357 ... FUNKY = 1
358 ... HAPPY = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700359 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700360 ... def describe(self):
361 ... # self is the member here
362 ... return self.name, self.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700363 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700364 ... def __str__(self):
365 ... return 'my custom str! {0}'.format(self.value)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700366 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700367 ... @classmethod
368 ... def favorite_mood(cls):
369 ... # cls here is the enumeration
Ethan Furman23bb6f42016-11-21 09:22:05 -0800370 ... return cls.HAPPY
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700371 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700372
373Then::
374
375 >>> Mood.favorite_mood()
Ethan Furman23bb6f42016-11-21 09:22:05 -0800376 <Mood.HAPPY: 3>
377 >>> Mood.HAPPY.describe()
378 ('HAPPY', 3)
379 >>> str(Mood.FUNKY)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700380 'my custom str! 1'
381
Martin Pantera90a4a92016-05-30 04:04:50 +0000382The rules for what is allowed are as follows: names that start and end with
383a single underscore are reserved by enum and cannot be used; all other
Ethan Furman8be6fac2014-11-01 07:40:22 -0700384attributes defined within an enumeration will become members of this
385enumeration, with the exception of special methods (:meth:`__str__`,
Ethan Furmana4b1bb42018-01-22 07:56:37 -0800386:meth:`__add__`, etc.), descriptors (methods are also descriptors), and
387variable names listed in :attr:`_ignore_`.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700388
389Note: if your enumeration defines :meth:`__new__` and/or :meth:`__init__` then
Antoined3c8d732019-08-20 03:41:31 +0200390any value(s) given to the enum member will be passed into those methods.
391See `Planet`_ for an example.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700392
393
Ethan Furman5bdab642018-09-21 19:03:09 -0700394Restricted Enum subclassing
395---------------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700396
Ethan Furman5bdab642018-09-21 19:03:09 -0700397A new :class:`Enum` class must have one base Enum class, up to one concrete
398data type, and as many :class:`object`-based mixin classes as needed. The
399order of these base classes is::
400
nu_nodfc8bb92019-01-27 23:07:47 +0100401 class EnumName([mix-in, ...,] [data-type,] base-enum):
Ethan Furman5bdab642018-09-21 19:03:09 -0700402 pass
403
404Also, subclassing an enumeration is allowed only if the enumeration does not define
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700405any members. So this is forbidden::
406
407 >>> class MoreColor(Color):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800408 ... PINK = 17
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700409 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700410 Traceback (most recent call last):
411 ...
412 TypeError: Cannot extend enumerations
413
414But this is allowed::
415
416 >>> class Foo(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700417 ... def some_behavior(self):
418 ... pass
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700419 ...
420 >>> class Bar(Foo):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800421 ... HAPPY = 1
422 ... SAD = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700423 ...
424
425Allowing subclassing of enums that define members would lead to a violation of
426some important invariants of types and instances. On the other hand, it makes
427sense to allow sharing some common behavior between a group of enumerations.
428(See `OrderedEnum`_ for an example.)
429
430
431Pickling
432--------
433
434Enumerations can be pickled and unpickled::
435
436 >>> from test.test_enum import Fruit
437 >>> from pickle import dumps, loads
Ethan Furman23bb6f42016-11-21 09:22:05 -0800438 >>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO))
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700439 True
440
441The usual restrictions for pickling apply: picklable enums must be defined in
442the top level of a module, since unpickling requires them to be importable
443from that module.
444
Ethan Furmanca1b7942014-02-08 11:36:27 -0800445.. note::
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700446
Ethan Furmanca1b7942014-02-08 11:36:27 -0800447 With pickle protocol version 4 it is possible to easily pickle enums
448 nested in other classes.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700449
Ethan Furman2da95042014-03-03 12:42:52 -0800450It is possible to modify how Enum members are pickled/unpickled by defining
451:meth:`__reduce_ex__` in the enumeration class.
452
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700453
454Functional API
455--------------
456
457The :class:`Enum` class is callable, providing the following functional API::
458
Ethan Furman23bb6f42016-11-21 09:22:05 -0800459 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG')
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700460 >>> Animal
461 <enum 'Animal'>
Ethan Furman23bb6f42016-11-21 09:22:05 -0800462 >>> Animal.ANT
463 <Animal.ANT: 1>
464 >>> Animal.ANT.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700465 1
466 >>> list(Animal)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800467 [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700468
Ethan Furman332dbc72016-08-20 00:00:52 -0700469The semantics of this API resemble :class:`~collections.namedtuple`. The first
470argument of the call to :class:`Enum` is the name of the enumeration.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700471
Ethan Furman332dbc72016-08-20 00:00:52 -0700472The second argument is the *source* of enumeration member names. It can be a
473whitespace-separated string of names, a sequence of names, a sequence of
4742-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to
475values. The last two options enable assigning arbitrary values to
476enumerations; the others auto-assign increasing integers starting with 1 (use
477the ``start`` parameter to specify a different starting value). A
478new class derived from :class:`Enum` is returned. In other words, the above
479assignment to :class:`Animal` is equivalent to::
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700480
Ethan Furman8a123292015-01-14 22:31:50 -0800481 >>> class Animal(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800482 ... ANT = 1
483 ... BEE = 2
484 ... CAT = 3
485 ... DOG = 4
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700486 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700487
Ethan Furmane2563462013-06-28 19:37:17 -0700488The reason for defaulting to ``1`` as the starting number and not ``0`` is
489that ``0`` is ``False`` in a boolean sense, but enum members all evaluate
490to ``True``.
491
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700492Pickling enums created with the functional API can be tricky as frame stack
493implementation details are used to try and figure out which module the
494enumeration is being created in (e.g. it will fail if you use a utility
Ethan Furman332dbc72016-08-20 00:00:52 -0700495function in separate module, and also may not work on IronPython or Jython).
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700496The solution is to specify the module name explicitly as follows::
497
Ethan Furman23bb6f42016-11-21 09:22:05 -0800498 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700499
Ethan Furman2da95042014-03-03 12:42:52 -0800500.. warning::
501
Ethan Furman01cc2d52014-03-03 15:02:04 -0800502 If ``module`` is not supplied, and Enum cannot determine what it is,
Ethan Furman2da95042014-03-03 12:42:52 -0800503 the new Enum members will not be unpicklable; to keep errors closer to
504 the source, pickling will be disabled.
505
Ethan Furmanca1b7942014-02-08 11:36:27 -0800506The new pickle protocol 4 also, in some circumstances, relies on
Martin Panterbae5d812016-06-18 03:57:31 +0000507:attr:`~definition.__qualname__` being set to the location where pickle will be able
Ethan Furmanca1b7942014-02-08 11:36:27 -0800508to find the class. For example, if the class was made available in class
509SomeData in the global scope::
510
Ethan Furman23bb6f42016-11-21 09:22:05 -0800511 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal')
Ethan Furmanca1b7942014-02-08 11:36:27 -0800512
Ethan Furman2da95042014-03-03 12:42:52 -0800513The complete signature is::
514
Ethan Furman332dbc72016-08-20 00:00:52 -0700515 Enum(value='NewEnumName', names=<...>, *, module='...', qualname='...', type=<mixed-in class>, start=1)
Ethan Furman2da95042014-03-03 12:42:52 -0800516
Ethan Furman01cc2d52014-03-03 15:02:04 -0800517:value: What the new Enum class will record as its name.
Ethan Furman2da95042014-03-03 12:42:52 -0800518
Zachary Waredbd1c432014-03-20 10:01:48 -0500519:names: The Enum members. This can be a whitespace or comma separated string
Ethan Furmand9925a12014-09-16 20:35:55 -0700520 (values will start at 1 unless otherwise specified)::
Ethan Furman2da95042014-03-03 12:42:52 -0800521
Ethan Furman23bb6f42016-11-21 09:22:05 -0800522 'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE'
Ethan Furman2da95042014-03-03 12:42:52 -0800523
Ethan Furman8a123292015-01-14 22:31:50 -0800524 or an iterator of names::
525
Ethan Furman23bb6f42016-11-21 09:22:05 -0800526 ['RED', 'GREEN', 'BLUE']
Ethan Furman8a123292015-01-14 22:31:50 -0800527
Ethan Furman01cc2d52014-03-03 15:02:04 -0800528 or an iterator of (name, value) pairs::
Ethan Furman2da95042014-03-03 12:42:52 -0800529
Ethan Furman23bb6f42016-11-21 09:22:05 -0800530 [('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)]
Ethan Furman2da95042014-03-03 12:42:52 -0800531
Ethan Furman01cc2d52014-03-03 15:02:04 -0800532 or a mapping::
Ethan Furman2da95042014-03-03 12:42:52 -0800533
Ethan Furman23bb6f42016-11-21 09:22:05 -0800534 {'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42}
Ethan Furman2da95042014-03-03 12:42:52 -0800535
Ethan Furman01cc2d52014-03-03 15:02:04 -0800536:module: name of module where new Enum class can be found.
Ethan Furman2da95042014-03-03 12:42:52 -0800537
Ethan Furman01cc2d52014-03-03 15:02:04 -0800538:qualname: where in module new Enum class can be found.
Ethan Furman2da95042014-03-03 12:42:52 -0800539
Ethan Furman01cc2d52014-03-03 15:02:04 -0800540:type: type to mix in to new Enum class.
Ethan Furman2da95042014-03-03 12:42:52 -0800541
Yury Selivanov4dde5872015-09-11 00:48:21 -0400542:start: number to start counting at if only names are passed in.
Ethan Furmand9925a12014-09-16 20:35:55 -0700543
Berker Peksag60efd792014-09-18 05:23:14 +0300544.. versionchanged:: 3.5
545 The *start* parameter was added.
546
Ethan Furmanca1b7942014-02-08 11:36:27 -0800547
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700548Derived Enumerations
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700549--------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700550
551IntEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700552^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700553
Ethan Furman65a5a472016-09-01 23:55:19 -0700554The first variation of :class:`Enum` that is provided is also a subclass of
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700555:class:`int`. Members of an :class:`IntEnum` can be compared to integers;
556by extension, integer enumerations of different types can also be compared
557to each other::
558
559 >>> from enum import IntEnum
560 >>> class Shape(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800561 ... CIRCLE = 1
562 ... SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700563 ...
564 >>> class Request(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800565 ... POST = 1
566 ... GET = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700567 ...
568 >>> Shape == 1
569 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800570 >>> Shape.CIRCLE == 1
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700571 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800572 >>> Shape.CIRCLE == Request.POST
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700573 True
574
575However, they still can't be compared to standard :class:`Enum` enumerations::
576
577 >>> class Shape(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800578 ... CIRCLE = 1
579 ... SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700580 ...
581 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800582 ... RED = 1
583 ... GREEN = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700584 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800585 >>> Shape.CIRCLE == Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700586 False
587
588:class:`IntEnum` values behave like integers in other ways you'd expect::
589
Ethan Furman23bb6f42016-11-21 09:22:05 -0800590 >>> int(Shape.CIRCLE)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700591 1
Ethan Furman23bb6f42016-11-21 09:22:05 -0800592 >>> ['a', 'b', 'c'][Shape.CIRCLE]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700593 'b'
Ethan Furman23bb6f42016-11-21 09:22:05 -0800594 >>> [i for i in range(Shape.SQUARE)]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700595 [0, 1]
596
Ethan Furman65a5a472016-09-01 23:55:19 -0700597
598IntFlag
599^^^^^^^
600
601The next variation of :class:`Enum` provided, :class:`IntFlag`, is also based
602on :class:`int`. The difference being :class:`IntFlag` members can be combined
603using the bitwise operators (&, \|, ^, ~) and the result is still an
604:class:`IntFlag` member. However, as the name implies, :class:`IntFlag`
Ethan Furman54924df2016-09-07 23:40:31 -0700605members also subclass :class:`int` and can be used wherever an :class:`int` is
606used. Any operation on an :class:`IntFlag` member besides the bit-wise
607operations will lose the :class:`IntFlag` membership.
Ethan Furman65a5a472016-09-01 23:55:19 -0700608
Ethan Furman25d94bb2016-09-02 16:32:32 -0700609.. versionadded:: 3.6
610
611Sample :class:`IntFlag` class::
612
Ethan Furman65a5a472016-09-01 23:55:19 -0700613 >>> from enum import IntFlag
614 >>> class Perm(IntFlag):
615 ... R = 4
616 ... W = 2
617 ... X = 1
618 ...
619 >>> Perm.R | Perm.W
620 <Perm.R|W: 6>
621 >>> Perm.R + Perm.W
622 6
623 >>> RW = Perm.R | Perm.W
624 >>> Perm.R in RW
625 True
626
Ethan Furman25d94bb2016-09-02 16:32:32 -0700627It is also possible to name the combinations::
628
629 >>> class Perm(IntFlag):
630 ... R = 4
631 ... W = 2
632 ... X = 1
633 ... RWX = 7
634 >>> Perm.RWX
635 <Perm.RWX: 7>
636 >>> ~Perm.RWX
Ethan Furman27682d22016-09-04 11:39:01 -0700637 <Perm.-8: -8>
Ethan Furman25d94bb2016-09-02 16:32:32 -0700638
639Another important difference between :class:`IntFlag` and :class:`Enum` is that
640if no flags are set (the value is 0), its boolean evaluation is :data:`False`::
641
642 >>> Perm.R & Perm.X
643 <Perm.0: 0>
644 >>> bool(Perm.R & Perm.X)
645 False
646
647Because :class:`IntFlag` members are also subclasses of :class:`int` they can
648be combined with them::
649
650 >>> Perm.X | 8
651 <Perm.8|X: 9>
Ethan Furman65a5a472016-09-01 23:55:19 -0700652
653
654Flag
655^^^^
656
657The last variation is :class:`Flag`. Like :class:`IntFlag`, :class:`Flag`
Ethan Furman25d94bb2016-09-02 16:32:32 -0700658members can be combined using the bitwise operators (&, \|, ^, ~). Unlike
Ethan Furman65a5a472016-09-01 23:55:19 -0700659:class:`IntFlag`, they cannot be combined with, nor compared against, any
Ethan Furmanc16595e2016-09-10 23:36:59 -0700660other :class:`Flag` enumeration, nor :class:`int`. While it is possible to
661specify the values directly it is recommended to use :class:`auto` as the
662value and let :class:`Flag` select an appropriate value.
Ethan Furman65a5a472016-09-01 23:55:19 -0700663
664.. versionadded:: 3.6
665
Ethan Furman25d94bb2016-09-02 16:32:32 -0700666Like :class:`IntFlag`, if a combination of :class:`Flag` members results in no
667flags being set, the boolean evaluation is :data:`False`::
668
Julian Kahnert0f31c742018-01-13 04:35:57 +0100669 >>> from enum import Flag, auto
Ethan Furman25d94bb2016-09-02 16:32:32 -0700670 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800671 ... RED = auto()
672 ... BLUE = auto()
673 ... GREEN = auto()
Ethan Furman25d94bb2016-09-02 16:32:32 -0700674 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800675 >>> Color.RED & Color.GREEN
Ethan Furman25d94bb2016-09-02 16:32:32 -0700676 <Color.0: 0>
Ethan Furman23bb6f42016-11-21 09:22:05 -0800677 >>> bool(Color.RED & Color.GREEN)
Ethan Furman25d94bb2016-09-02 16:32:32 -0700678 False
679
Ethan Furman27682d22016-09-04 11:39:01 -0700680Individual flags should have values that are powers of two (1, 2, 4, 8, ...),
681while combinations of flags won't::
682
683 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800684 ... RED = auto()
685 ... BLUE = auto()
686 ... GREEN = auto()
687 ... WHITE = RED | BLUE | GREEN
Ethan Furmanc16595e2016-09-10 23:36:59 -0700688 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800689 >>> Color.WHITE
690 <Color.WHITE: 7>
Ethan Furman27682d22016-09-04 11:39:01 -0700691
Ethan Furman25d94bb2016-09-02 16:32:32 -0700692Giving a name to the "no flags set" condition does not change its boolean
693value::
694
695 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800696 ... BLACK = 0
697 ... RED = auto()
698 ... BLUE = auto()
699 ... GREEN = auto()
Ethan Furman25d94bb2016-09-02 16:32:32 -0700700 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800701 >>> Color.BLACK
702 <Color.BLACK: 0>
703 >>> bool(Color.BLACK)
Ethan Furman25d94bb2016-09-02 16:32:32 -0700704 False
705
Ethan Furman65a5a472016-09-01 23:55:19 -0700706.. note::
707
708 For the majority of new code, :class:`Enum` and :class:`Flag` are strongly
709 recommended, since :class:`IntEnum` and :class:`IntFlag` break some
710 semantic promises of an enumeration (by being comparable to integers, and
711 thus by transitivity to other unrelated enumerations). :class:`IntEnum`
712 and :class:`IntFlag` should be used only in cases where :class:`Enum` and
713 :class:`Flag` will not do; for example, when integer constants are replaced
714 with enumerations, or for interoperability with other systems.
Ethan Furman332dbc72016-08-20 00:00:52 -0700715
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700716
717Others
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700718^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700719
720While :class:`IntEnum` is part of the :mod:`enum` module, it would be very
721simple to implement independently::
722
723 class IntEnum(int, Enum):
724 pass
725
726This demonstrates how similar derived enumerations can be defined; for example
Ethan Furman332dbc72016-08-20 00:00:52 -0700727a :class:`StrEnum` that mixes in :class:`str` instead of :class:`int`.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700728
729Some rules:
730
7311. When subclassing :class:`Enum`, mix-in types must appear before
732 :class:`Enum` itself in the sequence of bases, as in the :class:`IntEnum`
733 example above.
7342. While :class:`Enum` can have members of any type, once you mix in an
735 additional type, all the members must have values of that type, e.g.
736 :class:`int` above. This restriction does not apply to mix-ins which only
Antoined3c8d732019-08-20 03:41:31 +0200737 add methods and don't specify another type.
Ethan Furman6b3d64a2013-06-14 16:55:46 -07007383. When another data type is mixed in, the :attr:`value` attribute is *not the
Zachary Waredbd1c432014-03-20 10:01:48 -0500739 same* as the enum member itself, although it is equivalent and will compare
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700740 equal.
Martin Panterd5db1472016-02-08 01:34:09 +00007414. %-style formatting: `%s` and `%r` call the :class:`Enum` class's
742 :meth:`__str__` and :meth:`__repr__` respectively; other codes (such as
743 `%i` or `%h` for IntEnum) treat the enum member as its mixed-in type.
Martin Panterbc1ee462016-02-13 00:41:37 +00007445. :ref:`Formatted string literals <f-strings>`, :meth:`str.format`,
thatneat2f19e822019-07-04 11:28:37 -0700745 and :func:`format` will use the mixed-in type's :meth:`__format__`
746 unless :meth:`__str__` or :meth:`__format__` is overridden in the subclass,
747 in which case the overridden methods or :class:`Enum` methods will be used.
748 Use the !s and !r format codes to force usage of the :class:`Enum` class's
749 :meth:`__str__` and :meth:`__repr__` methods.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700750
Ethan Furmanf5223742018-09-12 10:00:30 -0700751When to use :meth:`__new__` vs. :meth:`__init__`
752------------------------------------------------
753
754:meth:`__new__` must be used whenever you want to customize the actual value of
755the :class:`Enum` member. Any other modifications may go in either
756:meth:`__new__` or :meth:`__init__`, with :meth:`__init__` being preferred.
757
758For example, if you want to pass several items to the constructor, but only
759want one of them to be the value::
760
761 >>> class Coordinate(bytes, Enum):
762 ... """
763 ... Coordinate with binary codes that can be indexed by the int code.
764 ... """
765 ... def __new__(cls, value, label, unit):
766 ... obj = bytes.__new__(cls, [value])
767 ... obj._value_ = value
768 ... obj.label = label
769 ... obj.unit = unit
770 ... return obj
771 ... PX = (0, 'P.X', 'km')
772 ... PY = (1, 'P.Y', 'km')
773 ... VX = (2, 'V.X', 'km/s')
774 ... VY = (3, 'V.Y', 'km/s')
775 ...
776
777 >>> print(Coordinate['PY'])
778 Coordinate.PY
779
780 >>> print(Coordinate(3))
781 Coordinate.VY
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700782
783Interesting examples
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700784--------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700785
Ethan Furman65a5a472016-09-01 23:55:19 -0700786While :class:`Enum`, :class:`IntEnum`, :class:`IntFlag`, and :class:`Flag` are
787expected to cover the majority of use-cases, they cannot cover them all. Here
788are recipes for some different types of enumerations that can be used directly,
789or as examples for creating one's own.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700790
791
Ethan Furman6a137e82016-09-07 08:17:15 -0700792Omitting values
793^^^^^^^^^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700794
Ethan Furman6a137e82016-09-07 08:17:15 -0700795In many use-cases one doesn't care what the actual value of an enumeration
796is. There are several ways to define this type of simple enumeration:
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700797
Ethan Furmanc16595e2016-09-10 23:36:59 -0700798- use instances of :class:`auto` for the value
Ethan Furman6a137e82016-09-07 08:17:15 -0700799- use instances of :class:`object` as the value
800- use a descriptive string as the value
801- use a tuple as the value and a custom :meth:`__new__` to replace the
802 tuple with an :class:`int` value
803
804Using any of these methods signifies to the user that these values are not
805important, and also enables one to add, remove, or reorder members without
806having to renumber the remaining members.
807
808Whichever method you choose, you should provide a :meth:`repr` that also hides
809the (unimportant) value::
810
811 >>> class NoValue(Enum):
812 ... def __repr__(self):
813 ... return '<%s.%s>' % (self.__class__.__name__, self.name)
814 ...
815
816
Ethan Furmanc16595e2016-09-10 23:36:59 -0700817Using :class:`auto`
818"""""""""""""""""""
819
Berker Peksag2a267a12017-01-02 05:51:04 +0300820Using :class:`auto` would look like::
Ethan Furmanc16595e2016-09-10 23:36:59 -0700821
822 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800823 ... RED = auto()
824 ... BLUE = auto()
825 ... GREEN = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700826 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800827 >>> Color.GREEN
828 <Color.GREEN>
Ethan Furmanc16595e2016-09-10 23:36:59 -0700829
830
Ethan Furman6a137e82016-09-07 08:17:15 -0700831Using :class:`object`
832"""""""""""""""""""""
833
834Using :class:`object` would look like::
835
836 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800837 ... RED = object()
838 ... GREEN = object()
839 ... BLUE = object()
Ethan Furman6a137e82016-09-07 08:17:15 -0700840 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800841 >>> Color.GREEN
842 <Color.GREEN>
Ethan Furman6a137e82016-09-07 08:17:15 -0700843
844
845Using a descriptive string
846""""""""""""""""""""""""""
847
848Using a string as the value would look like::
849
850 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800851 ... RED = 'stop'
852 ... GREEN = 'go'
853 ... BLUE = 'too fast!'
Ethan Furman6a137e82016-09-07 08:17:15 -0700854 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800855 >>> Color.GREEN
856 <Color.GREEN>
857 >>> Color.GREEN.value
Ethan Furman6a137e82016-09-07 08:17:15 -0700858 'go'
859
860
861Using a custom :meth:`__new__`
862""""""""""""""""""""""""""""""
863
864Using an auto-numbering :meth:`__new__` would look like::
865
866 >>> class AutoNumber(NoValue):
Ethan Furman332dbc72016-08-20 00:00:52 -0700867 ... def __new__(cls):
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700868 ... value = len(cls.__members__) + 1
869 ... obj = object.__new__(cls)
Ethan Furman90262622013-07-30 12:24:25 -0700870 ... obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700871 ... return obj
872 ...
Ethan Furman332dbc72016-08-20 00:00:52 -0700873 >>> class Color(AutoNumber):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800874 ... RED = ()
875 ... GREEN = ()
876 ... BLUE = ()
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700877 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800878 >>> Color.GREEN
879 <Color.GREEN>
880 >>> Color.GREEN.value
Ethan Furman6a137e82016-09-07 08:17:15 -0700881 2
882
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700883
Ethan Furman9a1daf52013-09-27 22:58:06 -0700884.. note::
885
886 The :meth:`__new__` method, if defined, is used during creation of the Enum
887 members; it is then replaced by Enum's :meth:`__new__` which is used after
Ethan Furmanf75805e2014-09-16 19:13:31 -0700888 class creation for lookup of existing members.
Ethan Furman9a1daf52013-09-27 22:58:06 -0700889
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700890
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700891OrderedEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700892^^^^^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700893
894An ordered enumeration that is not based on :class:`IntEnum` and so maintains
895the normal :class:`Enum` invariants (such as not being comparable to other
896enumerations)::
897
898 >>> class OrderedEnum(Enum):
899 ... def __ge__(self, other):
900 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700901 ... return self.value >= other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700902 ... return NotImplemented
903 ... def __gt__(self, other):
904 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700905 ... return self.value > other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700906 ... return NotImplemented
907 ... def __le__(self, other):
908 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700909 ... return self.value <= other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700910 ... return NotImplemented
911 ... def __lt__(self, other):
912 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700913 ... return self.value < other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700914 ... return NotImplemented
915 ...
916 >>> class Grade(OrderedEnum):
917 ... A = 5
918 ... B = 4
919 ... C = 3
920 ... D = 2
921 ... F = 1
922 ...
923 >>> Grade.C < Grade.A
924 True
925
926
Ethan Furmanf24bb352013-07-18 17:05:39 -0700927DuplicateFreeEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700928^^^^^^^^^^^^^^^^^
Ethan Furmanf24bb352013-07-18 17:05:39 -0700929
930Raises an error if a duplicate member name is found instead of creating an
931alias::
932
933 >>> class DuplicateFreeEnum(Enum):
934 ... def __init__(self, *args):
935 ... cls = self.__class__
936 ... if any(self.value == e.value for e in cls):
937 ... a = self.name
938 ... e = cls(self.value).name
939 ... raise ValueError(
940 ... "aliases not allowed in DuplicateFreeEnum: %r --> %r"
941 ... % (a, e))
942 ...
943 >>> class Color(DuplicateFreeEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800944 ... RED = 1
945 ... GREEN = 2
946 ... BLUE = 3
947 ... GRENE = 2
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700948 ...
Ethan Furmanf24bb352013-07-18 17:05:39 -0700949 Traceback (most recent call last):
950 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800951 ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN'
Ethan Furmanf24bb352013-07-18 17:05:39 -0700952
953.. note::
954
955 This is a useful example for subclassing Enum to add or change other
Ezio Melotti93d7dda2013-10-05 04:13:18 +0300956 behaviors as well as disallowing aliases. If the only desired change is
Ezio Melotti17f1edd2013-10-05 04:26:06 +0300957 disallowing aliases, the :func:`unique` decorator can be used instead.
Ethan Furmanf24bb352013-07-18 17:05:39 -0700958
959
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700960Planet
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700961^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700962
963If :meth:`__new__` or :meth:`__init__` is defined the value of the enum member
964will be passed to those methods::
965
966 >>> class Planet(Enum):
967 ... MERCURY = (3.303e+23, 2.4397e6)
968 ... VENUS = (4.869e+24, 6.0518e6)
969 ... EARTH = (5.976e+24, 6.37814e6)
970 ... MARS = (6.421e+23, 3.3972e6)
971 ... JUPITER = (1.9e+27, 7.1492e7)
972 ... SATURN = (5.688e+26, 6.0268e7)
973 ... URANUS = (8.686e+25, 2.5559e7)
974 ... NEPTUNE = (1.024e+26, 2.4746e7)
975 ... def __init__(self, mass, radius):
976 ... self.mass = mass # in kilograms
977 ... self.radius = radius # in meters
978 ... @property
979 ... def surface_gravity(self):
980 ... # universal gravitational constant (m3 kg-1 s-2)
981 ... G = 6.67300E-11
982 ... return G * self.mass / (self.radius * self.radius)
983 ...
984 >>> Planet.EARTH.value
985 (5.976e+24, 6378140.0)
986 >>> Planet.EARTH.surface_gravity
987 9.802652743337129
Ethan Furman9a1daf52013-09-27 22:58:06 -0700988
989
Ethan Furmana4b1bb42018-01-22 07:56:37 -0800990TimePeriod
991^^^^^^^^^^
992
993An example to show the :attr:`_ignore_` attribute in use::
994
995 >>> from datetime import timedelta
996 >>> class Period(timedelta, Enum):
997 ... "different lengths of time"
998 ... _ignore_ = 'Period i'
999 ... Period = vars()
1000 ... for i in range(367):
1001 ... Period['day_%d' % i] = i
1002 ...
1003 >>> list(Period)[:2]
1004 [<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>]
1005 >>> list(Period)[-2:]
1006 [<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>]
1007
1008
Ethan Furman9a1daf52013-09-27 22:58:06 -07001009How are Enums different?
1010------------------------
1011
1012Enums have a custom metaclass that affects many aspects of both derived Enum
1013classes and their instances (members).
1014
1015
1016Enum Classes
1017^^^^^^^^^^^^
1018
1019The :class:`EnumMeta` metaclass is responsible for providing the
1020:meth:`__contains__`, :meth:`__dir__`, :meth:`__iter__` and other methods that
1021allow one to do things with an :class:`Enum` class that fail on a typical
Rahul Jha94306522018-09-10 23:51:04 +05301022class, such as `list(Color)` or `some_enum_var in Color`. :class:`EnumMeta` is
Ethan Furman9a1daf52013-09-27 22:58:06 -07001023responsible for ensuring that various other methods on the final :class:`Enum`
1024class are correct (such as :meth:`__new__`, :meth:`__getnewargs__`,
Martin Panterd21e0b52015-10-10 10:36:22 +00001025:meth:`__str__` and :meth:`__repr__`).
Ethan Furman9a1daf52013-09-27 22:58:06 -07001026
1027
1028Enum Members (aka instances)
1029^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1030
1031The most interesting thing about Enum members is that they are singletons.
1032:class:`EnumMeta` creates them all while it is creating the :class:`Enum`
1033class itself, and then puts a custom :meth:`__new__` in place to ensure
1034that no new ones are ever instantiated by returning only the existing
1035member instances.
1036
1037
1038Finer Points
1039^^^^^^^^^^^^
1040
Ethan Furman65a5a472016-09-01 23:55:19 -07001041Supported ``__dunder__`` names
Ethan Furman6a137e82016-09-07 08:17:15 -07001042""""""""""""""""""""""""""""""
Ethan Furman9a1daf52013-09-27 22:58:06 -07001043
INADA Naokie57f91a2018-06-19 01:14:26 +09001044:attr:`__members__` is a read-only ordered mapping of ``member_name``:``member``
Ethan Furman65a5a472016-09-01 23:55:19 -07001045items. It is only available on the class.
Ethan Furman9a1daf52013-09-27 22:58:06 -07001046
Ethan Furman65a5a472016-09-01 23:55:19 -07001047:meth:`__new__`, if specified, must create and return the enum members; it is
1048also a very good idea to set the member's :attr:`_value_` appropriately. Once
1049all the members are created it is no longer used.
Ethan Furman748dad52015-11-20 13:12:26 -08001050
Ethan Furman60255b62016-01-15 15:01:33 -08001051
Ethan Furman65a5a472016-09-01 23:55:19 -07001052Supported ``_sunder_`` names
Ethan Furman6a137e82016-09-07 08:17:15 -07001053""""""""""""""""""""""""""""
Ethan Furman60255b62016-01-15 15:01:33 -08001054
Ethan Furman65a5a472016-09-01 23:55:19 -07001055- ``_name_`` -- name of the member
1056- ``_value_`` -- value of the member; can be set / modified in ``__new__``
Ethan Furman9a1daf52013-09-27 22:58:06 -07001057
Ethan Furman65a5a472016-09-01 23:55:19 -07001058- ``_missing_`` -- a lookup function used when a value is not found; may be
1059 overridden
Antoined3c8d732019-08-20 03:41:31 +02001060- ``_ignore_`` -- a list of names, either as a :class:`list` or a :class:`str`,
Ethan Furmana4b1bb42018-01-22 07:56:37 -08001061 that will not be transformed into members, and will be removed from the final
1062 class
Ethan Furman65a5a472016-09-01 23:55:19 -07001063- ``_order_`` -- used in Python 2/3 code to ensure member order is consistent
1064 (class attribute, removed during class creation)
Ethan Furmanc16595e2016-09-10 23:36:59 -07001065- ``_generate_next_value_`` -- used by the `Functional API`_ and by
1066 :class:`auto` to get an appropriate value for an enum member; may be
1067 overridden
Ethan Furman9a1daf52013-09-27 22:58:06 -07001068
Ethan Furmanc16595e2016-09-10 23:36:59 -07001069.. versionadded:: 3.6 ``_missing_``, ``_order_``, ``_generate_next_value_``
Ethan Furmana4b1bb42018-01-22 07:56:37 -08001070.. versionadded:: 3.7 ``_ignore_``
Ethan Furman332dbc72016-08-20 00:00:52 -07001071
Ethan Furman65a5a472016-09-01 23:55:19 -07001072To help keep Python 2 / Python 3 code in sync an :attr:`_order_` attribute can
1073be provided. It will be checked against the actual order of the enumeration
1074and raise an error if the two do not match::
Ethan Furmane8e61272016-08-20 07:19:31 -07001075
1076 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -08001077 ... _order_ = 'RED GREEN BLUE'
1078 ... RED = 1
1079 ... BLUE = 3
1080 ... GREEN = 2
Ethan Furmane8e61272016-08-20 07:19:31 -07001081 ...
1082 Traceback (most recent call last):
1083 ...
1084 TypeError: member order does not match _order_
1085
1086.. note::
1087
1088 In Python 2 code the :attr:`_order_` attribute is necessary as definition
Ethan Furman65a5a472016-09-01 23:55:19 -07001089 order is lost before it can be recorded.
1090
1091``Enum`` member type
Ethan Furman6a137e82016-09-07 08:17:15 -07001092""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001093
Ethan Furman54924df2016-09-07 23:40:31 -07001094:class:`Enum` members are instances of their :class:`Enum` class, and are
1095normally accessed as ``EnumClass.member``. Under certain circumstances they
1096can also be accessed as ``EnumClass.member.member``, but you should never do
1097this as that lookup may fail or, worse, return something besides the
Ethan Furman23bb6f42016-11-21 09:22:05 -08001098:class:`Enum` member you are looking for (this is another good reason to use
1099all-uppercase names for members)::
Ethan Furman65a5a472016-09-01 23:55:19 -07001100
1101 >>> class FieldTypes(Enum):
1102 ... name = 0
1103 ... value = 1
1104 ... size = 2
1105 ...
1106 >>> FieldTypes.value.size
1107 <FieldTypes.size: 2>
1108 >>> FieldTypes.size.value
1109 2
1110
1111.. versionchanged:: 3.5
1112
1113
1114Boolean value of ``Enum`` classes and members
Ethan Furman6a137e82016-09-07 08:17:15 -07001115"""""""""""""""""""""""""""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001116
Ethan Furman54924df2016-09-07 23:40:31 -07001117:class:`Enum` members that are mixed with non-:class:`Enum` types (such as
Ethan Furman65a5a472016-09-01 23:55:19 -07001118:class:`int`, :class:`str`, etc.) are evaluated according to the mixed-in
Ethan Furman54924df2016-09-07 23:40:31 -07001119type's rules; otherwise, all members evaluate as :data:`True`. To make your
1120own Enum's boolean evaluation depend on the member's value add the following to
Ethan Furman65a5a472016-09-01 23:55:19 -07001121your class::
1122
1123 def __bool__(self):
1124 return bool(self.value)
1125
Ethan Furman54924df2016-09-07 23:40:31 -07001126:class:`Enum` classes always evaluate as :data:`True`.
Ethan Furman65a5a472016-09-01 23:55:19 -07001127
1128
1129``Enum`` classes with methods
Ethan Furman6a137e82016-09-07 08:17:15 -07001130"""""""""""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001131
1132If you give your :class:`Enum` subclass extra methods, like the `Planet`_
1133class above, those methods will show up in a :func:`dir` of the member,
1134but not of the class::
1135
1136 >>> dir(Planet)
1137 ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__']
1138 >>> dir(Planet.EARTH)
1139 ['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value']
1140
Ethan Furman3515dcc2016-09-18 13:15:41 -07001141
1142Combining members of ``Flag``
1143"""""""""""""""""""""""""""""
1144
1145If a combination of Flag members is not named, the :func:`repr` will include
1146all named flags and all named combinations of flags that are in the value::
1147
1148 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -08001149 ... RED = auto()
1150 ... GREEN = auto()
1151 ... BLUE = auto()
1152 ... MAGENTA = RED | BLUE
1153 ... YELLOW = RED | GREEN
1154 ... CYAN = GREEN | BLUE
Ethan Furman3515dcc2016-09-18 13:15:41 -07001155 ...
1156 >>> Color(3) # named combination
Ethan Furman23bb6f42016-11-21 09:22:05 -08001157 <Color.YELLOW: 3>
Ethan Furman3515dcc2016-09-18 13:15:41 -07001158 >>> Color(7) # not named combination
Ethan Furman23bb6f42016-11-21 09:22:05 -08001159 <Color.CYAN|MAGENTA|BLUE|YELLOW|GREEN|RED: 7>
Ethan Furman3515dcc2016-09-18 13:15:41 -07001160