blob: 382db11a72ba6703086b8fc64bb6d5387c7260e2 [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
Victor Stinner8f881902020-08-19 19:25:22 +020053 :noindex:
Ethan Furmanc72e6382014-02-06 08:13:14 -080054
55 Enum class decorator that ensures only one name is bound to any one value.
Ethan Furmanf24bb352013-07-18 17:05:39 -070056
Ethan Furmanc16595e2016-09-10 23:36:59 -070057.. class:: auto
58
YoSTEALTH24bcefc2020-01-06 16:04:43 -060059 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 -070060
61.. versionadded:: 3.6 ``Flag``, ``IntFlag``, ``auto``
Ethan Furman65a5a472016-09-01 23:55:19 -070062
Ethan Furman6b3d64a2013-06-14 16:55:46 -070063
64Creating an Enum
65----------------
66
67Enumerations are created using the :keyword:`class` syntax, which makes them
68easy to read and write. An alternative creation method is described in
Ethan Furman332dbc72016-08-20 00:00:52 -070069`Functional API`_. To define an enumeration, subclass :class:`Enum` as
70follows::
Ethan Furman6b3d64a2013-06-14 16:55:46 -070071
Ethan Furman332dbc72016-08-20 00:00:52 -070072 >>> from enum import Enum
73 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -080074 ... RED = 1
75 ... GREEN = 2
76 ... BLUE = 3
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070077 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -070078
Ethan Furmanc16595e2016-09-10 23:36:59 -070079.. note:: Enum member values
80
81 Member values can be anything: :class:`int`, :class:`str`, etc.. If
82 the exact value is unimportant you may use :class:`auto` instances and an
83 appropriate value will be chosen for you. Care must be taken if you mix
84 :class:`auto` with other values.
85
Ethan Furman455bfde2013-09-08 23:48:34 -070086.. note:: Nomenclature
87
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070088 - The class :class:`Color` is an *enumeration* (or *enum*)
Ethan Furman23bb6f42016-11-21 09:22:05 -080089 - The attributes :attr:`Color.RED`, :attr:`Color.GREEN`, etc., are
90 *enumeration members* (or *enum members*) and are functionally constants.
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070091 - The enum members have *names* and *values* (the name of
Ethan Furman23bb6f42016-11-21 09:22:05 -080092 :attr:`Color.RED` is ``RED``, the value of :attr:`Color.BLUE` is
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070093 ``3``, etc.)
Ethan Furman6b3d64a2013-06-14 16:55:46 -070094
Ethan Furman9a1daf52013-09-27 22:58:06 -070095.. note::
96
97 Even though we use the :keyword:`class` syntax to create Enums, Enums
98 are not normal Python classes. See `How are Enums different?`_ for
99 more details.
100
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700101Enumeration members have human readable string representations::
102
Ethan Furman23bb6f42016-11-21 09:22:05 -0800103 >>> print(Color.RED)
104 Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700105
106...while their ``repr`` has more information::
107
Ethan Furman23bb6f42016-11-21 09:22:05 -0800108 >>> print(repr(Color.RED))
109 <Color.RED: 1>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700110
111The *type* of an enumeration member is the enumeration it belongs to::
112
Ethan Furman23bb6f42016-11-21 09:22:05 -0800113 >>> type(Color.RED)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700114 <enum 'Color'>
Ethan Furman23bb6f42016-11-21 09:22:05 -0800115 >>> isinstance(Color.GREEN, Color)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700116 True
117 >>>
118
119Enum members also have a property that contains just their item name::
120
Ethan Furman23bb6f42016-11-21 09:22:05 -0800121 >>> print(Color.RED.name)
122 RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700123
124Enumerations support iteration, in definition order::
125
126 >>> class Shake(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800127 ... VANILLA = 7
128 ... CHOCOLATE = 4
129 ... COOKIES = 9
130 ... MINT = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700131 ...
132 >>> for shake in Shake:
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700133 ... print(shake)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700134 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800135 Shake.VANILLA
136 Shake.CHOCOLATE
137 Shake.COOKIES
138 Shake.MINT
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700139
140Enumeration members are hashable, so they can be used in dictionaries and sets::
141
142 >>> apples = {}
Ethan Furman23bb6f42016-11-21 09:22:05 -0800143 >>> apples[Color.RED] = 'red delicious'
144 >>> apples[Color.GREEN] = 'granny smith'
145 >>> apples == {Color.RED: 'red delicious', Color.GREEN: 'granny smith'}
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700146 True
147
148
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700149Programmatic access to enumeration members and their attributes
150---------------------------------------------------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700151
152Sometimes it's useful to access members in enumerations programmatically (i.e.
Ethan Furman23bb6f42016-11-21 09:22:05 -0800153situations where ``Color.RED`` won't do because the exact color is not known
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700154at program-writing time). ``Enum`` allows such access::
155
156 >>> Color(1)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800157 <Color.RED: 1>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700158 >>> Color(3)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800159 <Color.BLUE: 3>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700160
161If you want to access enum members by *name*, use item access::
162
Ethan Furman23bb6f42016-11-21 09:22:05 -0800163 >>> Color['RED']
164 <Color.RED: 1>
165 >>> Color['GREEN']
166 <Color.GREEN: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700167
Larry Hastings3732ed22014-03-15 21:13:56 -0700168If you have an enum member and need its :attr:`name` or :attr:`value`::
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700169
Ethan Furman23bb6f42016-11-21 09:22:05 -0800170 >>> member = Color.RED
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700171 >>> member.name
Ethan Furman23bb6f42016-11-21 09:22:05 -0800172 'RED'
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700173 >>> member.value
174 1
175
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700176
177Duplicating enum members and values
178-----------------------------------
179
180Having two enum members with the same name is invalid::
181
182 >>> class Shape(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800183 ... SQUARE = 2
184 ... SQUARE = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700185 ...
186 Traceback (most recent call last):
187 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800188 TypeError: Attempted to reuse key: 'SQUARE'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700189
190However, two enum members are allowed to have the same value. Given two members
191A and B with the same value (and A defined first), B is an alias to A. By-value
192lookup of the value of A and B will return A. By-name lookup of B will also
193return A::
194
195 >>> class Shape(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800196 ... SQUARE = 2
197 ... DIAMOND = 1
198 ... CIRCLE = 3
199 ... ALIAS_FOR_SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700200 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800201 >>> Shape.SQUARE
202 <Shape.SQUARE: 2>
203 >>> Shape.ALIAS_FOR_SQUARE
204 <Shape.SQUARE: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700205 >>> Shape(2)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800206 <Shape.SQUARE: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700207
Ethan Furman101e0742013-09-15 12:34:36 -0700208.. note::
209
210 Attempting to create a member with the same name as an already
211 defined attribute (another member, a method, etc.) or attempting to create
212 an attribute with the same name as a member is not allowed.
213
Ethan Furmanf24bb352013-07-18 17:05:39 -0700214
215Ensuring unique enumeration values
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700216----------------------------------
Ethan Furmanf24bb352013-07-18 17:05:39 -0700217
218By default, enumerations allow multiple names as aliases for the same value.
219When this behavior isn't desired, the following decorator can be used to
220ensure each value is used only once in the enumeration:
221
222.. decorator:: unique
223
224A :keyword:`class` decorator specifically for enumerations. It searches an
225enumeration's :attr:`__members__` gathering any aliases it finds; if any are
226found :exc:`ValueError` is raised with the details::
227
228 >>> from enum import Enum, unique
229 >>> @unique
230 ... class Mistake(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800231 ... ONE = 1
232 ... TWO = 2
233 ... THREE = 3
234 ... FOUR = 3
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700235 ...
Ethan Furmanf24bb352013-07-18 17:05:39 -0700236 Traceback (most recent call last):
237 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800238 ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
Ethan Furmanf24bb352013-07-18 17:05:39 -0700239
240
Ethan Furmanc16595e2016-09-10 23:36:59 -0700241Using automatic values
242----------------------
243
244If the exact value is unimportant you can use :class:`auto`::
245
246 >>> from enum import Enum, auto
247 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800248 ... RED = auto()
249 ... BLUE = auto()
250 ... GREEN = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700251 ...
252 >>> list(Color)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800253 [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
Ethan Furmanc16595e2016-09-10 23:36:59 -0700254
255The values are chosen by :func:`_generate_next_value_`, which can be
256overridden::
257
258 >>> class AutoName(Enum):
259 ... def _generate_next_value_(name, start, count, last_values):
260 ... return name
261 ...
262 >>> class Ordinal(AutoName):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800263 ... NORTH = auto()
264 ... SOUTH = auto()
265 ... EAST = auto()
266 ... WEST = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700267 ...
268 >>> list(Ordinal)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800269 [<Ordinal.NORTH: 'NORTH'>, <Ordinal.SOUTH: 'SOUTH'>, <Ordinal.EAST: 'EAST'>, <Ordinal.WEST: 'WEST'>]
Ethan Furmanc16595e2016-09-10 23:36:59 -0700270
271.. note::
272
273 The goal of the default :meth:`_generate_next_value_` methods is to provide
274 the next :class:`int` in sequence with the last :class:`int` provided, but
275 the way it does this is an implementation detail and may change.
276
Ethan Onstottd9a43e22020-04-28 13:20:55 -0400277.. note::
278
279 The :meth:`_generate_next_value_` method must be defined before any members.
280
Ethan Furmanf24bb352013-07-18 17:05:39 -0700281Iteration
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700282---------
Ethan Furmanf24bb352013-07-18 17:05:39 -0700283
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700284Iterating over the members of an enum does not provide the aliases::
285
286 >>> list(Shape)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800287 [<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700288
INADA Naokie57f91a2018-06-19 01:14:26 +0900289The special attribute ``__members__`` is a read-only ordered mapping of names
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700290to members. It includes all names defined in the enumeration, including the
291aliases::
292
293 >>> for name, member in Shape.__members__.items():
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700294 ... name, member
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700295 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800296 ('SQUARE', <Shape.SQUARE: 2>)
297 ('DIAMOND', <Shape.DIAMOND: 1>)
298 ('CIRCLE', <Shape.CIRCLE: 3>)
299 ('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700300
301The ``__members__`` attribute can be used for detailed programmatic access to
302the enumeration members. For example, finding all the aliases::
303
Ethan Furman332dbc72016-08-20 00:00:52 -0700304 >>> [name for name, member in Shape.__members__.items() if member.name != name]
Ethan Furman23bb6f42016-11-21 09:22:05 -0800305 ['ALIAS_FOR_SQUARE']
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700306
Ethan Furmanf24bb352013-07-18 17:05:39 -0700307
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700308Comparisons
309-----------
310
311Enumeration members are compared by identity::
312
Ethan Furman23bb6f42016-11-21 09:22:05 -0800313 >>> Color.RED is Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700314 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800315 >>> Color.RED is Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700316 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800317 >>> Color.RED is not Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700318 True
319
320Ordered comparisons between enumeration values are *not* supported. Enum
321members are not integers (but see `IntEnum`_ below)::
322
Ethan Furman23bb6f42016-11-21 09:22:05 -0800323 >>> Color.RED < Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700324 Traceback (most recent call last):
325 File "<stdin>", line 1, in <module>
Ethan Furmane8e61272016-08-20 07:19:31 -0700326 TypeError: '<' not supported between instances of 'Color' and 'Color'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700327
328Equality comparisons are defined though::
329
Ethan Furman23bb6f42016-11-21 09:22:05 -0800330 >>> Color.BLUE == Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700331 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800332 >>> Color.BLUE != Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700333 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800334 >>> Color.BLUE == Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700335 True
336
337Comparisons against non-enumeration values will always compare not equal
Ezio Melotti93d7dda2013-10-05 04:13:18 +0300338(again, :class:`IntEnum` was explicitly designed to behave differently, see
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700339below)::
340
Ethan Furman23bb6f42016-11-21 09:22:05 -0800341 >>> Color.BLUE == 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700342 False
343
344
345Allowed members and attributes of enumerations
346----------------------------------------------
347
348The examples above use integers for enumeration values. Using integers is
Ethan Furman332dbc72016-08-20 00:00:52 -0700349short and handy (and provided by default by the `Functional API`_), but not
350strictly enforced. In the vast majority of use-cases, one doesn't care what
351the actual value of an enumeration is. But if the value *is* important,
352enumerations can have arbitrary values.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700353
354Enumerations are Python classes, and can have methods and special methods as
355usual. If we have this enumeration::
356
357 >>> class Mood(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800358 ... FUNKY = 1
359 ... HAPPY = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700360 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700361 ... def describe(self):
362 ... # self is the member here
363 ... return self.name, self.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700364 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700365 ... def __str__(self):
366 ... return 'my custom str! {0}'.format(self.value)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700367 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700368 ... @classmethod
369 ... def favorite_mood(cls):
370 ... # cls here is the enumeration
Ethan Furman23bb6f42016-11-21 09:22:05 -0800371 ... return cls.HAPPY
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700372 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700373
374Then::
375
376 >>> Mood.favorite_mood()
Ethan Furman23bb6f42016-11-21 09:22:05 -0800377 <Mood.HAPPY: 3>
378 >>> Mood.HAPPY.describe()
379 ('HAPPY', 3)
380 >>> str(Mood.FUNKY)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700381 'my custom str! 1'
382
Martin Pantera90a4a92016-05-30 04:04:50 +0000383The rules for what is allowed are as follows: names that start and end with
384a single underscore are reserved by enum and cannot be used; all other
Ethan Furman8be6fac2014-11-01 07:40:22 -0700385attributes defined within an enumeration will become members of this
386enumeration, with the exception of special methods (:meth:`__str__`,
Ethan Furmana4b1bb42018-01-22 07:56:37 -0800387:meth:`__add__`, etc.), descriptors (methods are also descriptors), and
388variable names listed in :attr:`_ignore_`.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700389
390Note: if your enumeration defines :meth:`__new__` and/or :meth:`__init__` then
Antoined3c8d732019-08-20 03:41:31 +0200391any value(s) given to the enum member will be passed into those methods.
392See `Planet`_ for an example.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700393
394
Ethan Furman5bdab642018-09-21 19:03:09 -0700395Restricted Enum subclassing
396---------------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700397
Ethan Furman5bdab642018-09-21 19:03:09 -0700398A new :class:`Enum` class must have one base Enum class, up to one concrete
399data type, and as many :class:`object`-based mixin classes as needed. The
400order of these base classes is::
401
nu_nodfc8bb92019-01-27 23:07:47 +0100402 class EnumName([mix-in, ...,] [data-type,] base-enum):
Ethan Furman5bdab642018-09-21 19:03:09 -0700403 pass
404
405Also, subclassing an enumeration is allowed only if the enumeration does not define
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700406any members. So this is forbidden::
407
408 >>> class MoreColor(Color):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800409 ... PINK = 17
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700410 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700411 Traceback (most recent call last):
412 ...
413 TypeError: Cannot extend enumerations
414
415But this is allowed::
416
417 >>> class Foo(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700418 ... def some_behavior(self):
419 ... pass
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700420 ...
421 >>> class Bar(Foo):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800422 ... HAPPY = 1
423 ... SAD = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700424 ...
425
426Allowing subclassing of enums that define members would lead to a violation of
427some important invariants of types and instances. On the other hand, it makes
428sense to allow sharing some common behavior between a group of enumerations.
429(See `OrderedEnum`_ for an example.)
430
431
432Pickling
433--------
434
435Enumerations can be pickled and unpickled::
436
437 >>> from test.test_enum import Fruit
438 >>> from pickle import dumps, loads
Ethan Furman23bb6f42016-11-21 09:22:05 -0800439 >>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO))
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700440 True
441
442The usual restrictions for pickling apply: picklable enums must be defined in
443the top level of a module, since unpickling requires them to be importable
444from that module.
445
Ethan Furmanca1b7942014-02-08 11:36:27 -0800446.. note::
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700447
Ethan Furmanca1b7942014-02-08 11:36:27 -0800448 With pickle protocol version 4 it is possible to easily pickle enums
449 nested in other classes.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700450
Ethan Furman2da95042014-03-03 12:42:52 -0800451It is possible to modify how Enum members are pickled/unpickled by defining
452:meth:`__reduce_ex__` in the enumeration class.
453
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700454
455Functional API
456--------------
457
458The :class:`Enum` class is callable, providing the following functional API::
459
Ethan Furman23bb6f42016-11-21 09:22:05 -0800460 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG')
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700461 >>> Animal
462 <enum 'Animal'>
Ethan Furman23bb6f42016-11-21 09:22:05 -0800463 >>> Animal.ANT
464 <Animal.ANT: 1>
465 >>> Animal.ANT.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700466 1
467 >>> list(Animal)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800468 [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700469
Ethan Furman332dbc72016-08-20 00:00:52 -0700470The semantics of this API resemble :class:`~collections.namedtuple`. The first
471argument of the call to :class:`Enum` is the name of the enumeration.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700472
Ethan Furman332dbc72016-08-20 00:00:52 -0700473The second argument is the *source* of enumeration member names. It can be a
474whitespace-separated string of names, a sequence of names, a sequence of
4752-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to
476values. The last two options enable assigning arbitrary values to
477enumerations; the others auto-assign increasing integers starting with 1 (use
478the ``start`` parameter to specify a different starting value). A
479new class derived from :class:`Enum` is returned. In other words, the above
480assignment to :class:`Animal` is equivalent to::
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700481
Ethan Furman8a123292015-01-14 22:31:50 -0800482 >>> class Animal(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800483 ... ANT = 1
484 ... BEE = 2
485 ... CAT = 3
486 ... DOG = 4
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700487 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700488
Ethan Furmane2563462013-06-28 19:37:17 -0700489The reason for defaulting to ``1`` as the starting number and not ``0`` is
490that ``0`` is ``False`` in a boolean sense, but enum members all evaluate
491to ``True``.
492
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700493Pickling enums created with the functional API can be tricky as frame stack
494implementation details are used to try and figure out which module the
495enumeration is being created in (e.g. it will fail if you use a utility
Ethan Furman332dbc72016-08-20 00:00:52 -0700496function in separate module, and also may not work on IronPython or Jython).
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700497The solution is to specify the module name explicitly as follows::
498
Ethan Furman23bb6f42016-11-21 09:22:05 -0800499 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700500
Ethan Furman2da95042014-03-03 12:42:52 -0800501.. warning::
502
Ethan Furman01cc2d52014-03-03 15:02:04 -0800503 If ``module`` is not supplied, and Enum cannot determine what it is,
Ethan Furman2da95042014-03-03 12:42:52 -0800504 the new Enum members will not be unpicklable; to keep errors closer to
505 the source, pickling will be disabled.
506
Ethan Furmanca1b7942014-02-08 11:36:27 -0800507The new pickle protocol 4 also, in some circumstances, relies on
Martin Panterbae5d812016-06-18 03:57:31 +0000508:attr:`~definition.__qualname__` being set to the location where pickle will be able
Ethan Furmanca1b7942014-02-08 11:36:27 -0800509to find the class. For example, if the class was made available in class
510SomeData in the global scope::
511
Ethan Furman23bb6f42016-11-21 09:22:05 -0800512 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal')
Ethan Furmanca1b7942014-02-08 11:36:27 -0800513
Ethan Furman2da95042014-03-03 12:42:52 -0800514The complete signature is::
515
Ethan Furman332dbc72016-08-20 00:00:52 -0700516 Enum(value='NewEnumName', names=<...>, *, module='...', qualname='...', type=<mixed-in class>, start=1)
Ethan Furman2da95042014-03-03 12:42:52 -0800517
Ethan Furman01cc2d52014-03-03 15:02:04 -0800518:value: What the new Enum class will record as its name.
Ethan Furman2da95042014-03-03 12:42:52 -0800519
Zachary Waredbd1c432014-03-20 10:01:48 -0500520:names: The Enum members. This can be a whitespace or comma separated string
Ethan Furmand9925a12014-09-16 20:35:55 -0700521 (values will start at 1 unless otherwise specified)::
Ethan Furman2da95042014-03-03 12:42:52 -0800522
Ethan Furman23bb6f42016-11-21 09:22:05 -0800523 'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE'
Ethan Furman2da95042014-03-03 12:42:52 -0800524
Ethan Furman8a123292015-01-14 22:31:50 -0800525 or an iterator of names::
526
Ethan Furman23bb6f42016-11-21 09:22:05 -0800527 ['RED', 'GREEN', 'BLUE']
Ethan Furman8a123292015-01-14 22:31:50 -0800528
Ethan Furman01cc2d52014-03-03 15:02:04 -0800529 or an iterator of (name, value) pairs::
Ethan Furman2da95042014-03-03 12:42:52 -0800530
Ethan Furman23bb6f42016-11-21 09:22:05 -0800531 [('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)]
Ethan Furman2da95042014-03-03 12:42:52 -0800532
Ethan Furman01cc2d52014-03-03 15:02:04 -0800533 or a mapping::
Ethan Furman2da95042014-03-03 12:42:52 -0800534
Ethan Furman23bb6f42016-11-21 09:22:05 -0800535 {'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42}
Ethan Furman2da95042014-03-03 12:42:52 -0800536
Ethan Furman01cc2d52014-03-03 15:02:04 -0800537:module: name of module where new Enum class can be found.
Ethan Furman2da95042014-03-03 12:42:52 -0800538
Ethan Furman01cc2d52014-03-03 15:02:04 -0800539:qualname: where in module new Enum class can be found.
Ethan Furman2da95042014-03-03 12:42:52 -0800540
Ethan Furman01cc2d52014-03-03 15:02:04 -0800541:type: type to mix in to new Enum class.
Ethan Furman2da95042014-03-03 12:42:52 -0800542
Yury Selivanov4dde5872015-09-11 00:48:21 -0400543:start: number to start counting at if only names are passed in.
Ethan Furmand9925a12014-09-16 20:35:55 -0700544
Berker Peksag60efd792014-09-18 05:23:14 +0300545.. versionchanged:: 3.5
546 The *start* parameter was added.
547
Ethan Furmanca1b7942014-02-08 11:36:27 -0800548
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700549Derived Enumerations
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700550--------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700551
552IntEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700553^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700554
Ethan Furman65a5a472016-09-01 23:55:19 -0700555The first variation of :class:`Enum` that is provided is also a subclass of
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700556:class:`int`. Members of an :class:`IntEnum` can be compared to integers;
557by extension, integer enumerations of different types can also be compared
558to each other::
559
560 >>> from enum import IntEnum
561 >>> class Shape(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800562 ... CIRCLE = 1
563 ... SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700564 ...
565 >>> class Request(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800566 ... POST = 1
567 ... GET = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700568 ...
569 >>> Shape == 1
570 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800571 >>> Shape.CIRCLE == 1
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700572 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800573 >>> Shape.CIRCLE == Request.POST
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700574 True
575
576However, they still can't be compared to standard :class:`Enum` enumerations::
577
578 >>> class Shape(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800579 ... CIRCLE = 1
580 ... SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700581 ...
582 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800583 ... RED = 1
584 ... GREEN = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700585 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800586 >>> Shape.CIRCLE == Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700587 False
588
589:class:`IntEnum` values behave like integers in other ways you'd expect::
590
Ethan Furman23bb6f42016-11-21 09:22:05 -0800591 >>> int(Shape.CIRCLE)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700592 1
Ethan Furman23bb6f42016-11-21 09:22:05 -0800593 >>> ['a', 'b', 'c'][Shape.CIRCLE]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700594 'b'
Ethan Furman23bb6f42016-11-21 09:22:05 -0800595 >>> [i for i in range(Shape.SQUARE)]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700596 [0, 1]
597
Ethan Furman65a5a472016-09-01 23:55:19 -0700598
599IntFlag
600^^^^^^^
601
602The next variation of :class:`Enum` provided, :class:`IntFlag`, is also based
603on :class:`int`. The difference being :class:`IntFlag` members can be combined
604using the bitwise operators (&, \|, ^, ~) and the result is still an
605:class:`IntFlag` member. However, as the name implies, :class:`IntFlag`
Ethan Furman54924df2016-09-07 23:40:31 -0700606members also subclass :class:`int` and can be used wherever an :class:`int` is
607used. Any operation on an :class:`IntFlag` member besides the bit-wise
608operations will lose the :class:`IntFlag` membership.
Ethan Furman65a5a472016-09-01 23:55:19 -0700609
Ethan Furman25d94bb2016-09-02 16:32:32 -0700610.. versionadded:: 3.6
611
612Sample :class:`IntFlag` class::
613
Ethan Furman65a5a472016-09-01 23:55:19 -0700614 >>> from enum import IntFlag
615 >>> class Perm(IntFlag):
616 ... R = 4
617 ... W = 2
618 ... X = 1
619 ...
620 >>> Perm.R | Perm.W
621 <Perm.R|W: 6>
622 >>> Perm.R + Perm.W
623 6
624 >>> RW = Perm.R | Perm.W
625 >>> Perm.R in RW
626 True
627
Ethan Furman25d94bb2016-09-02 16:32:32 -0700628It is also possible to name the combinations::
629
630 >>> class Perm(IntFlag):
631 ... R = 4
632 ... W = 2
633 ... X = 1
634 ... RWX = 7
635 >>> Perm.RWX
636 <Perm.RWX: 7>
637 >>> ~Perm.RWX
Ethan Furman27682d22016-09-04 11:39:01 -0700638 <Perm.-8: -8>
Ethan Furman25d94bb2016-09-02 16:32:32 -0700639
640Another important difference between :class:`IntFlag` and :class:`Enum` is that
641if no flags are set (the value is 0), its boolean evaluation is :data:`False`::
642
643 >>> Perm.R & Perm.X
644 <Perm.0: 0>
645 >>> bool(Perm.R & Perm.X)
646 False
647
648Because :class:`IntFlag` members are also subclasses of :class:`int` they can
649be combined with them::
650
651 >>> Perm.X | 8
652 <Perm.8|X: 9>
Ethan Furman65a5a472016-09-01 23:55:19 -0700653
654
655Flag
656^^^^
657
658The last variation is :class:`Flag`. Like :class:`IntFlag`, :class:`Flag`
Ethan Furman25d94bb2016-09-02 16:32:32 -0700659members can be combined using the bitwise operators (&, \|, ^, ~). Unlike
Ethan Furman65a5a472016-09-01 23:55:19 -0700660:class:`IntFlag`, they cannot be combined with, nor compared against, any
Ethan Furmanc16595e2016-09-10 23:36:59 -0700661other :class:`Flag` enumeration, nor :class:`int`. While it is possible to
662specify the values directly it is recommended to use :class:`auto` as the
663value and let :class:`Flag` select an appropriate value.
Ethan Furman65a5a472016-09-01 23:55:19 -0700664
665.. versionadded:: 3.6
666
Ethan Furman25d94bb2016-09-02 16:32:32 -0700667Like :class:`IntFlag`, if a combination of :class:`Flag` members results in no
668flags being set, the boolean evaluation is :data:`False`::
669
Julian Kahnert0f31c742018-01-13 04:35:57 +0100670 >>> from enum import Flag, auto
Ethan Furman25d94bb2016-09-02 16:32:32 -0700671 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800672 ... RED = auto()
673 ... BLUE = auto()
674 ... GREEN = auto()
Ethan Furman25d94bb2016-09-02 16:32:32 -0700675 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800676 >>> Color.RED & Color.GREEN
Ethan Furman25d94bb2016-09-02 16:32:32 -0700677 <Color.0: 0>
Ethan Furman23bb6f42016-11-21 09:22:05 -0800678 >>> bool(Color.RED & Color.GREEN)
Ethan Furman25d94bb2016-09-02 16:32:32 -0700679 False
680
Ethan Furman27682d22016-09-04 11:39:01 -0700681Individual flags should have values that are powers of two (1, 2, 4, 8, ...),
682while combinations of flags won't::
683
684 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800685 ... RED = auto()
686 ... BLUE = auto()
687 ... GREEN = auto()
688 ... WHITE = RED | BLUE | GREEN
Ethan Furmanc16595e2016-09-10 23:36:59 -0700689 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800690 >>> Color.WHITE
691 <Color.WHITE: 7>
Ethan Furman27682d22016-09-04 11:39:01 -0700692
Ethan Furman25d94bb2016-09-02 16:32:32 -0700693Giving a name to the "no flags set" condition does not change its boolean
694value::
695
696 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800697 ... BLACK = 0
698 ... RED = auto()
699 ... BLUE = auto()
700 ... GREEN = auto()
Ethan Furman25d94bb2016-09-02 16:32:32 -0700701 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800702 >>> Color.BLACK
703 <Color.BLACK: 0>
704 >>> bool(Color.BLACK)
Ethan Furman25d94bb2016-09-02 16:32:32 -0700705 False
706
Ethan Furman65a5a472016-09-01 23:55:19 -0700707.. note::
708
709 For the majority of new code, :class:`Enum` and :class:`Flag` are strongly
710 recommended, since :class:`IntEnum` and :class:`IntFlag` break some
711 semantic promises of an enumeration (by being comparable to integers, and
712 thus by transitivity to other unrelated enumerations). :class:`IntEnum`
713 and :class:`IntFlag` should be used only in cases where :class:`Enum` and
714 :class:`Flag` will not do; for example, when integer constants are replaced
715 with enumerations, or for interoperability with other systems.
Ethan Furman332dbc72016-08-20 00:00:52 -0700716
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700717
718Others
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700719^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700720
721While :class:`IntEnum` is part of the :mod:`enum` module, it would be very
722simple to implement independently::
723
724 class IntEnum(int, Enum):
725 pass
726
727This demonstrates how similar derived enumerations can be defined; for example
Ethan Furman332dbc72016-08-20 00:00:52 -0700728a :class:`StrEnum` that mixes in :class:`str` instead of :class:`int`.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700729
730Some rules:
731
7321. When subclassing :class:`Enum`, mix-in types must appear before
733 :class:`Enum` itself in the sequence of bases, as in the :class:`IntEnum`
734 example above.
7352. While :class:`Enum` can have members of any type, once you mix in an
736 additional type, all the members must have values of that type, e.g.
737 :class:`int` above. This restriction does not apply to mix-ins which only
Antoined3c8d732019-08-20 03:41:31 +0200738 add methods and don't specify another type.
Ethan Furman6b3d64a2013-06-14 16:55:46 -07007393. When another data type is mixed in, the :attr:`value` attribute is *not the
Zachary Waredbd1c432014-03-20 10:01:48 -0500740 same* as the enum member itself, although it is equivalent and will compare
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700741 equal.
Martin Panterd5db1472016-02-08 01:34:09 +00007424. %-style formatting: `%s` and `%r` call the :class:`Enum` class's
743 :meth:`__str__` and :meth:`__repr__` respectively; other codes (such as
744 `%i` or `%h` for IntEnum) treat the enum member as its mixed-in type.
Martin Panterbc1ee462016-02-13 00:41:37 +00007455. :ref:`Formatted string literals <f-strings>`, :meth:`str.format`,
thatneat2f19e822019-07-04 11:28:37 -0700746 and :func:`format` will use the mixed-in type's :meth:`__format__`
747 unless :meth:`__str__` or :meth:`__format__` is overridden in the subclass,
748 in which case the overridden methods or :class:`Enum` methods will be used.
749 Use the !s and !r format codes to force usage of the :class:`Enum` class's
750 :meth:`__str__` and :meth:`__repr__` methods.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700751
Ethan Furmanf5223742018-09-12 10:00:30 -0700752When to use :meth:`__new__` vs. :meth:`__init__`
753------------------------------------------------
754
755:meth:`__new__` must be used whenever you want to customize the actual value of
756the :class:`Enum` member. Any other modifications may go in either
757:meth:`__new__` or :meth:`__init__`, with :meth:`__init__` being preferred.
758
759For example, if you want to pass several items to the constructor, but only
760want one of them to be the value::
761
762 >>> class Coordinate(bytes, Enum):
763 ... """
764 ... Coordinate with binary codes that can be indexed by the int code.
765 ... """
766 ... def __new__(cls, value, label, unit):
767 ... obj = bytes.__new__(cls, [value])
768 ... obj._value_ = value
769 ... obj.label = label
770 ... obj.unit = unit
771 ... return obj
772 ... PX = (0, 'P.X', 'km')
773 ... PY = (1, 'P.Y', 'km')
774 ... VX = (2, 'V.X', 'km/s')
775 ... VY = (3, 'V.Y', 'km/s')
776 ...
777
778 >>> print(Coordinate['PY'])
779 Coordinate.PY
780
781 >>> print(Coordinate(3))
782 Coordinate.VY
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700783
784Interesting examples
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700785--------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700786
Ethan Furman65a5a472016-09-01 23:55:19 -0700787While :class:`Enum`, :class:`IntEnum`, :class:`IntFlag`, and :class:`Flag` are
788expected to cover the majority of use-cases, they cannot cover them all. Here
789are recipes for some different types of enumerations that can be used directly,
790or as examples for creating one's own.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700791
792
Ethan Furman6a137e82016-09-07 08:17:15 -0700793Omitting values
794^^^^^^^^^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700795
Ethan Furman6a137e82016-09-07 08:17:15 -0700796In many use-cases one doesn't care what the actual value of an enumeration
797is. There are several ways to define this type of simple enumeration:
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700798
Ethan Furmanc16595e2016-09-10 23:36:59 -0700799- use instances of :class:`auto` for the value
Ethan Furman6a137e82016-09-07 08:17:15 -0700800- use instances of :class:`object` as the value
801- use a descriptive string as the value
802- use a tuple as the value and a custom :meth:`__new__` to replace the
803 tuple with an :class:`int` value
804
805Using any of these methods signifies to the user that these values are not
806important, and also enables one to add, remove, or reorder members without
807having to renumber the remaining members.
808
809Whichever method you choose, you should provide a :meth:`repr` that also hides
810the (unimportant) value::
811
812 >>> class NoValue(Enum):
813 ... def __repr__(self):
814 ... return '<%s.%s>' % (self.__class__.__name__, self.name)
815 ...
816
817
Ethan Furmanc16595e2016-09-10 23:36:59 -0700818Using :class:`auto`
819"""""""""""""""""""
820
Berker Peksag2a267a12017-01-02 05:51:04 +0300821Using :class:`auto` would look like::
Ethan Furmanc16595e2016-09-10 23:36:59 -0700822
823 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800824 ... RED = auto()
825 ... BLUE = auto()
826 ... GREEN = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700827 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800828 >>> Color.GREEN
829 <Color.GREEN>
Ethan Furmanc16595e2016-09-10 23:36:59 -0700830
831
Ethan Furman6a137e82016-09-07 08:17:15 -0700832Using :class:`object`
833"""""""""""""""""""""
834
835Using :class:`object` would look like::
836
837 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800838 ... RED = object()
839 ... GREEN = object()
840 ... BLUE = object()
Ethan Furman6a137e82016-09-07 08:17:15 -0700841 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800842 >>> Color.GREEN
843 <Color.GREEN>
Ethan Furman6a137e82016-09-07 08:17:15 -0700844
845
846Using a descriptive string
847""""""""""""""""""""""""""
848
849Using a string as the value would look like::
850
851 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800852 ... RED = 'stop'
853 ... GREEN = 'go'
854 ... BLUE = 'too fast!'
Ethan Furman6a137e82016-09-07 08:17:15 -0700855 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800856 >>> Color.GREEN
857 <Color.GREEN>
858 >>> Color.GREEN.value
Ethan Furman6a137e82016-09-07 08:17:15 -0700859 'go'
860
861
862Using a custom :meth:`__new__`
863""""""""""""""""""""""""""""""
864
865Using an auto-numbering :meth:`__new__` would look like::
866
867 >>> class AutoNumber(NoValue):
Ethan Furman332dbc72016-08-20 00:00:52 -0700868 ... def __new__(cls):
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700869 ... value = len(cls.__members__) + 1
870 ... obj = object.__new__(cls)
Ethan Furman90262622013-07-30 12:24:25 -0700871 ... obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700872 ... return obj
873 ...
Ethan Furman332dbc72016-08-20 00:00:52 -0700874 >>> class Color(AutoNumber):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800875 ... RED = ()
876 ... GREEN = ()
877 ... BLUE = ()
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700878 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800879 >>> Color.GREEN
880 <Color.GREEN>
881 >>> Color.GREEN.value
Ethan Furman6a137e82016-09-07 08:17:15 -0700882 2
883
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700884
Ethan Furman9a1daf52013-09-27 22:58:06 -0700885.. note::
886
887 The :meth:`__new__` method, if defined, is used during creation of the Enum
888 members; it is then replaced by Enum's :meth:`__new__` which is used after
Ethan Furmanf75805e2014-09-16 19:13:31 -0700889 class creation for lookup of existing members.
Ethan Furman9a1daf52013-09-27 22:58:06 -0700890
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700891
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700892OrderedEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700893^^^^^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700894
895An ordered enumeration that is not based on :class:`IntEnum` and so maintains
896the normal :class:`Enum` invariants (such as not being comparable to other
897enumerations)::
898
899 >>> class OrderedEnum(Enum):
900 ... def __ge__(self, other):
901 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700902 ... return self.value >= other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700903 ... return NotImplemented
904 ... def __gt__(self, other):
905 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700906 ... return self.value > other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700907 ... return NotImplemented
908 ... def __le__(self, other):
909 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700910 ... return self.value <= other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700911 ... return NotImplemented
912 ... def __lt__(self, other):
913 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700914 ... return self.value < other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700915 ... return NotImplemented
916 ...
917 >>> class Grade(OrderedEnum):
918 ... A = 5
919 ... B = 4
920 ... C = 3
921 ... D = 2
922 ... F = 1
923 ...
924 >>> Grade.C < Grade.A
925 True
926
927
Ethan Furmanf24bb352013-07-18 17:05:39 -0700928DuplicateFreeEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700929^^^^^^^^^^^^^^^^^
Ethan Furmanf24bb352013-07-18 17:05:39 -0700930
931Raises an error if a duplicate member name is found instead of creating an
932alias::
933
934 >>> class DuplicateFreeEnum(Enum):
935 ... def __init__(self, *args):
936 ... cls = self.__class__
937 ... if any(self.value == e.value for e in cls):
938 ... a = self.name
939 ... e = cls(self.value).name
940 ... raise ValueError(
941 ... "aliases not allowed in DuplicateFreeEnum: %r --> %r"
942 ... % (a, e))
943 ...
944 >>> class Color(DuplicateFreeEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800945 ... RED = 1
946 ... GREEN = 2
947 ... BLUE = 3
948 ... GRENE = 2
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700949 ...
Ethan Furmanf24bb352013-07-18 17:05:39 -0700950 Traceback (most recent call last):
951 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800952 ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN'
Ethan Furmanf24bb352013-07-18 17:05:39 -0700953
954.. note::
955
956 This is a useful example for subclassing Enum to add or change other
Ezio Melotti93d7dda2013-10-05 04:13:18 +0300957 behaviors as well as disallowing aliases. If the only desired change is
Ezio Melotti17f1edd2013-10-05 04:26:06 +0300958 disallowing aliases, the :func:`unique` decorator can be used instead.
Ethan Furmanf24bb352013-07-18 17:05:39 -0700959
960
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700961Planet
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700962^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700963
964If :meth:`__new__` or :meth:`__init__` is defined the value of the enum member
965will be passed to those methods::
966
967 >>> class Planet(Enum):
968 ... MERCURY = (3.303e+23, 2.4397e6)
969 ... VENUS = (4.869e+24, 6.0518e6)
970 ... EARTH = (5.976e+24, 6.37814e6)
971 ... MARS = (6.421e+23, 3.3972e6)
972 ... JUPITER = (1.9e+27, 7.1492e7)
973 ... SATURN = (5.688e+26, 6.0268e7)
974 ... URANUS = (8.686e+25, 2.5559e7)
975 ... NEPTUNE = (1.024e+26, 2.4746e7)
976 ... def __init__(self, mass, radius):
977 ... self.mass = mass # in kilograms
978 ... self.radius = radius # in meters
979 ... @property
980 ... def surface_gravity(self):
981 ... # universal gravitational constant (m3 kg-1 s-2)
982 ... G = 6.67300E-11
983 ... return G * self.mass / (self.radius * self.radius)
984 ...
985 >>> Planet.EARTH.value
986 (5.976e+24, 6378140.0)
987 >>> Planet.EARTH.surface_gravity
988 9.802652743337129
Ethan Furman9a1daf52013-09-27 22:58:06 -0700989
990
Ethan Furmana4b1bb42018-01-22 07:56:37 -0800991TimePeriod
992^^^^^^^^^^
993
994An example to show the :attr:`_ignore_` attribute in use::
995
996 >>> from datetime import timedelta
997 >>> class Period(timedelta, Enum):
998 ... "different lengths of time"
999 ... _ignore_ = 'Period i'
1000 ... Period = vars()
1001 ... for i in range(367):
1002 ... Period['day_%d' % i] = i
1003 ...
1004 >>> list(Period)[:2]
1005 [<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>]
1006 >>> list(Period)[-2:]
1007 [<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>]
1008
1009
Ethan Furman9a1daf52013-09-27 22:58:06 -07001010How are Enums different?
1011------------------------
1012
1013Enums have a custom metaclass that affects many aspects of both derived Enum
1014classes and their instances (members).
1015
1016
1017Enum Classes
1018^^^^^^^^^^^^
1019
1020The :class:`EnumMeta` metaclass is responsible for providing the
1021:meth:`__contains__`, :meth:`__dir__`, :meth:`__iter__` and other methods that
1022allow one to do things with an :class:`Enum` class that fail on a typical
Rahul Jha94306522018-09-10 23:51:04 +05301023class, such as `list(Color)` or `some_enum_var in Color`. :class:`EnumMeta` is
Ethan Furman9a1daf52013-09-27 22:58:06 -07001024responsible for ensuring that various other methods on the final :class:`Enum`
1025class are correct (such as :meth:`__new__`, :meth:`__getnewargs__`,
Martin Panterd21e0b52015-10-10 10:36:22 +00001026:meth:`__str__` and :meth:`__repr__`).
Ethan Furman9a1daf52013-09-27 22:58:06 -07001027
1028
1029Enum Members (aka instances)
1030^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1031
1032The most interesting thing about Enum members is that they are singletons.
1033:class:`EnumMeta` creates them all while it is creating the :class:`Enum`
1034class itself, and then puts a custom :meth:`__new__` in place to ensure
1035that no new ones are ever instantiated by returning only the existing
1036member instances.
1037
1038
1039Finer Points
1040^^^^^^^^^^^^
1041
Ethan Furman65a5a472016-09-01 23:55:19 -07001042Supported ``__dunder__`` names
Ethan Furman6a137e82016-09-07 08:17:15 -07001043""""""""""""""""""""""""""""""
Ethan Furman9a1daf52013-09-27 22:58:06 -07001044
INADA Naokie57f91a2018-06-19 01:14:26 +09001045:attr:`__members__` is a read-only ordered mapping of ``member_name``:``member``
Ethan Furman65a5a472016-09-01 23:55:19 -07001046items. It is only available on the class.
Ethan Furman9a1daf52013-09-27 22:58:06 -07001047
Ethan Furman65a5a472016-09-01 23:55:19 -07001048:meth:`__new__`, if specified, must create and return the enum members; it is
1049also a very good idea to set the member's :attr:`_value_` appropriately. Once
1050all the members are created it is no longer used.
Ethan Furman748dad52015-11-20 13:12:26 -08001051
Ethan Furman60255b62016-01-15 15:01:33 -08001052
Ethan Furman65a5a472016-09-01 23:55:19 -07001053Supported ``_sunder_`` names
Ethan Furman6a137e82016-09-07 08:17:15 -07001054""""""""""""""""""""""""""""
Ethan Furman60255b62016-01-15 15:01:33 -08001055
Ethan Furman65a5a472016-09-01 23:55:19 -07001056- ``_name_`` -- name of the member
1057- ``_value_`` -- value of the member; can be set / modified in ``__new__``
Ethan Furman9a1daf52013-09-27 22:58:06 -07001058
Ethan Furman65a5a472016-09-01 23:55:19 -07001059- ``_missing_`` -- a lookup function used when a value is not found; may be
1060 overridden
Antoined3c8d732019-08-20 03:41:31 +02001061- ``_ignore_`` -- a list of names, either as a :class:`list` or a :class:`str`,
Ethan Furmana4b1bb42018-01-22 07:56:37 -08001062 that will not be transformed into members, and will be removed from the final
1063 class
Ethan Furman65a5a472016-09-01 23:55:19 -07001064- ``_order_`` -- used in Python 2/3 code to ensure member order is consistent
1065 (class attribute, removed during class creation)
Ethan Furmanc16595e2016-09-10 23:36:59 -07001066- ``_generate_next_value_`` -- used by the `Functional API`_ and by
1067 :class:`auto` to get an appropriate value for an enum member; may be
1068 overridden
Ethan Furman9a1daf52013-09-27 22:58:06 -07001069
Ethan Furmanc16595e2016-09-10 23:36:59 -07001070.. versionadded:: 3.6 ``_missing_``, ``_order_``, ``_generate_next_value_``
Ethan Furmana4b1bb42018-01-22 07:56:37 -08001071.. versionadded:: 3.7 ``_ignore_``
Ethan Furman332dbc72016-08-20 00:00:52 -07001072
Ethan Furman65a5a472016-09-01 23:55:19 -07001073To help keep Python 2 / Python 3 code in sync an :attr:`_order_` attribute can
1074be provided. It will be checked against the actual order of the enumeration
1075and raise an error if the two do not match::
Ethan Furmane8e61272016-08-20 07:19:31 -07001076
1077 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -08001078 ... _order_ = 'RED GREEN BLUE'
1079 ... RED = 1
1080 ... BLUE = 3
1081 ... GREEN = 2
Ethan Furmane8e61272016-08-20 07:19:31 -07001082 ...
1083 Traceback (most recent call last):
1084 ...
1085 TypeError: member order does not match _order_
1086
1087.. note::
1088
1089 In Python 2 code the :attr:`_order_` attribute is necessary as definition
Ethan Furman65a5a472016-09-01 23:55:19 -07001090 order is lost before it can be recorded.
1091
1092``Enum`` member type
Ethan Furman6a137e82016-09-07 08:17:15 -07001093""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001094
Ethan Furman54924df2016-09-07 23:40:31 -07001095:class:`Enum` members are instances of their :class:`Enum` class, and are
1096normally accessed as ``EnumClass.member``. Under certain circumstances they
1097can also be accessed as ``EnumClass.member.member``, but you should never do
1098this as that lookup may fail or, worse, return something besides the
Ethan Furman23bb6f42016-11-21 09:22:05 -08001099:class:`Enum` member you are looking for (this is another good reason to use
1100all-uppercase names for members)::
Ethan Furman65a5a472016-09-01 23:55:19 -07001101
1102 >>> class FieldTypes(Enum):
1103 ... name = 0
1104 ... value = 1
1105 ... size = 2
1106 ...
1107 >>> FieldTypes.value.size
1108 <FieldTypes.size: 2>
1109 >>> FieldTypes.size.value
1110 2
1111
1112.. versionchanged:: 3.5
1113
1114
1115Boolean value of ``Enum`` classes and members
Ethan Furman6a137e82016-09-07 08:17:15 -07001116"""""""""""""""""""""""""""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001117
Ethan Furman54924df2016-09-07 23:40:31 -07001118:class:`Enum` members that are mixed with non-:class:`Enum` types (such as
Ethan Furman65a5a472016-09-01 23:55:19 -07001119:class:`int`, :class:`str`, etc.) are evaluated according to the mixed-in
Ethan Furman54924df2016-09-07 23:40:31 -07001120type's rules; otherwise, all members evaluate as :data:`True`. To make your
1121own Enum's boolean evaluation depend on the member's value add the following to
Ethan Furman65a5a472016-09-01 23:55:19 -07001122your class::
1123
1124 def __bool__(self):
1125 return bool(self.value)
1126
Ethan Furman54924df2016-09-07 23:40:31 -07001127:class:`Enum` classes always evaluate as :data:`True`.
Ethan Furman65a5a472016-09-01 23:55:19 -07001128
1129
1130``Enum`` classes with methods
Ethan Furman6a137e82016-09-07 08:17:15 -07001131"""""""""""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001132
1133If you give your :class:`Enum` subclass extra methods, like the `Planet`_
1134class above, those methods will show up in a :func:`dir` of the member,
1135but not of the class::
1136
1137 >>> dir(Planet)
1138 ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__']
1139 >>> dir(Planet.EARTH)
1140 ['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value']
1141
Ethan Furman3515dcc2016-09-18 13:15:41 -07001142
1143Combining members of ``Flag``
1144"""""""""""""""""""""""""""""
1145
1146If a combination of Flag members is not named, the :func:`repr` will include
1147all named flags and all named combinations of flags that are in the value::
1148
1149 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -08001150 ... RED = auto()
1151 ... GREEN = auto()
1152 ... BLUE = auto()
1153 ... MAGENTA = RED | BLUE
1154 ... YELLOW = RED | GREEN
1155 ... CYAN = GREEN | BLUE
Ethan Furman3515dcc2016-09-18 13:15:41 -07001156 ...
1157 >>> Color(3) # named combination
Ethan Furman23bb6f42016-11-21 09:22:05 -08001158 <Color.YELLOW: 3>
Ethan Furman3515dcc2016-09-18 13:15:41 -07001159 >>> Color(7) # not named combination
Ethan Furman23bb6f42016-11-21 09:22:05 -08001160 <Color.CYAN|MAGENTA|BLUE|YELLOW|GREEN|RED: 7>
Ethan Furman3515dcc2016-09-18 13:15:41 -07001161