blob: b327a0ad15f96c940ebfee6aeeecbd7d712989f3 [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
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700116
117Enum members also have a property that contains just their item name::
118
Ethan Furman23bb6f42016-11-21 09:22:05 -0800119 >>> print(Color.RED.name)
120 RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700121
122Enumerations support iteration, in definition order::
123
124 >>> class Shake(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800125 ... VANILLA = 7
126 ... CHOCOLATE = 4
127 ... COOKIES = 9
128 ... MINT = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700129 ...
130 >>> for shake in Shake:
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700131 ... print(shake)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700132 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800133 Shake.VANILLA
134 Shake.CHOCOLATE
135 Shake.COOKIES
136 Shake.MINT
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700137
138Enumeration members are hashable, so they can be used in dictionaries and sets::
139
140 >>> apples = {}
Ethan Furman23bb6f42016-11-21 09:22:05 -0800141 >>> apples[Color.RED] = 'red delicious'
142 >>> apples[Color.GREEN] = 'granny smith'
143 >>> apples == {Color.RED: 'red delicious', Color.GREEN: 'granny smith'}
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700144 True
145
146
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700147Programmatic access to enumeration members and their attributes
148---------------------------------------------------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700149
150Sometimes it's useful to access members in enumerations programmatically (i.e.
Ethan Furman23bb6f42016-11-21 09:22:05 -0800151situations where ``Color.RED`` won't do because the exact color is not known
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700152at program-writing time). ``Enum`` allows such access::
153
154 >>> Color(1)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800155 <Color.RED: 1>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700156 >>> Color(3)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800157 <Color.BLUE: 3>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700158
159If you want to access enum members by *name*, use item access::
160
Ethan Furman23bb6f42016-11-21 09:22:05 -0800161 >>> Color['RED']
162 <Color.RED: 1>
163 >>> Color['GREEN']
164 <Color.GREEN: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700165
Larry Hastings3732ed22014-03-15 21:13:56 -0700166If you have an enum member and need its :attr:`name` or :attr:`value`::
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700167
Ethan Furman23bb6f42016-11-21 09:22:05 -0800168 >>> member = Color.RED
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700169 >>> member.name
Ethan Furman23bb6f42016-11-21 09:22:05 -0800170 'RED'
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700171 >>> member.value
172 1
173
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700174
175Duplicating enum members and values
176-----------------------------------
177
178Having two enum members with the same name is invalid::
179
180 >>> class Shape(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800181 ... SQUARE = 2
182 ... SQUARE = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700183 ...
184 Traceback (most recent call last):
185 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800186 TypeError: Attempted to reuse key: 'SQUARE'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700187
188However, two enum members are allowed to have the same value. Given two members
189A and B with the same value (and A defined first), B is an alias to A. By-value
190lookup of the value of A and B will return A. By-name lookup of B will also
191return A::
192
193 >>> class Shape(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800194 ... SQUARE = 2
195 ... DIAMOND = 1
196 ... CIRCLE = 3
197 ... ALIAS_FOR_SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700198 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800199 >>> Shape.SQUARE
200 <Shape.SQUARE: 2>
201 >>> Shape.ALIAS_FOR_SQUARE
202 <Shape.SQUARE: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700203 >>> Shape(2)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800204 <Shape.SQUARE: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700205
Ethan Furman101e0742013-09-15 12:34:36 -0700206.. note::
207
208 Attempting to create a member with the same name as an already
209 defined attribute (another member, a method, etc.) or attempting to create
210 an attribute with the same name as a member is not allowed.
211
Ethan Furmanf24bb352013-07-18 17:05:39 -0700212
213Ensuring unique enumeration values
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700214----------------------------------
Ethan Furmanf24bb352013-07-18 17:05:39 -0700215
216By default, enumerations allow multiple names as aliases for the same value.
217When this behavior isn't desired, the following decorator can be used to
218ensure each value is used only once in the enumeration:
219
220.. decorator:: unique
221
222A :keyword:`class` decorator specifically for enumerations. It searches an
223enumeration's :attr:`__members__` gathering any aliases it finds; if any are
224found :exc:`ValueError` is raised with the details::
225
226 >>> from enum import Enum, unique
227 >>> @unique
228 ... class Mistake(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800229 ... ONE = 1
230 ... TWO = 2
231 ... THREE = 3
232 ... FOUR = 3
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700233 ...
Ethan Furmanf24bb352013-07-18 17:05:39 -0700234 Traceback (most recent call last):
235 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800236 ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
Ethan Furmanf24bb352013-07-18 17:05:39 -0700237
238
Ethan Furmanc16595e2016-09-10 23:36:59 -0700239Using automatic values
240----------------------
241
242If the exact value is unimportant you can use :class:`auto`::
243
244 >>> from enum import Enum, auto
245 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800246 ... RED = auto()
247 ... BLUE = auto()
248 ... GREEN = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700249 ...
250 >>> list(Color)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800251 [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
Ethan Furmanc16595e2016-09-10 23:36:59 -0700252
253The values are chosen by :func:`_generate_next_value_`, which can be
254overridden::
255
256 >>> class AutoName(Enum):
257 ... def _generate_next_value_(name, start, count, last_values):
258 ... return name
259 ...
260 >>> class Ordinal(AutoName):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800261 ... NORTH = auto()
262 ... SOUTH = auto()
263 ... EAST = auto()
264 ... WEST = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700265 ...
266 >>> list(Ordinal)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800267 [<Ordinal.NORTH: 'NORTH'>, <Ordinal.SOUTH: 'SOUTH'>, <Ordinal.EAST: 'EAST'>, <Ordinal.WEST: 'WEST'>]
Ethan Furmanc16595e2016-09-10 23:36:59 -0700268
269.. note::
270
271 The goal of the default :meth:`_generate_next_value_` methods is to provide
272 the next :class:`int` in sequence with the last :class:`int` provided, but
273 the way it does this is an implementation detail and may change.
274
Ethan Onstottd9a43e22020-04-28 13:20:55 -0400275.. note::
276
277 The :meth:`_generate_next_value_` method must be defined before any members.
278
Ethan Furmanf24bb352013-07-18 17:05:39 -0700279Iteration
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700280---------
Ethan Furmanf24bb352013-07-18 17:05:39 -0700281
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700282Iterating over the members of an enum does not provide the aliases::
283
284 >>> list(Shape)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800285 [<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700286
INADA Naokie57f91a2018-06-19 01:14:26 +0900287The special attribute ``__members__`` is a read-only ordered mapping of names
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700288to members. It includes all names defined in the enumeration, including the
289aliases::
290
291 >>> for name, member in Shape.__members__.items():
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700292 ... name, member
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700293 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800294 ('SQUARE', <Shape.SQUARE: 2>)
295 ('DIAMOND', <Shape.DIAMOND: 1>)
296 ('CIRCLE', <Shape.CIRCLE: 3>)
297 ('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700298
299The ``__members__`` attribute can be used for detailed programmatic access to
300the enumeration members. For example, finding all the aliases::
301
Ethan Furman332dbc72016-08-20 00:00:52 -0700302 >>> [name for name, member in Shape.__members__.items() if member.name != name]
Ethan Furman23bb6f42016-11-21 09:22:05 -0800303 ['ALIAS_FOR_SQUARE']
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700304
Ethan Furmanf24bb352013-07-18 17:05:39 -0700305
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700306Comparisons
307-----------
308
309Enumeration members are compared by identity::
310
Ethan Furman23bb6f42016-11-21 09:22:05 -0800311 >>> Color.RED is Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700312 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800313 >>> Color.RED is Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700314 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800315 >>> Color.RED is not Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700316 True
317
318Ordered comparisons between enumeration values are *not* supported. Enum
319members are not integers (but see `IntEnum`_ below)::
320
Ethan Furman23bb6f42016-11-21 09:22:05 -0800321 >>> Color.RED < Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700322 Traceback (most recent call last):
323 File "<stdin>", line 1, in <module>
Ethan Furmane8e61272016-08-20 07:19:31 -0700324 TypeError: '<' not supported between instances of 'Color' and 'Color'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700325
326Equality comparisons are defined though::
327
Ethan Furman23bb6f42016-11-21 09:22:05 -0800328 >>> Color.BLUE == Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700329 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800330 >>> Color.BLUE != Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700331 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800332 >>> Color.BLUE == Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700333 True
334
335Comparisons against non-enumeration values will always compare not equal
Ezio Melotti93d7dda2013-10-05 04:13:18 +0300336(again, :class:`IntEnum` was explicitly designed to behave differently, see
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700337below)::
338
Ethan Furman23bb6f42016-11-21 09:22:05 -0800339 >>> Color.BLUE == 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700340 False
341
342
343Allowed members and attributes of enumerations
344----------------------------------------------
345
346The examples above use integers for enumeration values. Using integers is
Ethan Furman332dbc72016-08-20 00:00:52 -0700347short and handy (and provided by default by the `Functional API`_), but not
348strictly enforced. In the vast majority of use-cases, one doesn't care what
349the actual value of an enumeration is. But if the value *is* important,
350enumerations can have arbitrary values.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700351
352Enumerations are Python classes, and can have methods and special methods as
353usual. If we have this enumeration::
354
355 >>> class Mood(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800356 ... FUNKY = 1
357 ... HAPPY = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700358 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700359 ... def describe(self):
360 ... # self is the member here
361 ... return self.name, self.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700362 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700363 ... def __str__(self):
364 ... return 'my custom str! {0}'.format(self.value)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700365 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700366 ... @classmethod
367 ... def favorite_mood(cls):
368 ... # cls here is the enumeration
Ethan Furman23bb6f42016-11-21 09:22:05 -0800369 ... return cls.HAPPY
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700370 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700371
372Then::
373
374 >>> Mood.favorite_mood()
Ethan Furman23bb6f42016-11-21 09:22:05 -0800375 <Mood.HAPPY: 3>
376 >>> Mood.HAPPY.describe()
377 ('HAPPY', 3)
378 >>> str(Mood.FUNKY)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700379 'my custom str! 1'
380
Martin Pantera90a4a92016-05-30 04:04:50 +0000381The rules for what is allowed are as follows: names that start and end with
382a single underscore are reserved by enum and cannot be used; all other
Ethan Furman8be6fac2014-11-01 07:40:22 -0700383attributes defined within an enumeration will become members of this
384enumeration, with the exception of special methods (:meth:`__str__`,
Ethan Furmana4b1bb42018-01-22 07:56:37 -0800385:meth:`__add__`, etc.), descriptors (methods are also descriptors), and
386variable names listed in :attr:`_ignore_`.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700387
388Note: if your enumeration defines :meth:`__new__` and/or :meth:`__init__` then
Antoined3c8d732019-08-20 03:41:31 +0200389any value(s) given to the enum member will be passed into those methods.
390See `Planet`_ for an example.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700391
392
Ethan Furman5bdab642018-09-21 19:03:09 -0700393Restricted Enum subclassing
394---------------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700395
Ethan Furman5bdab642018-09-21 19:03:09 -0700396A new :class:`Enum` class must have one base Enum class, up to one concrete
397data type, and as many :class:`object`-based mixin classes as needed. The
398order of these base classes is::
399
nu_nodfc8bb92019-01-27 23:07:47 +0100400 class EnumName([mix-in, ...,] [data-type,] base-enum):
Ethan Furman5bdab642018-09-21 19:03:09 -0700401 pass
402
403Also, subclassing an enumeration is allowed only if the enumeration does not define
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700404any members. So this is forbidden::
405
406 >>> class MoreColor(Color):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800407 ... PINK = 17
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700408 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700409 Traceback (most recent call last):
410 ...
411 TypeError: Cannot extend enumerations
412
413But this is allowed::
414
415 >>> class Foo(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700416 ... def some_behavior(self):
417 ... pass
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700418 ...
419 >>> class Bar(Foo):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800420 ... HAPPY = 1
421 ... SAD = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700422 ...
423
424Allowing subclassing of enums that define members would lead to a violation of
425some important invariants of types and instances. On the other hand, it makes
426sense to allow sharing some common behavior between a group of enumerations.
427(See `OrderedEnum`_ for an example.)
428
429
430Pickling
431--------
432
433Enumerations can be pickled and unpickled::
434
435 >>> from test.test_enum import Fruit
436 >>> from pickle import dumps, loads
Ethan Furman23bb6f42016-11-21 09:22:05 -0800437 >>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO))
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700438 True
439
440The usual restrictions for pickling apply: picklable enums must be defined in
441the top level of a module, since unpickling requires them to be importable
442from that module.
443
Ethan Furmanca1b7942014-02-08 11:36:27 -0800444.. note::
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700445
Ethan Furmanca1b7942014-02-08 11:36:27 -0800446 With pickle protocol version 4 it is possible to easily pickle enums
447 nested in other classes.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700448
Ethan Furman2da95042014-03-03 12:42:52 -0800449It is possible to modify how Enum members are pickled/unpickled by defining
450:meth:`__reduce_ex__` in the enumeration class.
451
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700452
453Functional API
454--------------
455
456The :class:`Enum` class is callable, providing the following functional API::
457
Ethan Furman23bb6f42016-11-21 09:22:05 -0800458 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG')
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700459 >>> Animal
460 <enum 'Animal'>
Ethan Furman23bb6f42016-11-21 09:22:05 -0800461 >>> Animal.ANT
462 <Animal.ANT: 1>
463 >>> Animal.ANT.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700464 1
465 >>> list(Animal)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800466 [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700467
Ethan Furman332dbc72016-08-20 00:00:52 -0700468The semantics of this API resemble :class:`~collections.namedtuple`. The first
469argument of the call to :class:`Enum` is the name of the enumeration.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700470
Ethan Furman332dbc72016-08-20 00:00:52 -0700471The second argument is the *source* of enumeration member names. It can be a
472whitespace-separated string of names, a sequence of names, a sequence of
4732-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to
474values. The last two options enable assigning arbitrary values to
475enumerations; the others auto-assign increasing integers starting with 1 (use
476the ``start`` parameter to specify a different starting value). A
477new class derived from :class:`Enum` is returned. In other words, the above
478assignment to :class:`Animal` is equivalent to::
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700479
Ethan Furman8a123292015-01-14 22:31:50 -0800480 >>> class Animal(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800481 ... ANT = 1
482 ... BEE = 2
483 ... CAT = 3
484 ... DOG = 4
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700485 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700486
Ethan Furmane2563462013-06-28 19:37:17 -0700487The reason for defaulting to ``1`` as the starting number and not ``0`` is
488that ``0`` is ``False`` in a boolean sense, but enum members all evaluate
489to ``True``.
490
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700491Pickling enums created with the functional API can be tricky as frame stack
492implementation details are used to try and figure out which module the
493enumeration is being created in (e.g. it will fail if you use a utility
Ethan Furman332dbc72016-08-20 00:00:52 -0700494function in separate module, and also may not work on IronPython or Jython).
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700495The solution is to specify the module name explicitly as follows::
496
Ethan Furman23bb6f42016-11-21 09:22:05 -0800497 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700498
Ethan Furman2da95042014-03-03 12:42:52 -0800499.. warning::
500
Ethan Furman01cc2d52014-03-03 15:02:04 -0800501 If ``module`` is not supplied, and Enum cannot determine what it is,
Ethan Furman2da95042014-03-03 12:42:52 -0800502 the new Enum members will not be unpicklable; to keep errors closer to
503 the source, pickling will be disabled.
504
Ethan Furmanca1b7942014-02-08 11:36:27 -0800505The new pickle protocol 4 also, in some circumstances, relies on
Martin Panterbae5d812016-06-18 03:57:31 +0000506:attr:`~definition.__qualname__` being set to the location where pickle will be able
Ethan Furmanca1b7942014-02-08 11:36:27 -0800507to find the class. For example, if the class was made available in class
508SomeData in the global scope::
509
Ethan Furman23bb6f42016-11-21 09:22:05 -0800510 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal')
Ethan Furmanca1b7942014-02-08 11:36:27 -0800511
Ethan Furman2da95042014-03-03 12:42:52 -0800512The complete signature is::
513
Ethan Furman332dbc72016-08-20 00:00:52 -0700514 Enum(value='NewEnumName', names=<...>, *, module='...', qualname='...', type=<mixed-in class>, start=1)
Ethan Furman2da95042014-03-03 12:42:52 -0800515
Ethan Furman01cc2d52014-03-03 15:02:04 -0800516:value: What the new Enum class will record as its name.
Ethan Furman2da95042014-03-03 12:42:52 -0800517
Zachary Waredbd1c432014-03-20 10:01:48 -0500518:names: The Enum members. This can be a whitespace or comma separated string
Ethan Furmand9925a12014-09-16 20:35:55 -0700519 (values will start at 1 unless otherwise specified)::
Ethan Furman2da95042014-03-03 12:42:52 -0800520
Ethan Furman23bb6f42016-11-21 09:22:05 -0800521 'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE'
Ethan Furman2da95042014-03-03 12:42:52 -0800522
Ethan Furman8a123292015-01-14 22:31:50 -0800523 or an iterator of names::
524
Ethan Furman23bb6f42016-11-21 09:22:05 -0800525 ['RED', 'GREEN', 'BLUE']
Ethan Furman8a123292015-01-14 22:31:50 -0800526
Ethan Furman01cc2d52014-03-03 15:02:04 -0800527 or an iterator of (name, value) pairs::
Ethan Furman2da95042014-03-03 12:42:52 -0800528
Ethan Furman23bb6f42016-11-21 09:22:05 -0800529 [('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)]
Ethan Furman2da95042014-03-03 12:42:52 -0800530
Ethan Furman01cc2d52014-03-03 15:02:04 -0800531 or a mapping::
Ethan Furman2da95042014-03-03 12:42:52 -0800532
Ethan Furman23bb6f42016-11-21 09:22:05 -0800533 {'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42}
Ethan Furman2da95042014-03-03 12:42:52 -0800534
Ethan Furman01cc2d52014-03-03 15:02:04 -0800535:module: name of module where new Enum class can be found.
Ethan Furman2da95042014-03-03 12:42:52 -0800536
Ethan Furman01cc2d52014-03-03 15:02:04 -0800537:qualname: where in module new Enum class can be found.
Ethan Furman2da95042014-03-03 12:42:52 -0800538
Ethan Furman01cc2d52014-03-03 15:02:04 -0800539:type: type to mix in to new Enum class.
Ethan Furman2da95042014-03-03 12:42:52 -0800540
Yury Selivanov4dde5872015-09-11 00:48:21 -0400541:start: number to start counting at if only names are passed in.
Ethan Furmand9925a12014-09-16 20:35:55 -0700542
Berker Peksag60efd792014-09-18 05:23:14 +0300543.. versionchanged:: 3.5
544 The *start* parameter was added.
545
Ethan Furmanca1b7942014-02-08 11:36:27 -0800546
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700547Derived Enumerations
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700548--------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700549
550IntEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700551^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700552
Ethan Furman65a5a472016-09-01 23:55:19 -0700553The first variation of :class:`Enum` that is provided is also a subclass of
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700554:class:`int`. Members of an :class:`IntEnum` can be compared to integers;
555by extension, integer enumerations of different types can also be compared
556to each other::
557
558 >>> from enum import IntEnum
559 >>> class Shape(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800560 ... CIRCLE = 1
561 ... SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700562 ...
563 >>> class Request(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800564 ... POST = 1
565 ... GET = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700566 ...
567 >>> Shape == 1
568 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800569 >>> Shape.CIRCLE == 1
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700570 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800571 >>> Shape.CIRCLE == Request.POST
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700572 True
573
574However, they still can't be compared to standard :class:`Enum` enumerations::
575
576 >>> class Shape(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800577 ... CIRCLE = 1
578 ... SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700579 ...
580 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800581 ... RED = 1
582 ... GREEN = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700583 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800584 >>> Shape.CIRCLE == Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700585 False
586
587:class:`IntEnum` values behave like integers in other ways you'd expect::
588
Ethan Furman23bb6f42016-11-21 09:22:05 -0800589 >>> int(Shape.CIRCLE)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700590 1
Ethan Furman23bb6f42016-11-21 09:22:05 -0800591 >>> ['a', 'b', 'c'][Shape.CIRCLE]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700592 'b'
Ethan Furman23bb6f42016-11-21 09:22:05 -0800593 >>> [i for i in range(Shape.SQUARE)]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700594 [0, 1]
595
Ethan Furman65a5a472016-09-01 23:55:19 -0700596
597IntFlag
598^^^^^^^
599
600The next variation of :class:`Enum` provided, :class:`IntFlag`, is also based
601on :class:`int`. The difference being :class:`IntFlag` members can be combined
602using the bitwise operators (&, \|, ^, ~) and the result is still an
603:class:`IntFlag` member. However, as the name implies, :class:`IntFlag`
Ethan Furman54924df2016-09-07 23:40:31 -0700604members also subclass :class:`int` and can be used wherever an :class:`int` is
605used. Any operation on an :class:`IntFlag` member besides the bit-wise
606operations will lose the :class:`IntFlag` membership.
Ethan Furman65a5a472016-09-01 23:55:19 -0700607
Ethan Furman25d94bb2016-09-02 16:32:32 -0700608.. versionadded:: 3.6
609
610Sample :class:`IntFlag` class::
611
Ethan Furman65a5a472016-09-01 23:55:19 -0700612 >>> from enum import IntFlag
613 >>> class Perm(IntFlag):
614 ... R = 4
615 ... W = 2
616 ... X = 1
617 ...
618 >>> Perm.R | Perm.W
619 <Perm.R|W: 6>
620 >>> Perm.R + Perm.W
621 6
622 >>> RW = Perm.R | Perm.W
623 >>> Perm.R in RW
624 True
625
Ethan Furman25d94bb2016-09-02 16:32:32 -0700626It is also possible to name the combinations::
627
628 >>> class Perm(IntFlag):
629 ... R = 4
630 ... W = 2
631 ... X = 1
632 ... RWX = 7
633 >>> Perm.RWX
634 <Perm.RWX: 7>
635 >>> ~Perm.RWX
Ethan Furman27682d22016-09-04 11:39:01 -0700636 <Perm.-8: -8>
Ethan Furman25d94bb2016-09-02 16:32:32 -0700637
638Another important difference between :class:`IntFlag` and :class:`Enum` is that
639if no flags are set (the value is 0), its boolean evaluation is :data:`False`::
640
641 >>> Perm.R & Perm.X
642 <Perm.0: 0>
643 >>> bool(Perm.R & Perm.X)
644 False
645
646Because :class:`IntFlag` members are also subclasses of :class:`int` they can
647be combined with them::
648
649 >>> Perm.X | 8
650 <Perm.8|X: 9>
Ethan Furman65a5a472016-09-01 23:55:19 -0700651
652
653Flag
654^^^^
655
656The last variation is :class:`Flag`. Like :class:`IntFlag`, :class:`Flag`
Ethan Furman25d94bb2016-09-02 16:32:32 -0700657members can be combined using the bitwise operators (&, \|, ^, ~). Unlike
Ethan Furman65a5a472016-09-01 23:55:19 -0700658:class:`IntFlag`, they cannot be combined with, nor compared against, any
Ethan Furmanc16595e2016-09-10 23:36:59 -0700659other :class:`Flag` enumeration, nor :class:`int`. While it is possible to
660specify the values directly it is recommended to use :class:`auto` as the
661value and let :class:`Flag` select an appropriate value.
Ethan Furman65a5a472016-09-01 23:55:19 -0700662
663.. versionadded:: 3.6
664
Ethan Furman25d94bb2016-09-02 16:32:32 -0700665Like :class:`IntFlag`, if a combination of :class:`Flag` members results in no
666flags being set, the boolean evaluation is :data:`False`::
667
Julian Kahnert0f31c742018-01-13 04:35:57 +0100668 >>> from enum import Flag, auto
Ethan Furman25d94bb2016-09-02 16:32:32 -0700669 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800670 ... RED = auto()
671 ... BLUE = auto()
672 ... GREEN = auto()
Ethan Furman25d94bb2016-09-02 16:32:32 -0700673 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800674 >>> Color.RED & Color.GREEN
Ethan Furman25d94bb2016-09-02 16:32:32 -0700675 <Color.0: 0>
Ethan Furman23bb6f42016-11-21 09:22:05 -0800676 >>> bool(Color.RED & Color.GREEN)
Ethan Furman25d94bb2016-09-02 16:32:32 -0700677 False
678
Ethan Furman27682d22016-09-04 11:39:01 -0700679Individual flags should have values that are powers of two (1, 2, 4, 8, ...),
680while combinations of flags won't::
681
682 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800683 ... RED = auto()
684 ... BLUE = auto()
685 ... GREEN = auto()
686 ... WHITE = RED | BLUE | GREEN
Ethan Furmanc16595e2016-09-10 23:36:59 -0700687 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800688 >>> Color.WHITE
689 <Color.WHITE: 7>
Ethan Furman27682d22016-09-04 11:39:01 -0700690
Ethan Furman25d94bb2016-09-02 16:32:32 -0700691Giving a name to the "no flags set" condition does not change its boolean
692value::
693
694 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800695 ... BLACK = 0
696 ... RED = auto()
697 ... BLUE = auto()
698 ... GREEN = auto()
Ethan Furman25d94bb2016-09-02 16:32:32 -0700699 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800700 >>> Color.BLACK
701 <Color.BLACK: 0>
702 >>> bool(Color.BLACK)
Ethan Furman25d94bb2016-09-02 16:32:32 -0700703 False
704
Ethan Furman65a5a472016-09-01 23:55:19 -0700705.. note::
706
707 For the majority of new code, :class:`Enum` and :class:`Flag` are strongly
708 recommended, since :class:`IntEnum` and :class:`IntFlag` break some
709 semantic promises of an enumeration (by being comparable to integers, and
710 thus by transitivity to other unrelated enumerations). :class:`IntEnum`
711 and :class:`IntFlag` should be used only in cases where :class:`Enum` and
712 :class:`Flag` will not do; for example, when integer constants are replaced
713 with enumerations, or for interoperability with other systems.
Ethan Furman332dbc72016-08-20 00:00:52 -0700714
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700715
716Others
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700717^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700718
719While :class:`IntEnum` is part of the :mod:`enum` module, it would be very
720simple to implement independently::
721
722 class IntEnum(int, Enum):
723 pass
724
725This demonstrates how similar derived enumerations can be defined; for example
Ethan Furman332dbc72016-08-20 00:00:52 -0700726a :class:`StrEnum` that mixes in :class:`str` instead of :class:`int`.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700727
728Some rules:
729
7301. When subclassing :class:`Enum`, mix-in types must appear before
731 :class:`Enum` itself in the sequence of bases, as in the :class:`IntEnum`
732 example above.
7332. While :class:`Enum` can have members of any type, once you mix in an
734 additional type, all the members must have values of that type, e.g.
735 :class:`int` above. This restriction does not apply to mix-ins which only
Antoined3c8d732019-08-20 03:41:31 +0200736 add methods and don't specify another type.
Ethan Furman6b3d64a2013-06-14 16:55:46 -07007373. When another data type is mixed in, the :attr:`value` attribute is *not the
Zachary Waredbd1c432014-03-20 10:01:48 -0500738 same* as the enum member itself, although it is equivalent and will compare
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700739 equal.
Martin Panterd5db1472016-02-08 01:34:09 +00007404. %-style formatting: `%s` and `%r` call the :class:`Enum` class's
741 :meth:`__str__` and :meth:`__repr__` respectively; other codes (such as
742 `%i` or `%h` for IntEnum) treat the enum member as its mixed-in type.
Martin Panterbc1ee462016-02-13 00:41:37 +00007435. :ref:`Formatted string literals <f-strings>`, :meth:`str.format`,
thatneat2f19e822019-07-04 11:28:37 -0700744 and :func:`format` will use the mixed-in type's :meth:`__format__`
745 unless :meth:`__str__` or :meth:`__format__` is overridden in the subclass,
746 in which case the overridden methods or :class:`Enum` methods will be used.
747 Use the !s and !r format codes to force usage of the :class:`Enum` class's
748 :meth:`__str__` and :meth:`__repr__` methods.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700749
Ethan Furmanf5223742018-09-12 10:00:30 -0700750When to use :meth:`__new__` vs. :meth:`__init__`
751------------------------------------------------
752
753:meth:`__new__` must be used whenever you want to customize the actual value of
754the :class:`Enum` member. Any other modifications may go in either
755:meth:`__new__` or :meth:`__init__`, with :meth:`__init__` being preferred.
756
757For example, if you want to pass several items to the constructor, but only
758want one of them to be the value::
759
760 >>> class Coordinate(bytes, Enum):
761 ... """
762 ... Coordinate with binary codes that can be indexed by the int code.
763 ... """
764 ... def __new__(cls, value, label, unit):
765 ... obj = bytes.__new__(cls, [value])
766 ... obj._value_ = value
767 ... obj.label = label
768 ... obj.unit = unit
769 ... return obj
770 ... PX = (0, 'P.X', 'km')
771 ... PY = (1, 'P.Y', 'km')
772 ... VX = (2, 'V.X', 'km/s')
773 ... VY = (3, 'V.Y', 'km/s')
774 ...
775
776 >>> print(Coordinate['PY'])
777 Coordinate.PY
778
779 >>> print(Coordinate(3))
780 Coordinate.VY
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700781
782Interesting examples
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700783--------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700784
Ethan Furman65a5a472016-09-01 23:55:19 -0700785While :class:`Enum`, :class:`IntEnum`, :class:`IntFlag`, and :class:`Flag` are
786expected to cover the majority of use-cases, they cannot cover them all. Here
787are recipes for some different types of enumerations that can be used directly,
788or as examples for creating one's own.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700789
790
Ethan Furman6a137e82016-09-07 08:17:15 -0700791Omitting values
792^^^^^^^^^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700793
Ethan Furman6a137e82016-09-07 08:17:15 -0700794In many use-cases one doesn't care what the actual value of an enumeration
795is. There are several ways to define this type of simple enumeration:
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700796
Ethan Furmanc16595e2016-09-10 23:36:59 -0700797- use instances of :class:`auto` for the value
Ethan Furman6a137e82016-09-07 08:17:15 -0700798- use instances of :class:`object` as the value
799- use a descriptive string as the value
800- use a tuple as the value and a custom :meth:`__new__` to replace the
801 tuple with an :class:`int` value
802
803Using any of these methods signifies to the user that these values are not
804important, and also enables one to add, remove, or reorder members without
805having to renumber the remaining members.
806
807Whichever method you choose, you should provide a :meth:`repr` that also hides
808the (unimportant) value::
809
810 >>> class NoValue(Enum):
811 ... def __repr__(self):
812 ... return '<%s.%s>' % (self.__class__.__name__, self.name)
813 ...
814
815
Ethan Furmanc16595e2016-09-10 23:36:59 -0700816Using :class:`auto`
817"""""""""""""""""""
818
Berker Peksag2a267a12017-01-02 05:51:04 +0300819Using :class:`auto` would look like::
Ethan Furmanc16595e2016-09-10 23:36:59 -0700820
821 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800822 ... RED = auto()
823 ... BLUE = auto()
824 ... GREEN = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700825 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800826 >>> Color.GREEN
827 <Color.GREEN>
Ethan Furmanc16595e2016-09-10 23:36:59 -0700828
829
Ethan Furman6a137e82016-09-07 08:17:15 -0700830Using :class:`object`
831"""""""""""""""""""""
832
833Using :class:`object` would look like::
834
835 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800836 ... RED = object()
837 ... GREEN = object()
838 ... BLUE = object()
Ethan Furman6a137e82016-09-07 08:17:15 -0700839 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800840 >>> Color.GREEN
841 <Color.GREEN>
Ethan Furman6a137e82016-09-07 08:17:15 -0700842
843
844Using a descriptive string
845""""""""""""""""""""""""""
846
847Using a string as the value would look like::
848
849 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800850 ... RED = 'stop'
851 ... GREEN = 'go'
852 ... BLUE = 'too fast!'
Ethan Furman6a137e82016-09-07 08:17:15 -0700853 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800854 >>> Color.GREEN
855 <Color.GREEN>
856 >>> Color.GREEN.value
Ethan Furman6a137e82016-09-07 08:17:15 -0700857 'go'
858
859
860Using a custom :meth:`__new__`
861""""""""""""""""""""""""""""""
862
863Using an auto-numbering :meth:`__new__` would look like::
864
865 >>> class AutoNumber(NoValue):
Ethan Furman332dbc72016-08-20 00:00:52 -0700866 ... def __new__(cls):
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700867 ... value = len(cls.__members__) + 1
868 ... obj = object.__new__(cls)
Ethan Furman90262622013-07-30 12:24:25 -0700869 ... obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700870 ... return obj
871 ...
Ethan Furman332dbc72016-08-20 00:00:52 -0700872 >>> class Color(AutoNumber):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800873 ... RED = ()
874 ... GREEN = ()
875 ... BLUE = ()
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700876 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800877 >>> Color.GREEN
878 <Color.GREEN>
879 >>> Color.GREEN.value
Ethan Furman6a137e82016-09-07 08:17:15 -0700880 2
881
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700882
Ethan Furman9a1daf52013-09-27 22:58:06 -0700883.. note::
884
885 The :meth:`__new__` method, if defined, is used during creation of the Enum
886 members; it is then replaced by Enum's :meth:`__new__` which is used after
Ethan Furmanf75805e2014-09-16 19:13:31 -0700887 class creation for lookup of existing members.
Ethan Furman9a1daf52013-09-27 22:58:06 -0700888
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700889
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700890OrderedEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700891^^^^^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700892
893An ordered enumeration that is not based on :class:`IntEnum` and so maintains
894the normal :class:`Enum` invariants (such as not being comparable to other
895enumerations)::
896
897 >>> class OrderedEnum(Enum):
898 ... def __ge__(self, other):
899 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700900 ... return self.value >= other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700901 ... return NotImplemented
902 ... def __gt__(self, other):
903 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700904 ... return self.value > other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700905 ... return NotImplemented
906 ... def __le__(self, other):
907 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700908 ... return self.value <= other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700909 ... return NotImplemented
910 ... def __lt__(self, other):
911 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -0700912 ... return self.value < other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700913 ... return NotImplemented
914 ...
915 >>> class Grade(OrderedEnum):
916 ... A = 5
917 ... B = 4
918 ... C = 3
919 ... D = 2
920 ... F = 1
921 ...
922 >>> Grade.C < Grade.A
923 True
924
925
Ethan Furmanf24bb352013-07-18 17:05:39 -0700926DuplicateFreeEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700927^^^^^^^^^^^^^^^^^
Ethan Furmanf24bb352013-07-18 17:05:39 -0700928
929Raises an error if a duplicate member name is found instead of creating an
930alias::
931
932 >>> class DuplicateFreeEnum(Enum):
933 ... def __init__(self, *args):
934 ... cls = self.__class__
935 ... if any(self.value == e.value for e in cls):
936 ... a = self.name
937 ... e = cls(self.value).name
938 ... raise ValueError(
939 ... "aliases not allowed in DuplicateFreeEnum: %r --> %r"
940 ... % (a, e))
941 ...
942 >>> class Color(DuplicateFreeEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800943 ... RED = 1
944 ... GREEN = 2
945 ... BLUE = 3
946 ... GRENE = 2
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700947 ...
Ethan Furmanf24bb352013-07-18 17:05:39 -0700948 Traceback (most recent call last):
949 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800950 ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN'
Ethan Furmanf24bb352013-07-18 17:05:39 -0700951
952.. note::
953
954 This is a useful example for subclassing Enum to add or change other
Ezio Melotti93d7dda2013-10-05 04:13:18 +0300955 behaviors as well as disallowing aliases. If the only desired change is
Ezio Melotti17f1edd2013-10-05 04:26:06 +0300956 disallowing aliases, the :func:`unique` decorator can be used instead.
Ethan Furmanf24bb352013-07-18 17:05:39 -0700957
958
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700959Planet
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700960^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700961
962If :meth:`__new__` or :meth:`__init__` is defined the value of the enum member
963will be passed to those methods::
964
965 >>> class Planet(Enum):
966 ... MERCURY = (3.303e+23, 2.4397e6)
967 ... VENUS = (4.869e+24, 6.0518e6)
968 ... EARTH = (5.976e+24, 6.37814e6)
969 ... MARS = (6.421e+23, 3.3972e6)
970 ... JUPITER = (1.9e+27, 7.1492e7)
971 ... SATURN = (5.688e+26, 6.0268e7)
972 ... URANUS = (8.686e+25, 2.5559e7)
973 ... NEPTUNE = (1.024e+26, 2.4746e7)
974 ... def __init__(self, mass, radius):
975 ... self.mass = mass # in kilograms
976 ... self.radius = radius # in meters
977 ... @property
978 ... def surface_gravity(self):
979 ... # universal gravitational constant (m3 kg-1 s-2)
980 ... G = 6.67300E-11
981 ... return G * self.mass / (self.radius * self.radius)
982 ...
983 >>> Planet.EARTH.value
984 (5.976e+24, 6378140.0)
985 >>> Planet.EARTH.surface_gravity
986 9.802652743337129
Ethan Furman9a1daf52013-09-27 22:58:06 -0700987
988
Ethan Furmana4b1bb42018-01-22 07:56:37 -0800989TimePeriod
990^^^^^^^^^^
991
992An example to show the :attr:`_ignore_` attribute in use::
993
994 >>> from datetime import timedelta
995 >>> class Period(timedelta, Enum):
996 ... "different lengths of time"
997 ... _ignore_ = 'Period i'
998 ... Period = vars()
999 ... for i in range(367):
1000 ... Period['day_%d' % i] = i
1001 ...
1002 >>> list(Period)[:2]
1003 [<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>]
1004 >>> list(Period)[-2:]
1005 [<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>]
1006
1007
Ethan Furman9a1daf52013-09-27 22:58:06 -07001008How are Enums different?
1009------------------------
1010
1011Enums have a custom metaclass that affects many aspects of both derived Enum
1012classes and their instances (members).
1013
1014
1015Enum Classes
1016^^^^^^^^^^^^
1017
1018The :class:`EnumMeta` metaclass is responsible for providing the
1019:meth:`__contains__`, :meth:`__dir__`, :meth:`__iter__` and other methods that
1020allow one to do things with an :class:`Enum` class that fail on a typical
Rahul Jha94306522018-09-10 23:51:04 +05301021class, such as `list(Color)` or `some_enum_var in Color`. :class:`EnumMeta` is
Ethan Furman9a1daf52013-09-27 22:58:06 -07001022responsible for ensuring that various other methods on the final :class:`Enum`
1023class are correct (such as :meth:`__new__`, :meth:`__getnewargs__`,
Martin Panterd21e0b52015-10-10 10:36:22 +00001024:meth:`__str__` and :meth:`__repr__`).
Ethan Furman9a1daf52013-09-27 22:58:06 -07001025
1026
1027Enum Members (aka instances)
1028^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1029
1030The most interesting thing about Enum members is that they are singletons.
1031:class:`EnumMeta` creates them all while it is creating the :class:`Enum`
1032class itself, and then puts a custom :meth:`__new__` in place to ensure
1033that no new ones are ever instantiated by returning only the existing
1034member instances.
1035
1036
1037Finer Points
1038^^^^^^^^^^^^
1039
Ethan Furman65a5a472016-09-01 23:55:19 -07001040Supported ``__dunder__`` names
Ethan Furman6a137e82016-09-07 08:17:15 -07001041""""""""""""""""""""""""""""""
Ethan Furman9a1daf52013-09-27 22:58:06 -07001042
INADA Naokie57f91a2018-06-19 01:14:26 +09001043:attr:`__members__` is a read-only ordered mapping of ``member_name``:``member``
Ethan Furman65a5a472016-09-01 23:55:19 -07001044items. It is only available on the class.
Ethan Furman9a1daf52013-09-27 22:58:06 -07001045
Ethan Furman65a5a472016-09-01 23:55:19 -07001046:meth:`__new__`, if specified, must create and return the enum members; it is
1047also a very good idea to set the member's :attr:`_value_` appropriately. Once
1048all the members are created it is no longer used.
Ethan Furman748dad52015-11-20 13:12:26 -08001049
Ethan Furman60255b62016-01-15 15:01:33 -08001050
Ethan Furman65a5a472016-09-01 23:55:19 -07001051Supported ``_sunder_`` names
Ethan Furman6a137e82016-09-07 08:17:15 -07001052""""""""""""""""""""""""""""
Ethan Furman60255b62016-01-15 15:01:33 -08001053
Ethan Furman65a5a472016-09-01 23:55:19 -07001054- ``_name_`` -- name of the member
1055- ``_value_`` -- value of the member; can be set / modified in ``__new__``
Ethan Furman9a1daf52013-09-27 22:58:06 -07001056
Ethan Furman65a5a472016-09-01 23:55:19 -07001057- ``_missing_`` -- a lookup function used when a value is not found; may be
1058 overridden
Antoined3c8d732019-08-20 03:41:31 +02001059- ``_ignore_`` -- a list of names, either as a :class:`list` or a :class:`str`,
Ethan Furmana4b1bb42018-01-22 07:56:37 -08001060 that will not be transformed into members, and will be removed from the final
1061 class
Ethan Furman65a5a472016-09-01 23:55:19 -07001062- ``_order_`` -- used in Python 2/3 code to ensure member order is consistent
1063 (class attribute, removed during class creation)
Ethan Furmanc16595e2016-09-10 23:36:59 -07001064- ``_generate_next_value_`` -- used by the `Functional API`_ and by
1065 :class:`auto` to get an appropriate value for an enum member; may be
1066 overridden
Ethan Furman9a1daf52013-09-27 22:58:06 -07001067
Ethan Furmanc16595e2016-09-10 23:36:59 -07001068.. versionadded:: 3.6 ``_missing_``, ``_order_``, ``_generate_next_value_``
Ethan Furmana4b1bb42018-01-22 07:56:37 -08001069.. versionadded:: 3.7 ``_ignore_``
Ethan Furman332dbc72016-08-20 00:00:52 -07001070
Ethan Furman65a5a472016-09-01 23:55:19 -07001071To help keep Python 2 / Python 3 code in sync an :attr:`_order_` attribute can
1072be provided. It will be checked against the actual order of the enumeration
1073and raise an error if the two do not match::
Ethan Furmane8e61272016-08-20 07:19:31 -07001074
1075 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -08001076 ... _order_ = 'RED GREEN BLUE'
1077 ... RED = 1
1078 ... BLUE = 3
1079 ... GREEN = 2
Ethan Furmane8e61272016-08-20 07:19:31 -07001080 ...
1081 Traceback (most recent call last):
1082 ...
1083 TypeError: member order does not match _order_
1084
1085.. note::
1086
1087 In Python 2 code the :attr:`_order_` attribute is necessary as definition
Ethan Furman65a5a472016-09-01 23:55:19 -07001088 order is lost before it can be recorded.
1089
1090``Enum`` member type
Ethan Furman6a137e82016-09-07 08:17:15 -07001091""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001092
Ethan Furman54924df2016-09-07 23:40:31 -07001093:class:`Enum` members are instances of their :class:`Enum` class, and are
1094normally accessed as ``EnumClass.member``. Under certain circumstances they
1095can also be accessed as ``EnumClass.member.member``, but you should never do
1096this as that lookup may fail or, worse, return something besides the
Ethan Furman23bb6f42016-11-21 09:22:05 -08001097:class:`Enum` member you are looking for (this is another good reason to use
1098all-uppercase names for members)::
Ethan Furman65a5a472016-09-01 23:55:19 -07001099
1100 >>> class FieldTypes(Enum):
1101 ... name = 0
1102 ... value = 1
1103 ... size = 2
1104 ...
1105 >>> FieldTypes.value.size
1106 <FieldTypes.size: 2>
1107 >>> FieldTypes.size.value
1108 2
1109
1110.. versionchanged:: 3.5
1111
1112
1113Boolean value of ``Enum`` classes and members
Ethan Furman6a137e82016-09-07 08:17:15 -07001114"""""""""""""""""""""""""""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001115
Ethan Furman54924df2016-09-07 23:40:31 -07001116:class:`Enum` members that are mixed with non-:class:`Enum` types (such as
Ethan Furman65a5a472016-09-01 23:55:19 -07001117:class:`int`, :class:`str`, etc.) are evaluated according to the mixed-in
Ethan Furman54924df2016-09-07 23:40:31 -07001118type's rules; otherwise, all members evaluate as :data:`True`. To make your
1119own Enum's boolean evaluation depend on the member's value add the following to
Ethan Furman65a5a472016-09-01 23:55:19 -07001120your class::
1121
1122 def __bool__(self):
1123 return bool(self.value)
1124
Ethan Furman54924df2016-09-07 23:40:31 -07001125:class:`Enum` classes always evaluate as :data:`True`.
Ethan Furman65a5a472016-09-01 23:55:19 -07001126
1127
1128``Enum`` classes with methods
Ethan Furman6a137e82016-09-07 08:17:15 -07001129"""""""""""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001130
1131If you give your :class:`Enum` subclass extra methods, like the `Planet`_
1132class above, those methods will show up in a :func:`dir` of the member,
1133but not of the class::
1134
1135 >>> dir(Planet)
1136 ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__']
1137 >>> dir(Planet.EARTH)
1138 ['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value']
1139
Ethan Furman3515dcc2016-09-18 13:15:41 -07001140
1141Combining members of ``Flag``
1142"""""""""""""""""""""""""""""
1143
1144If a combination of Flag members is not named, the :func:`repr` will include
1145all named flags and all named combinations of flags that are in the value::
1146
1147 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -08001148 ... RED = auto()
1149 ... GREEN = auto()
1150 ... BLUE = auto()
1151 ... MAGENTA = RED | BLUE
1152 ... YELLOW = RED | GREEN
1153 ... CYAN = GREEN | BLUE
Ethan Furman3515dcc2016-09-18 13:15:41 -07001154 ...
1155 >>> Color(3) # named combination
Ethan Furman23bb6f42016-11-21 09:22:05 -08001156 <Color.YELLOW: 3>
Ethan Furman3515dcc2016-09-18 13:15:41 -07001157 >>> Color(7) # not named combination
Ethan Furman23bb6f42016-11-21 09:22:05 -08001158 <Color.CYAN|MAGENTA|BLUE|YELLOW|GREEN|RED: 7>
Ethan Furman3515dcc2016-09-18 13:15:41 -07001159