blob: b27c5527c7f7c4386e897b89bff12a3ae7f84fc9 [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
Ethan Furman542e1df2020-09-14 13:32:44 -070022.. note:: Case of Enum Members
23
24 Because Enums are used to represent constants we recommend using
25 UPPER_CASE names for enum members, and will be using that style
26 in our examples.
27
Ethan Furmanc72e6382014-02-06 08:13:14 -080028
29Module Contents
30---------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -070031
Ethan Furman65a5a472016-09-01 23:55:19 -070032This module defines four enumeration classes that can be used to define unique
Kartik Anand62658422017-03-01 01:37:19 +053033sets of names and values: :class:`Enum`, :class:`IntEnum`, :class:`Flag`, and
34:class:`IntFlag`. It also defines one decorator, :func:`unique`, and one
Ethan Furmanc16595e2016-09-10 23:36:59 -070035helper, :class:`auto`.
Ethan Furmanc72e6382014-02-06 08:13:14 -080036
37.. class:: Enum
38
39 Base class for creating enumerated constants. See section
Larry Hastingsad88d7a2014-02-10 04:26:10 -080040 `Functional API`_ for an alternate construction syntax.
Ethan Furmanc72e6382014-02-06 08:13:14 -080041
42.. class:: IntEnum
43
44 Base class for creating enumerated constants that are also
45 subclasses of :class:`int`.
46
Ethan Furman0063ff42020-09-21 17:23:13 -070047.. class:: StrEnum
48
49 Base class for creating enumerated constants that are also
50 subclasses of :class:`str`.
51
Ethan Furman65a5a472016-09-01 23:55:19 -070052.. class:: IntFlag
53
54 Base class for creating enumerated constants that can be combined using
55 the bitwise operators without losing their :class:`IntFlag` membership.
56 :class:`IntFlag` members are also subclasses of :class:`int`.
57
58.. class:: Flag
59
60 Base class for creating enumerated constants that can be combined using
61 the bitwise operations without losing their :class:`Flag` membership.
62
Ethan Furmanc72e6382014-02-06 08:13:14 -080063.. function:: unique
Andre Delfino96a09df2020-12-17 14:25:55 -030064 :noindex:
Ethan Furmanc72e6382014-02-06 08:13:14 -080065
66 Enum class decorator that ensures only one name is bound to any one value.
Ethan Furmanf24bb352013-07-18 17:05:39 -070067
Ethan Furmanc16595e2016-09-10 23:36:59 -070068.. class:: auto
69
Ethan Furmanefb13be2020-12-10 12:20:06 -080070 Instances are replaced with an appropriate value for Enum members.
71 :class:`StrEnum` defaults to the lower-cased version of the member name,
72 while other Enums default to 1 and increase from there.
Ethan Furmanc16595e2016-09-10 23:36:59 -070073
74.. versionadded:: 3.6 ``Flag``, ``IntFlag``, ``auto``
Ethan Furmanefb13be2020-12-10 12:20:06 -080075.. versionadded:: 3.10 ``StrEnum``
Ethan Furman6b3d64a2013-06-14 16:55:46 -070076
77Creating an Enum
78----------------
79
80Enumerations are created using the :keyword:`class` syntax, which makes them
81easy to read and write. An alternative creation method is described in
Ethan Furman332dbc72016-08-20 00:00:52 -070082`Functional API`_. To define an enumeration, subclass :class:`Enum` as
83follows::
Ethan Furman6b3d64a2013-06-14 16:55:46 -070084
Ethan Furman332dbc72016-08-20 00:00:52 -070085 >>> from enum import Enum
86 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -080087 ... RED = 1
88 ... GREEN = 2
89 ... BLUE = 3
Ethan Furmaned0bf8a2013-09-06 19:53:30 -070090 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -070091
Ethan Furmanc16595e2016-09-10 23:36:59 -070092.. note:: Enum member values
93
94 Member values can be anything: :class:`int`, :class:`str`, etc.. If
95 the exact value is unimportant you may use :class:`auto` instances and an
96 appropriate value will be chosen for you. Care must be taken if you mix
97 :class:`auto` with other values.
98
Ethan Furman455bfde2013-09-08 23:48:34 -070099.. note:: Nomenclature
100
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700101 - The class :class:`Color` is an *enumeration* (or *enum*)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800102 - The attributes :attr:`Color.RED`, :attr:`Color.GREEN`, etc., are
103 *enumeration members* (or *enum members*) and are functionally constants.
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700104 - The enum members have *names* and *values* (the name of
Ethan Furman23bb6f42016-11-21 09:22:05 -0800105 :attr:`Color.RED` is ``RED``, the value of :attr:`Color.BLUE` is
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700106 ``3``, etc.)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700107
Ethan Furman9a1daf52013-09-27 22:58:06 -0700108.. note::
109
110 Even though we use the :keyword:`class` syntax to create Enums, Enums
111 are not normal Python classes. See `How are Enums different?`_ for
112 more details.
113
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700114Enumeration members have human readable string representations::
115
Ethan Furman23bb6f42016-11-21 09:22:05 -0800116 >>> print(Color.RED)
117 Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700118
119...while their ``repr`` has more information::
120
Ethan Furman23bb6f42016-11-21 09:22:05 -0800121 >>> print(repr(Color.RED))
122 <Color.RED: 1>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700123
124The *type* of an enumeration member is the enumeration it belongs to::
125
Ethan Furman23bb6f42016-11-21 09:22:05 -0800126 >>> type(Color.RED)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700127 <enum 'Color'>
Ethan Furman23bb6f42016-11-21 09:22:05 -0800128 >>> isinstance(Color.GREEN, Color)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700129 True
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700130
131Enum members also have a property that contains just their item name::
132
Ethan Furman23bb6f42016-11-21 09:22:05 -0800133 >>> print(Color.RED.name)
134 RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700135
136Enumerations support iteration, in definition order::
137
138 >>> class Shake(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800139 ... VANILLA = 7
140 ... CHOCOLATE = 4
141 ... COOKIES = 9
142 ... MINT = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700143 ...
144 >>> for shake in Shake:
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700145 ... print(shake)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700146 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800147 Shake.VANILLA
148 Shake.CHOCOLATE
149 Shake.COOKIES
150 Shake.MINT
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700151
152Enumeration members are hashable, so they can be used in dictionaries and sets::
153
154 >>> apples = {}
Ethan Furman23bb6f42016-11-21 09:22:05 -0800155 >>> apples[Color.RED] = 'red delicious'
156 >>> apples[Color.GREEN] = 'granny smith'
157 >>> apples == {Color.RED: 'red delicious', Color.GREEN: 'granny smith'}
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700158 True
159
160
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700161Programmatic access to enumeration members and their attributes
162---------------------------------------------------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700163
164Sometimes it's useful to access members in enumerations programmatically (i.e.
Ethan Furman23bb6f42016-11-21 09:22:05 -0800165situations where ``Color.RED`` won't do because the exact color is not known
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700166at program-writing time). ``Enum`` allows such access::
167
168 >>> Color(1)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800169 <Color.RED: 1>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700170 >>> Color(3)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800171 <Color.BLUE: 3>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700172
173If you want to access enum members by *name*, use item access::
174
Ethan Furman23bb6f42016-11-21 09:22:05 -0800175 >>> Color['RED']
176 <Color.RED: 1>
177 >>> Color['GREEN']
178 <Color.GREEN: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700179
Larry Hastings3732ed22014-03-15 21:13:56 -0700180If you have an enum member and need its :attr:`name` or :attr:`value`::
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700181
Ethan Furman23bb6f42016-11-21 09:22:05 -0800182 >>> member = Color.RED
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700183 >>> member.name
Ethan Furman23bb6f42016-11-21 09:22:05 -0800184 'RED'
Ethan Furman3fe70b4a2013-06-28 14:02:34 -0700185 >>> member.value
186 1
187
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700188
189Duplicating enum members and values
190-----------------------------------
191
192Having two enum members with the same name is invalid::
193
194 >>> class Shape(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800195 ... SQUARE = 2
196 ... SQUARE = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700197 ...
198 Traceback (most recent call last):
199 ...
Ethan Furman7aaeb2a2021-01-25 14:26:19 -0800200 TypeError: 'SQUARE' already defined as: 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700201
202However, two enum members are allowed to have the same value. Given two members
203A and B with the same value (and A defined first), B is an alias to A. By-value
204lookup of the value of A and B will return A. By-name lookup of B will also
205return A::
206
207 >>> class Shape(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800208 ... SQUARE = 2
209 ... DIAMOND = 1
210 ... CIRCLE = 3
211 ... ALIAS_FOR_SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700212 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800213 >>> Shape.SQUARE
214 <Shape.SQUARE: 2>
215 >>> Shape.ALIAS_FOR_SQUARE
216 <Shape.SQUARE: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700217 >>> Shape(2)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800218 <Shape.SQUARE: 2>
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700219
Ethan Furman101e0742013-09-15 12:34:36 -0700220.. note::
221
222 Attempting to create a member with the same name as an already
223 defined attribute (another member, a method, etc.) or attempting to create
224 an attribute with the same name as a member is not allowed.
225
Ethan Furmanf24bb352013-07-18 17:05:39 -0700226
227Ensuring unique enumeration values
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700228----------------------------------
Ethan Furmanf24bb352013-07-18 17:05:39 -0700229
230By default, enumerations allow multiple names as aliases for the same value.
231When this behavior isn't desired, the following decorator can be used to
232ensure each value is used only once in the enumeration:
233
234.. decorator:: unique
235
236A :keyword:`class` decorator specifically for enumerations. It searches an
237enumeration's :attr:`__members__` gathering any aliases it finds; if any are
238found :exc:`ValueError` is raised with the details::
239
240 >>> from enum import Enum, unique
241 >>> @unique
242 ... class Mistake(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800243 ... ONE = 1
244 ... TWO = 2
245 ... THREE = 3
246 ... FOUR = 3
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700247 ...
Ethan Furmanf24bb352013-07-18 17:05:39 -0700248 Traceback (most recent call last):
249 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800250 ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
Ethan Furmanf24bb352013-07-18 17:05:39 -0700251
252
Ethan Furmanc16595e2016-09-10 23:36:59 -0700253Using automatic values
254----------------------
255
256If the exact value is unimportant you can use :class:`auto`::
257
258 >>> from enum import Enum, auto
259 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800260 ... RED = auto()
261 ... BLUE = auto()
262 ... GREEN = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700263 ...
264 >>> list(Color)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800265 [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
Ethan Furmanc16595e2016-09-10 23:36:59 -0700266
267The values are chosen by :func:`_generate_next_value_`, which can be
268overridden::
269
270 >>> class AutoName(Enum):
271 ... def _generate_next_value_(name, start, count, last_values):
272 ... return name
273 ...
274 >>> class Ordinal(AutoName):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800275 ... NORTH = auto()
276 ... SOUTH = auto()
277 ... EAST = auto()
278 ... WEST = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700279 ...
280 >>> list(Ordinal)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800281 [<Ordinal.NORTH: 'NORTH'>, <Ordinal.SOUTH: 'SOUTH'>, <Ordinal.EAST: 'EAST'>, <Ordinal.WEST: 'WEST'>]
Ethan Furmanc16595e2016-09-10 23:36:59 -0700282
283.. note::
284
285 The goal of the default :meth:`_generate_next_value_` methods is to provide
286 the next :class:`int` in sequence with the last :class:`int` provided, but
287 the way it does this is an implementation detail and may change.
288
Ethan Onstottd9a43e22020-04-28 13:20:55 -0400289.. note::
290
291 The :meth:`_generate_next_value_` method must be defined before any members.
292
Ethan Furmanf24bb352013-07-18 17:05:39 -0700293Iteration
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700294---------
Ethan Furmanf24bb352013-07-18 17:05:39 -0700295
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700296Iterating over the members of an enum does not provide the aliases::
297
298 >>> list(Shape)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800299 [<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700300
INADA Naokie57f91a2018-06-19 01:14:26 +0900301The special attribute ``__members__`` is a read-only ordered mapping of names
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700302to members. It includes all names defined in the enumeration, including the
303aliases::
304
305 >>> for name, member in Shape.__members__.items():
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700306 ... name, member
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700307 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800308 ('SQUARE', <Shape.SQUARE: 2>)
309 ('DIAMOND', <Shape.DIAMOND: 1>)
310 ('CIRCLE', <Shape.CIRCLE: 3>)
311 ('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700312
313The ``__members__`` attribute can be used for detailed programmatic access to
314the enumeration members. For example, finding all the aliases::
315
Ethan Furman332dbc72016-08-20 00:00:52 -0700316 >>> [name for name, member in Shape.__members__.items() if member.name != name]
Ethan Furman23bb6f42016-11-21 09:22:05 -0800317 ['ALIAS_FOR_SQUARE']
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700318
Ethan Furmanf24bb352013-07-18 17:05:39 -0700319
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700320Comparisons
321-----------
322
323Enumeration members are compared by identity::
324
Ethan Furman23bb6f42016-11-21 09:22:05 -0800325 >>> Color.RED is Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700326 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800327 >>> Color.RED is Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700328 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800329 >>> Color.RED is not Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700330 True
331
332Ordered comparisons between enumeration values are *not* supported. Enum
333members are not integers (but see `IntEnum`_ below)::
334
Ethan Furman23bb6f42016-11-21 09:22:05 -0800335 >>> Color.RED < Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700336 Traceback (most recent call last):
337 File "<stdin>", line 1, in <module>
Ethan Furmane8e61272016-08-20 07:19:31 -0700338 TypeError: '<' not supported between instances of 'Color' and 'Color'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700339
340Equality comparisons are defined though::
341
Ethan Furman23bb6f42016-11-21 09:22:05 -0800342 >>> Color.BLUE == Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700343 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800344 >>> Color.BLUE != Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700345 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800346 >>> Color.BLUE == Color.BLUE
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700347 True
348
349Comparisons against non-enumeration values will always compare not equal
Ezio Melotti93d7dda2013-10-05 04:13:18 +0300350(again, :class:`IntEnum` was explicitly designed to behave differently, see
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700351below)::
352
Ethan Furman23bb6f42016-11-21 09:22:05 -0800353 >>> Color.BLUE == 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700354 False
355
356
357Allowed members and attributes of enumerations
358----------------------------------------------
359
360The examples above use integers for enumeration values. Using integers is
Ethan Furman332dbc72016-08-20 00:00:52 -0700361short and handy (and provided by default by the `Functional API`_), but not
362strictly enforced. In the vast majority of use-cases, one doesn't care what
363the actual value of an enumeration is. But if the value *is* important,
364enumerations can have arbitrary values.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700365
366Enumerations are Python classes, and can have methods and special methods as
367usual. If we have this enumeration::
368
369 >>> class Mood(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800370 ... FUNKY = 1
371 ... HAPPY = 3
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700372 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700373 ... def describe(self):
374 ... # self is the member here
375 ... return self.name, self.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700376 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700377 ... def __str__(self):
378 ... return 'my custom str! {0}'.format(self.value)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700379 ...
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700380 ... @classmethod
381 ... def favorite_mood(cls):
382 ... # cls here is the enumeration
Ethan Furman23bb6f42016-11-21 09:22:05 -0800383 ... return cls.HAPPY
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700384 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700385
386Then::
387
388 >>> Mood.favorite_mood()
Ethan Furman23bb6f42016-11-21 09:22:05 -0800389 <Mood.HAPPY: 3>
390 >>> Mood.HAPPY.describe()
391 ('HAPPY', 3)
392 >>> str(Mood.FUNKY)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700393 'my custom str! 1'
394
Martin Pantera90a4a92016-05-30 04:04:50 +0000395The rules for what is allowed are as follows: names that start and end with
396a single underscore are reserved by enum and cannot be used; all other
Ethan Furman8be6fac2014-11-01 07:40:22 -0700397attributes defined within an enumeration will become members of this
398enumeration, with the exception of special methods (:meth:`__str__`,
Ethan Furmana4b1bb42018-01-22 07:56:37 -0800399:meth:`__add__`, etc.), descriptors (methods are also descriptors), and
400variable names listed in :attr:`_ignore_`.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700401
402Note: if your enumeration defines :meth:`__new__` and/or :meth:`__init__` then
Antoined3c8d732019-08-20 03:41:31 +0200403any value(s) given to the enum member will be passed into those methods.
404See `Planet`_ for an example.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700405
406
Ethan Furman5bdab642018-09-21 19:03:09 -0700407Restricted Enum subclassing
408---------------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700409
Ethan Furman5bdab642018-09-21 19:03:09 -0700410A new :class:`Enum` class must have one base Enum class, up to one concrete
411data type, and as many :class:`object`-based mixin classes as needed. The
412order of these base classes is::
413
nu_nodfc8bb92019-01-27 23:07:47 +0100414 class EnumName([mix-in, ...,] [data-type,] base-enum):
Ethan Furman5bdab642018-09-21 19:03:09 -0700415 pass
416
417Also, subclassing an enumeration is allowed only if the enumeration does not define
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700418any members. So this is forbidden::
419
420 >>> class MoreColor(Color):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800421 ... PINK = 17
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700422 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700423 Traceback (most recent call last):
424 ...
Ethan Furman7aaeb2a2021-01-25 14:26:19 -0800425 TypeError: MoreColor: cannot extend enumeration 'Color'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700426
427But this is allowed::
428
429 >>> class Foo(Enum):
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700430 ... def some_behavior(self):
431 ... pass
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700432 ...
433 >>> class Bar(Foo):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800434 ... HAPPY = 1
435 ... SAD = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700436 ...
437
438Allowing subclassing of enums that define members would lead to a violation of
439some important invariants of types and instances. On the other hand, it makes
440sense to allow sharing some common behavior between a group of enumerations.
441(See `OrderedEnum`_ for an example.)
442
443
444Pickling
445--------
446
447Enumerations can be pickled and unpickled::
448
449 >>> from test.test_enum import Fruit
450 >>> from pickle import dumps, loads
Ethan Furman23bb6f42016-11-21 09:22:05 -0800451 >>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO))
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700452 True
453
454The usual restrictions for pickling apply: picklable enums must be defined in
455the top level of a module, since unpickling requires them to be importable
456from that module.
457
Ethan Furmanca1b7942014-02-08 11:36:27 -0800458.. note::
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700459
Ethan Furmanca1b7942014-02-08 11:36:27 -0800460 With pickle protocol version 4 it is possible to easily pickle enums
461 nested in other classes.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700462
Ethan Furman2da95042014-03-03 12:42:52 -0800463It is possible to modify how Enum members are pickled/unpickled by defining
464:meth:`__reduce_ex__` in the enumeration class.
465
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700466
467Functional API
468--------------
469
470The :class:`Enum` class is callable, providing the following functional API::
471
Ethan Furman23bb6f42016-11-21 09:22:05 -0800472 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG')
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700473 >>> Animal
474 <enum 'Animal'>
Ethan Furman23bb6f42016-11-21 09:22:05 -0800475 >>> Animal.ANT
476 <Animal.ANT: 1>
477 >>> Animal.ANT.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700478 1
479 >>> list(Animal)
Ethan Furman23bb6f42016-11-21 09:22:05 -0800480 [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700481
Ethan Furman332dbc72016-08-20 00:00:52 -0700482The semantics of this API resemble :class:`~collections.namedtuple`. The first
483argument of the call to :class:`Enum` is the name of the enumeration.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700484
Ethan Furman332dbc72016-08-20 00:00:52 -0700485The second argument is the *source* of enumeration member names. It can be a
486whitespace-separated string of names, a sequence of names, a sequence of
4872-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to
488values. The last two options enable assigning arbitrary values to
489enumerations; the others auto-assign increasing integers starting with 1 (use
490the ``start`` parameter to specify a different starting value). A
491new class derived from :class:`Enum` is returned. In other words, the above
492assignment to :class:`Animal` is equivalent to::
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700493
Ethan Furman8a123292015-01-14 22:31:50 -0800494 >>> class Animal(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800495 ... ANT = 1
496 ... BEE = 2
497 ... CAT = 3
498 ... DOG = 4
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700499 ...
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700500
Ethan Furmane2563462013-06-28 19:37:17 -0700501The reason for defaulting to ``1`` as the starting number and not ``0`` is
502that ``0`` is ``False`` in a boolean sense, but enum members all evaluate
503to ``True``.
504
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700505Pickling enums created with the functional API can be tricky as frame stack
506implementation details are used to try and figure out which module the
507enumeration is being created in (e.g. it will fail if you use a utility
Ethan Furman332dbc72016-08-20 00:00:52 -0700508function in separate module, and also may not work on IronPython or Jython).
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700509The solution is to specify the module name explicitly as follows::
510
Ethan Furman23bb6f42016-11-21 09:22:05 -0800511 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700512
Ethan Furman2da95042014-03-03 12:42:52 -0800513.. warning::
514
Ethan Furman01cc2d52014-03-03 15:02:04 -0800515 If ``module`` is not supplied, and Enum cannot determine what it is,
Ethan Furman2da95042014-03-03 12:42:52 -0800516 the new Enum members will not be unpicklable; to keep errors closer to
517 the source, pickling will be disabled.
518
Ethan Furmanca1b7942014-02-08 11:36:27 -0800519The new pickle protocol 4 also, in some circumstances, relies on
Martin Panterbae5d812016-06-18 03:57:31 +0000520:attr:`~definition.__qualname__` being set to the location where pickle will be able
Ethan Furmanca1b7942014-02-08 11:36:27 -0800521to find the class. For example, if the class was made available in class
522SomeData in the global scope::
523
Ethan Furman23bb6f42016-11-21 09:22:05 -0800524 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal')
Ethan Furmanca1b7942014-02-08 11:36:27 -0800525
Ethan Furman2da95042014-03-03 12:42:52 -0800526The complete signature is::
527
Ethan Furman332dbc72016-08-20 00:00:52 -0700528 Enum(value='NewEnumName', names=<...>, *, module='...', qualname='...', type=<mixed-in class>, start=1)
Ethan Furman2da95042014-03-03 12:42:52 -0800529
Ethan Furman01cc2d52014-03-03 15:02:04 -0800530:value: What the new Enum class will record as its name.
Ethan Furman2da95042014-03-03 12:42:52 -0800531
Zachary Waredbd1c432014-03-20 10:01:48 -0500532:names: The Enum members. This can be a whitespace or comma separated string
Ethan Furmand9925a12014-09-16 20:35:55 -0700533 (values will start at 1 unless otherwise specified)::
Ethan Furman2da95042014-03-03 12:42:52 -0800534
Ethan Furman23bb6f42016-11-21 09:22:05 -0800535 'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE'
Ethan Furman2da95042014-03-03 12:42:52 -0800536
Ethan Furman8a123292015-01-14 22:31:50 -0800537 or an iterator of names::
538
Ethan Furman23bb6f42016-11-21 09:22:05 -0800539 ['RED', 'GREEN', 'BLUE']
Ethan Furman8a123292015-01-14 22:31:50 -0800540
Ethan Furman01cc2d52014-03-03 15:02:04 -0800541 or an iterator of (name, value) pairs::
Ethan Furman2da95042014-03-03 12:42:52 -0800542
Ethan Furman23bb6f42016-11-21 09:22:05 -0800543 [('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)]
Ethan Furman2da95042014-03-03 12:42:52 -0800544
Ethan Furman01cc2d52014-03-03 15:02:04 -0800545 or a mapping::
Ethan Furman2da95042014-03-03 12:42:52 -0800546
Ethan Furman23bb6f42016-11-21 09:22:05 -0800547 {'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42}
Ethan Furman2da95042014-03-03 12:42:52 -0800548
Ethan Furman01cc2d52014-03-03 15:02:04 -0800549:module: name of module where new Enum class can be found.
Ethan Furman2da95042014-03-03 12:42:52 -0800550
Ethan Furman01cc2d52014-03-03 15:02:04 -0800551:qualname: where in module new Enum class can be found.
Ethan Furman2da95042014-03-03 12:42:52 -0800552
Ethan Furman01cc2d52014-03-03 15:02:04 -0800553:type: type to mix in to new Enum class.
Ethan Furman2da95042014-03-03 12:42:52 -0800554
Yury Selivanov4dde5872015-09-11 00:48:21 -0400555:start: number to start counting at if only names are passed in.
Ethan Furmand9925a12014-09-16 20:35:55 -0700556
Berker Peksag60efd792014-09-18 05:23:14 +0300557.. versionchanged:: 3.5
558 The *start* parameter was added.
559
Ethan Furmanca1b7942014-02-08 11:36:27 -0800560
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700561Derived Enumerations
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700562--------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700563
564IntEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700565^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700566
Ethan Furman65a5a472016-09-01 23:55:19 -0700567The first variation of :class:`Enum` that is provided is also a subclass of
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700568:class:`int`. Members of an :class:`IntEnum` can be compared to integers;
569by extension, integer enumerations of different types can also be compared
570to each other::
571
572 >>> from enum import IntEnum
573 >>> class Shape(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800574 ... CIRCLE = 1
575 ... SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700576 ...
577 >>> class Request(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800578 ... POST = 1
579 ... GET = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700580 ...
581 >>> Shape == 1
582 False
Ethan Furman23bb6f42016-11-21 09:22:05 -0800583 >>> Shape.CIRCLE == 1
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700584 True
Ethan Furman23bb6f42016-11-21 09:22:05 -0800585 >>> Shape.CIRCLE == Request.POST
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700586 True
587
588However, they still can't be compared to standard :class:`Enum` enumerations::
589
590 >>> class Shape(IntEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800591 ... CIRCLE = 1
592 ... SQUARE = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700593 ...
594 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800595 ... RED = 1
596 ... GREEN = 2
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700597 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800598 >>> Shape.CIRCLE == Color.RED
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700599 False
600
601:class:`IntEnum` values behave like integers in other ways you'd expect::
602
Ethan Furman23bb6f42016-11-21 09:22:05 -0800603 >>> int(Shape.CIRCLE)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700604 1
Ethan Furman23bb6f42016-11-21 09:22:05 -0800605 >>> ['a', 'b', 'c'][Shape.CIRCLE]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700606 'b'
Ethan Furman23bb6f42016-11-21 09:22:05 -0800607 >>> [i for i in range(Shape.SQUARE)]
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700608 [0, 1]
609
Ethan Furman65a5a472016-09-01 23:55:19 -0700610
Ethan Furman0063ff42020-09-21 17:23:13 -0700611StrEnum
612^^^^^^^
613
614The second variation of :class:`Enum` that is provided is also a subclass of
615:class:`str`. Members of a :class:`StrEnum` can be compared to strings;
616by extension, string enumerations of different types can also be compared
617to each other. :class:`StrEnum` exists to help avoid the problem of getting
618an incorrect member::
619
Ethan Furman7aaeb2a2021-01-25 14:26:19 -0800620 >>> from enum import StrEnum
Ethan Furman0063ff42020-09-21 17:23:13 -0700621 >>> class Directions(StrEnum):
622 ... NORTH = 'north', # notice the trailing comma
623 ... SOUTH = 'south'
624
625Before :class:`StrEnum`, ``Directions.NORTH`` would have been the :class:`tuple`
626``('north',)``.
627
Ethan Furmand986d162020-09-22 13:00:07 -0700628.. note::
629
630 Unlike other Enum's, ``str(StrEnum.member)`` will return the value of the
631 member instead of the usual ``"EnumClass.member"``.
632
Ethan Furman0063ff42020-09-21 17:23:13 -0700633.. versionadded:: 3.10
634
635
Ethan Furman65a5a472016-09-01 23:55:19 -0700636IntFlag
637^^^^^^^
638
639The next variation of :class:`Enum` provided, :class:`IntFlag`, is also based
640on :class:`int`. The difference being :class:`IntFlag` members can be combined
641using the bitwise operators (&, \|, ^, ~) and the result is still an
Ethan Furman7aaeb2a2021-01-25 14:26:19 -0800642:class:`IntFlag` member, if possible. However, as the name implies, :class:`IntFlag`
Ethan Furman54924df2016-09-07 23:40:31 -0700643members also subclass :class:`int` and can be used wherever an :class:`int` is
Ethan Furman7aaeb2a2021-01-25 14:26:19 -0800644used.
645
646.. note::
647
648 Any operation on an :class:`IntFlag` member besides the bit-wise operations will
649 lose the :class:`IntFlag` membership.
650
651.. note::
652
653 Bit-wise operations that result in invalid :class:`IntFlag` values will lose the
654 :class:`IntFlag` membership.
Ethan Furman65a5a472016-09-01 23:55:19 -0700655
Ethan Furman25d94bb2016-09-02 16:32:32 -0700656.. versionadded:: 3.6
Ethan Furman7aaeb2a2021-01-25 14:26:19 -0800657.. versionchanged:: 3.10
Ethan Furman25d94bb2016-09-02 16:32:32 -0700658
659Sample :class:`IntFlag` class::
660
Ethan Furman65a5a472016-09-01 23:55:19 -0700661 >>> from enum import IntFlag
662 >>> class Perm(IntFlag):
663 ... R = 4
664 ... W = 2
665 ... X = 1
666 ...
667 >>> Perm.R | Perm.W
668 <Perm.R|W: 6>
669 >>> Perm.R + Perm.W
670 6
671 >>> RW = Perm.R | Perm.W
672 >>> Perm.R in RW
673 True
674
Ethan Furman25d94bb2016-09-02 16:32:32 -0700675It is also possible to name the combinations::
676
677 >>> class Perm(IntFlag):
678 ... R = 4
679 ... W = 2
680 ... X = 1
681 ... RWX = 7
682 >>> Perm.RWX
683 <Perm.RWX: 7>
684 >>> ~Perm.RWX
Ethan Furman7aaeb2a2021-01-25 14:26:19 -0800685 <Perm: 0>
686 >>> Perm(7)
687 <Perm.RWX: 7>
688
689.. note::
690
691 Named combinations are considered aliases. Aliases do not show up during
692 iteration, but can be returned from by-value lookups.
693
694.. versionchanged:: 3.10
Ethan Furman25d94bb2016-09-02 16:32:32 -0700695
696Another important difference between :class:`IntFlag` and :class:`Enum` is that
697if no flags are set (the value is 0), its boolean evaluation is :data:`False`::
698
699 >>> Perm.R & Perm.X
Ethan Furman7aaeb2a2021-01-25 14:26:19 -0800700 <Perm: 0>
Ethan Furman25d94bb2016-09-02 16:32:32 -0700701 >>> bool(Perm.R & Perm.X)
702 False
703
704Because :class:`IntFlag` members are also subclasses of :class:`int` they can
Ethan Furman7aaeb2a2021-01-25 14:26:19 -0800705be combined with them (but may lose :class:`IntFlag` membership::
706
707 >>> Perm.X | 4
708 <Perm.R|X: 5>
Ethan Furman25d94bb2016-09-02 16:32:32 -0700709
710 >>> Perm.X | 8
Ethan Furman7aaeb2a2021-01-25 14:26:19 -0800711 9
712
713.. note::
714
715 The negation operator, ``~``, always returns an :class:`IntFlag` member with a
716 positive value::
717
718 >>> (~Perm.X).value == (Perm.R|Perm.W).value == 6
719 True
Ethan Furman65a5a472016-09-01 23:55:19 -0700720
Ethan Furman7219e272020-09-16 13:01:00 -0700721:class:`IntFlag` members can also be iterated over::
722
723 >>> list(RW)
724 [<Perm.R: 4>, <Perm.W: 2>]
725
726.. versionadded:: 3.10
727
Ethan Furman65a5a472016-09-01 23:55:19 -0700728
729Flag
730^^^^
731
732The last variation is :class:`Flag`. Like :class:`IntFlag`, :class:`Flag`
Ethan Furman25d94bb2016-09-02 16:32:32 -0700733members can be combined using the bitwise operators (&, \|, ^, ~). Unlike
Ethan Furman65a5a472016-09-01 23:55:19 -0700734:class:`IntFlag`, they cannot be combined with, nor compared against, any
Ethan Furmanc16595e2016-09-10 23:36:59 -0700735other :class:`Flag` enumeration, nor :class:`int`. While it is possible to
736specify the values directly it is recommended to use :class:`auto` as the
737value and let :class:`Flag` select an appropriate value.
Ethan Furman65a5a472016-09-01 23:55:19 -0700738
739.. versionadded:: 3.6
740
Ethan Furman25d94bb2016-09-02 16:32:32 -0700741Like :class:`IntFlag`, if a combination of :class:`Flag` members results in no
742flags being set, the boolean evaluation is :data:`False`::
743
Julian Kahnert0f31c742018-01-13 04:35:57 +0100744 >>> from enum import Flag, auto
Ethan Furman25d94bb2016-09-02 16:32:32 -0700745 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800746 ... RED = auto()
747 ... BLUE = auto()
748 ... GREEN = auto()
Ethan Furman25d94bb2016-09-02 16:32:32 -0700749 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800750 >>> Color.RED & Color.GREEN
Ethan Furman7aaeb2a2021-01-25 14:26:19 -0800751 <Color: 0>
Ethan Furman23bb6f42016-11-21 09:22:05 -0800752 >>> bool(Color.RED & Color.GREEN)
Ethan Furman25d94bb2016-09-02 16:32:32 -0700753 False
754
Ethan Furman27682d22016-09-04 11:39:01 -0700755Individual flags should have values that are powers of two (1, 2, 4, 8, ...),
756while combinations of flags won't::
757
758 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800759 ... RED = auto()
760 ... BLUE = auto()
761 ... GREEN = auto()
762 ... WHITE = RED | BLUE | GREEN
Ethan Furmanc16595e2016-09-10 23:36:59 -0700763 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800764 >>> Color.WHITE
765 <Color.WHITE: 7>
Ethan Furman27682d22016-09-04 11:39:01 -0700766
Ethan Furman25d94bb2016-09-02 16:32:32 -0700767Giving a name to the "no flags set" condition does not change its boolean
768value::
769
770 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800771 ... BLACK = 0
772 ... RED = auto()
773 ... BLUE = auto()
774 ... GREEN = auto()
Ethan Furman25d94bb2016-09-02 16:32:32 -0700775 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800776 >>> Color.BLACK
777 <Color.BLACK: 0>
778 >>> bool(Color.BLACK)
Ethan Furman25d94bb2016-09-02 16:32:32 -0700779 False
780
Ethan Furman7219e272020-09-16 13:01:00 -0700781:class:`Flag` members can also be iterated over::
782
783 >>> purple = Color.RED | Color.BLUE
784 >>> list(purple)
Ethan Furman7aaeb2a2021-01-25 14:26:19 -0800785 [<Color.RED: 1>, <Color.BLUE: 2>]
Ethan Furman7219e272020-09-16 13:01:00 -0700786
787.. versionadded:: 3.10
788
Ethan Furman65a5a472016-09-01 23:55:19 -0700789.. note::
790
791 For the majority of new code, :class:`Enum` and :class:`Flag` are strongly
792 recommended, since :class:`IntEnum` and :class:`IntFlag` break some
793 semantic promises of an enumeration (by being comparable to integers, and
794 thus by transitivity to other unrelated enumerations). :class:`IntEnum`
795 and :class:`IntFlag` should be used only in cases where :class:`Enum` and
796 :class:`Flag` will not do; for example, when integer constants are replaced
797 with enumerations, or for interoperability with other systems.
Ethan Furman332dbc72016-08-20 00:00:52 -0700798
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700799
800Others
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700801^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700802
803While :class:`IntEnum` is part of the :mod:`enum` module, it would be very
804simple to implement independently::
805
806 class IntEnum(int, Enum):
807 pass
808
809This demonstrates how similar derived enumerations can be defined; for example
Ethan Furman332dbc72016-08-20 00:00:52 -0700810a :class:`StrEnum` that mixes in :class:`str` instead of :class:`int`.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700811
812Some rules:
813
8141. When subclassing :class:`Enum`, mix-in types must appear before
815 :class:`Enum` itself in the sequence of bases, as in the :class:`IntEnum`
816 example above.
8172. While :class:`Enum` can have members of any type, once you mix in an
818 additional type, all the members must have values of that type, e.g.
819 :class:`int` above. This restriction does not apply to mix-ins which only
Antoined3c8d732019-08-20 03:41:31 +0200820 add methods and don't specify another type.
Ethan Furman6b3d64a2013-06-14 16:55:46 -07008213. When another data type is mixed in, the :attr:`value` attribute is *not the
Zachary Waredbd1c432014-03-20 10:01:48 -0500822 same* as the enum member itself, although it is equivalent and will compare
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700823 equal.
Martin Panterd5db1472016-02-08 01:34:09 +00008244. %-style formatting: `%s` and `%r` call the :class:`Enum` class's
825 :meth:`__str__` and :meth:`__repr__` respectively; other codes (such as
826 `%i` or `%h` for IntEnum) treat the enum member as its mixed-in type.
Martin Panterbc1ee462016-02-13 00:41:37 +00008275. :ref:`Formatted string literals <f-strings>`, :meth:`str.format`,
thatneat2f19e822019-07-04 11:28:37 -0700828 and :func:`format` will use the mixed-in type's :meth:`__format__`
829 unless :meth:`__str__` or :meth:`__format__` is overridden in the subclass,
830 in which case the overridden methods or :class:`Enum` methods will be used.
831 Use the !s and !r format codes to force usage of the :class:`Enum` class's
832 :meth:`__str__` and :meth:`__repr__` methods.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700833
Ethan Furmanf5223742018-09-12 10:00:30 -0700834When to use :meth:`__new__` vs. :meth:`__init__`
835------------------------------------------------
836
837:meth:`__new__` must be used whenever you want to customize the actual value of
838the :class:`Enum` member. Any other modifications may go in either
839:meth:`__new__` or :meth:`__init__`, with :meth:`__init__` being preferred.
840
841For example, if you want to pass several items to the constructor, but only
842want one of them to be the value::
843
844 >>> class Coordinate(bytes, Enum):
845 ... """
846 ... Coordinate with binary codes that can be indexed by the int code.
847 ... """
848 ... def __new__(cls, value, label, unit):
849 ... obj = bytes.__new__(cls, [value])
850 ... obj._value_ = value
851 ... obj.label = label
852 ... obj.unit = unit
853 ... return obj
854 ... PX = (0, 'P.X', 'km')
855 ... PY = (1, 'P.Y', 'km')
856 ... VX = (2, 'V.X', 'km/s')
857 ... VY = (3, 'V.Y', 'km/s')
858 ...
859
860 >>> print(Coordinate['PY'])
861 Coordinate.PY
862
863 >>> print(Coordinate(3))
864 Coordinate.VY
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700865
866Interesting examples
Ethan Furmaned0bf8a2013-09-06 19:53:30 -0700867--------------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700868
Ethan Furman65a5a472016-09-01 23:55:19 -0700869While :class:`Enum`, :class:`IntEnum`, :class:`IntFlag`, and :class:`Flag` are
870expected to cover the majority of use-cases, they cannot cover them all. Here
871are recipes for some different types of enumerations that can be used directly,
872or as examples for creating one's own.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700873
874
Ethan Furman6a137e82016-09-07 08:17:15 -0700875Omitting values
876^^^^^^^^^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700877
Ethan Furman6a137e82016-09-07 08:17:15 -0700878In many use-cases one doesn't care what the actual value of an enumeration
879is. There are several ways to define this type of simple enumeration:
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700880
Ethan Furmanc16595e2016-09-10 23:36:59 -0700881- use instances of :class:`auto` for the value
Ethan Furman6a137e82016-09-07 08:17:15 -0700882- use instances of :class:`object` as the value
883- use a descriptive string as the value
884- use a tuple as the value and a custom :meth:`__new__` to replace the
885 tuple with an :class:`int` value
886
887Using any of these methods signifies to the user that these values are not
888important, and also enables one to add, remove, or reorder members without
889having to renumber the remaining members.
890
891Whichever method you choose, you should provide a :meth:`repr` that also hides
892the (unimportant) value::
893
894 >>> class NoValue(Enum):
895 ... def __repr__(self):
896 ... return '<%s.%s>' % (self.__class__.__name__, self.name)
897 ...
898
899
Ethan Furmanc16595e2016-09-10 23:36:59 -0700900Using :class:`auto`
901"""""""""""""""""""
902
Berker Peksag2a267a12017-01-02 05:51:04 +0300903Using :class:`auto` would look like::
Ethan Furmanc16595e2016-09-10 23:36:59 -0700904
905 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800906 ... RED = auto()
907 ... BLUE = auto()
908 ... GREEN = auto()
Ethan Furmanc16595e2016-09-10 23:36:59 -0700909 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800910 >>> Color.GREEN
911 <Color.GREEN>
Ethan Furmanc16595e2016-09-10 23:36:59 -0700912
913
Ethan Furman6a137e82016-09-07 08:17:15 -0700914Using :class:`object`
915"""""""""""""""""""""
916
917Using :class:`object` would look like::
918
919 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800920 ... RED = object()
921 ... GREEN = object()
922 ... BLUE = object()
Ethan Furman6a137e82016-09-07 08:17:15 -0700923 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800924 >>> Color.GREEN
925 <Color.GREEN>
Ethan Furman6a137e82016-09-07 08:17:15 -0700926
927
928Using a descriptive string
929""""""""""""""""""""""""""
930
931Using a string as the value would look like::
932
933 >>> class Color(NoValue):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800934 ... RED = 'stop'
935 ... GREEN = 'go'
936 ... BLUE = 'too fast!'
Ethan Furman6a137e82016-09-07 08:17:15 -0700937 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800938 >>> Color.GREEN
939 <Color.GREEN>
940 >>> Color.GREEN.value
Ethan Furman6a137e82016-09-07 08:17:15 -0700941 'go'
942
943
944Using a custom :meth:`__new__`
945""""""""""""""""""""""""""""""
946
947Using an auto-numbering :meth:`__new__` would look like::
948
949 >>> class AutoNumber(NoValue):
Ethan Furman332dbc72016-08-20 00:00:52 -0700950 ... def __new__(cls):
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700951 ... value = len(cls.__members__) + 1
952 ... obj = object.__new__(cls)
Ethan Furman90262622013-07-30 12:24:25 -0700953 ... obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700954 ... return obj
955 ...
Ethan Furman332dbc72016-08-20 00:00:52 -0700956 >>> class Color(AutoNumber):
Ethan Furman23bb6f42016-11-21 09:22:05 -0800957 ... RED = ()
958 ... GREEN = ()
959 ... BLUE = ()
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700960 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -0800961 >>> Color.GREEN
962 <Color.GREEN>
963 >>> Color.GREEN.value
Ethan Furman6a137e82016-09-07 08:17:15 -0700964 2
965
Ethan Furman62e40d82020-09-22 00:05:27 -0700966To make a more general purpose ``AutoNumber``, add ``*args`` to the signature::
967
968 >>> class AutoNumber(NoValue):
969 ... def __new__(cls, *args): # this is the only change from above
970 ... value = len(cls.__members__) + 1
971 ... obj = object.__new__(cls)
972 ... obj._value_ = value
973 ... return obj
974 ...
975
976Then when you inherit from ``AutoNumber`` you can write your own ``__init__``
977to handle any extra arguments::
978
979 >>> class Swatch(AutoNumber):
980 ... def __init__(self, pantone='unknown'):
981 ... self.pantone = pantone
982 ... AUBURN = '3497'
983 ... SEA_GREEN = '1246'
984 ... BLEACHED_CORAL = () # New color, no Pantone code yet!
985 ...
986 >>> Swatch.SEA_GREEN
Ethan Furman7aaeb2a2021-01-25 14:26:19 -0800987 <Swatch.SEA_GREEN>
Ethan Furman62e40d82020-09-22 00:05:27 -0700988 >>> Swatch.SEA_GREEN.pantone
989 '1246'
990 >>> Swatch.BLEACHED_CORAL.pantone
991 'unknown'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700992
Ethan Furman9a1daf52013-09-27 22:58:06 -0700993.. note::
994
995 The :meth:`__new__` method, if defined, is used during creation of the Enum
996 members; it is then replaced by Enum's :meth:`__new__` which is used after
Ethan Furmanf75805e2014-09-16 19:13:31 -0700997 class creation for lookup of existing members.
Ethan Furman9a1daf52013-09-27 22:58:06 -0700998
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700999
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001000OrderedEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -07001001^^^^^^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001002
1003An ordered enumeration that is not based on :class:`IntEnum` and so maintains
1004the normal :class:`Enum` invariants (such as not being comparable to other
1005enumerations)::
1006
1007 >>> class OrderedEnum(Enum):
1008 ... def __ge__(self, other):
1009 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -07001010 ... return self.value >= other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001011 ... return NotImplemented
1012 ... def __gt__(self, other):
1013 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -07001014 ... return self.value > other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001015 ... return NotImplemented
1016 ... def __le__(self, other):
1017 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -07001018 ... return self.value <= other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001019 ... return NotImplemented
1020 ... def __lt__(self, other):
1021 ... if self.__class__ is other.__class__:
Ethan Furman90262622013-07-30 12:24:25 -07001022 ... return self.value < other.value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001023 ... return NotImplemented
1024 ...
1025 >>> class Grade(OrderedEnum):
1026 ... A = 5
1027 ... B = 4
1028 ... C = 3
1029 ... D = 2
1030 ... F = 1
1031 ...
1032 >>> Grade.C < Grade.A
1033 True
1034
1035
Ethan Furmanf24bb352013-07-18 17:05:39 -07001036DuplicateFreeEnum
Ethan Furmaned0bf8a2013-09-06 19:53:30 -07001037^^^^^^^^^^^^^^^^^
Ethan Furmanf24bb352013-07-18 17:05:39 -07001038
1039Raises an error if a duplicate member name is found instead of creating an
1040alias::
1041
1042 >>> class DuplicateFreeEnum(Enum):
1043 ... def __init__(self, *args):
1044 ... cls = self.__class__
1045 ... if any(self.value == e.value for e in cls):
1046 ... a = self.name
1047 ... e = cls(self.value).name
1048 ... raise ValueError(
1049 ... "aliases not allowed in DuplicateFreeEnum: %r --> %r"
1050 ... % (a, e))
1051 ...
1052 >>> class Color(DuplicateFreeEnum):
Ethan Furman23bb6f42016-11-21 09:22:05 -08001053 ... RED = 1
1054 ... GREEN = 2
1055 ... BLUE = 3
1056 ... GRENE = 2
Ethan Furmaned0bf8a2013-09-06 19:53:30 -07001057 ...
Ethan Furmanf24bb352013-07-18 17:05:39 -07001058 Traceback (most recent call last):
1059 ...
Ethan Furman23bb6f42016-11-21 09:22:05 -08001060 ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN'
Ethan Furmanf24bb352013-07-18 17:05:39 -07001061
1062.. note::
1063
1064 This is a useful example for subclassing Enum to add or change other
Ezio Melotti93d7dda2013-10-05 04:13:18 +03001065 behaviors as well as disallowing aliases. If the only desired change is
Ezio Melotti17f1edd2013-10-05 04:26:06 +03001066 disallowing aliases, the :func:`unique` decorator can be used instead.
Ethan Furmanf24bb352013-07-18 17:05:39 -07001067
1068
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001069Planet
Ethan Furmaned0bf8a2013-09-06 19:53:30 -07001070^^^^^^
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001071
1072If :meth:`__new__` or :meth:`__init__` is defined the value of the enum member
1073will be passed to those methods::
1074
1075 >>> class Planet(Enum):
1076 ... MERCURY = (3.303e+23, 2.4397e6)
1077 ... VENUS = (4.869e+24, 6.0518e6)
1078 ... EARTH = (5.976e+24, 6.37814e6)
1079 ... MARS = (6.421e+23, 3.3972e6)
1080 ... JUPITER = (1.9e+27, 7.1492e7)
1081 ... SATURN = (5.688e+26, 6.0268e7)
1082 ... URANUS = (8.686e+25, 2.5559e7)
1083 ... NEPTUNE = (1.024e+26, 2.4746e7)
1084 ... def __init__(self, mass, radius):
1085 ... self.mass = mass # in kilograms
1086 ... self.radius = radius # in meters
1087 ... @property
1088 ... def surface_gravity(self):
1089 ... # universal gravitational constant (m3 kg-1 s-2)
1090 ... G = 6.67300E-11
1091 ... return G * self.mass / (self.radius * self.radius)
1092 ...
1093 >>> Planet.EARTH.value
1094 (5.976e+24, 6378140.0)
1095 >>> Planet.EARTH.surface_gravity
1096 9.802652743337129
Ethan Furman9a1daf52013-09-27 22:58:06 -07001097
1098
Ethan Furmana4b1bb42018-01-22 07:56:37 -08001099TimePeriod
1100^^^^^^^^^^
1101
1102An example to show the :attr:`_ignore_` attribute in use::
1103
1104 >>> from datetime import timedelta
1105 >>> class Period(timedelta, Enum):
1106 ... "different lengths of time"
1107 ... _ignore_ = 'Period i'
1108 ... Period = vars()
1109 ... for i in range(367):
1110 ... Period['day_%d' % i] = i
1111 ...
1112 >>> list(Period)[:2]
1113 [<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>]
1114 >>> list(Period)[-2:]
1115 [<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>]
1116
1117
Ethan Furman9a1daf52013-09-27 22:58:06 -07001118How are Enums different?
1119------------------------
1120
1121Enums have a custom metaclass that affects many aspects of both derived Enum
1122classes and their instances (members).
1123
1124
1125Enum Classes
1126^^^^^^^^^^^^
1127
1128The :class:`EnumMeta` metaclass is responsible for providing the
1129:meth:`__contains__`, :meth:`__dir__`, :meth:`__iter__` and other methods that
1130allow one to do things with an :class:`Enum` class that fail on a typical
Rahul Jha94306522018-09-10 23:51:04 +05301131class, such as `list(Color)` or `some_enum_var in Color`. :class:`EnumMeta` is
Ethan Furman9a1daf52013-09-27 22:58:06 -07001132responsible for ensuring that various other methods on the final :class:`Enum`
1133class are correct (such as :meth:`__new__`, :meth:`__getnewargs__`,
Martin Panterd21e0b52015-10-10 10:36:22 +00001134:meth:`__str__` and :meth:`__repr__`).
Ethan Furman9a1daf52013-09-27 22:58:06 -07001135
1136
1137Enum Members (aka instances)
1138^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1139
1140The most interesting thing about Enum members is that they are singletons.
1141:class:`EnumMeta` creates them all while it is creating the :class:`Enum`
1142class itself, and then puts a custom :meth:`__new__` in place to ensure
1143that no new ones are ever instantiated by returning only the existing
1144member instances.
1145
1146
1147Finer Points
1148^^^^^^^^^^^^
1149
Ethan Furman65a5a472016-09-01 23:55:19 -07001150Supported ``__dunder__`` names
Ethan Furman6a137e82016-09-07 08:17:15 -07001151""""""""""""""""""""""""""""""
Ethan Furman9a1daf52013-09-27 22:58:06 -07001152
INADA Naokie57f91a2018-06-19 01:14:26 +09001153:attr:`__members__` is a read-only ordered mapping of ``member_name``:``member``
Ethan Furman65a5a472016-09-01 23:55:19 -07001154items. It is only available on the class.
Ethan Furman9a1daf52013-09-27 22:58:06 -07001155
Ethan Furman65a5a472016-09-01 23:55:19 -07001156:meth:`__new__`, if specified, must create and return the enum members; it is
1157also a very good idea to set the member's :attr:`_value_` appropriately. Once
1158all the members are created it is no longer used.
Ethan Furman748dad52015-11-20 13:12:26 -08001159
Ethan Furman60255b62016-01-15 15:01:33 -08001160
Ethan Furman65a5a472016-09-01 23:55:19 -07001161Supported ``_sunder_`` names
Ethan Furman6a137e82016-09-07 08:17:15 -07001162""""""""""""""""""""""""""""
Ethan Furman60255b62016-01-15 15:01:33 -08001163
Ethan Furman65a5a472016-09-01 23:55:19 -07001164- ``_name_`` -- name of the member
1165- ``_value_`` -- value of the member; can be set / modified in ``__new__``
Ethan Furman9a1daf52013-09-27 22:58:06 -07001166
Ethan Furman65a5a472016-09-01 23:55:19 -07001167- ``_missing_`` -- a lookup function used when a value is not found; may be
1168 overridden
Antoined3c8d732019-08-20 03:41:31 +02001169- ``_ignore_`` -- a list of names, either as a :class:`list` or a :class:`str`,
Ethan Furmana4b1bb42018-01-22 07:56:37 -08001170 that will not be transformed into members, and will be removed from the final
1171 class
Ethan Furman65a5a472016-09-01 23:55:19 -07001172- ``_order_`` -- used in Python 2/3 code to ensure member order is consistent
1173 (class attribute, removed during class creation)
Ethan Furmanc16595e2016-09-10 23:36:59 -07001174- ``_generate_next_value_`` -- used by the `Functional API`_ and by
1175 :class:`auto` to get an appropriate value for an enum member; may be
1176 overridden
Ethan Furman9a1daf52013-09-27 22:58:06 -07001177
Ethan Furman7aaeb2a2021-01-25 14:26:19 -08001178.. note::
1179
1180 For standard :class:`Enum` classes the next value chosen is the last value seen
1181 incremented by one.
1182
1183 For :class:`Flag`-type classes the next value chosen will be the next highest
1184 power-of-two, regardless of the last value seen.
1185
Ethan Furmanc16595e2016-09-10 23:36:59 -07001186.. versionadded:: 3.6 ``_missing_``, ``_order_``, ``_generate_next_value_``
Ethan Furmana4b1bb42018-01-22 07:56:37 -08001187.. versionadded:: 3.7 ``_ignore_``
Ethan Furman332dbc72016-08-20 00:00:52 -07001188
Ethan Furman65a5a472016-09-01 23:55:19 -07001189To help keep Python 2 / Python 3 code in sync an :attr:`_order_` attribute can
1190be provided. It will be checked against the actual order of the enumeration
1191and raise an error if the two do not match::
Ethan Furmane8e61272016-08-20 07:19:31 -07001192
1193 >>> class Color(Enum):
Ethan Furman23bb6f42016-11-21 09:22:05 -08001194 ... _order_ = 'RED GREEN BLUE'
1195 ... RED = 1
1196 ... BLUE = 3
1197 ... GREEN = 2
Ethan Furmane8e61272016-08-20 07:19:31 -07001198 ...
1199 Traceback (most recent call last):
1200 ...
Ethan Furman7aaeb2a2021-01-25 14:26:19 -08001201 TypeError: member order does not match _order_:
1202 ['RED', 'BLUE', 'GREEN']
1203 ['RED', 'GREEN', 'BLUE']
Ethan Furmane8e61272016-08-20 07:19:31 -07001204
1205.. note::
1206
1207 In Python 2 code the :attr:`_order_` attribute is necessary as definition
Ethan Furman65a5a472016-09-01 23:55:19 -07001208 order is lost before it can be recorded.
1209
Ethan Furman7cf0aad2020-12-09 17:12:11 -08001210
1211_Private__names
1212"""""""""""""""
1213
1214Private names are not converted to Enum members, but remain normal attributes.
1215
1216.. versionchanged:: 3.10
1217
1218
Ethan Furman65a5a472016-09-01 23:55:19 -07001219``Enum`` member type
Ethan Furman6a137e82016-09-07 08:17:15 -07001220""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001221
Ethan Furman54924df2016-09-07 23:40:31 -07001222:class:`Enum` members are instances of their :class:`Enum` class, and are
Ethan Furman7aaeb2a2021-01-25 14:26:19 -08001223normally accessed as ``EnumClass.member``. In Python versions ``3.5`` to
1224``3.9`` you could access members from other members -- this practice was
1225discouraged, and in ``3.10`` :class:`Enum` has returned to not allowing it::
Ethan Furman65a5a472016-09-01 23:55:19 -07001226
1227 >>> class FieldTypes(Enum):
1228 ... name = 0
1229 ... value = 1
1230 ... size = 2
1231 ...
1232 >>> FieldTypes.value.size
Ethan Furman7aaeb2a2021-01-25 14:26:19 -08001233 Traceback (most recent call last):
1234 ...
1235 AttributeError: FieldTypes: no attribute 'size'
Ethan Furman65a5a472016-09-01 23:55:19 -07001236
1237.. versionchanged:: 3.5
Ethan Furman7aaeb2a2021-01-25 14:26:19 -08001238.. versionchanged:: 3.10
Ethan Furman65a5a472016-09-01 23:55:19 -07001239
1240
Ethan Furman0063ff42020-09-21 17:23:13 -07001241Creating members that are mixed with other data types
1242"""""""""""""""""""""""""""""""""""""""""""""""""""""
1243
1244When subclassing other data types, such as :class:`int` or :class:`str`, with
1245an :class:`Enum`, all values after the `=` are passed to that data type's
1246constructor. For example::
1247
1248 >>> class MyEnum(IntEnum):
1249 ... example = '11', 16 # '11' will be interpreted as a hexadecimal
1250 ... # number
1251 >>> MyEnum.example
1252 <MyEnum.example: 17>
1253
1254
Ethan Furman65a5a472016-09-01 23:55:19 -07001255Boolean value of ``Enum`` classes and members
Ethan Furman6a137e82016-09-07 08:17:15 -07001256"""""""""""""""""""""""""""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001257
Ethan Furman54924df2016-09-07 23:40:31 -07001258:class:`Enum` members that are mixed with non-:class:`Enum` types (such as
Ethan Furman65a5a472016-09-01 23:55:19 -07001259:class:`int`, :class:`str`, etc.) are evaluated according to the mixed-in
Ethan Furman54924df2016-09-07 23:40:31 -07001260type's rules; otherwise, all members evaluate as :data:`True`. To make your
1261own Enum's boolean evaluation depend on the member's value add the following to
Ethan Furman65a5a472016-09-01 23:55:19 -07001262your class::
1263
1264 def __bool__(self):
1265 return bool(self.value)
1266
Ethan Furman54924df2016-09-07 23:40:31 -07001267:class:`Enum` classes always evaluate as :data:`True`.
Ethan Furman65a5a472016-09-01 23:55:19 -07001268
1269
1270``Enum`` classes with methods
Ethan Furman6a137e82016-09-07 08:17:15 -07001271"""""""""""""""""""""""""""""
Ethan Furman65a5a472016-09-01 23:55:19 -07001272
1273If you give your :class:`Enum` subclass extra methods, like the `Planet`_
1274class above, those methods will show up in a :func:`dir` of the member,
1275but not of the class::
1276
1277 >>> dir(Planet)
1278 ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__']
1279 >>> dir(Planet.EARTH)
Ethan Furman7aaeb2a2021-01-25 14:26:19 -08001280 ['__class__', '__doc__', '__module__', 'mass', 'name', 'radius', 'surface_gravity', 'value']
Ethan Furman65a5a472016-09-01 23:55:19 -07001281
Ethan Furman3515dcc2016-09-18 13:15:41 -07001282
1283Combining members of ``Flag``
1284"""""""""""""""""""""""""""""
1285
Ethan Furman7aaeb2a2021-01-25 14:26:19 -08001286Iterating over a combination of Flag members will only return the members that
1287are comprised of a single bit::
Ethan Furman3515dcc2016-09-18 13:15:41 -07001288
1289 >>> class Color(Flag):
Ethan Furman23bb6f42016-11-21 09:22:05 -08001290 ... RED = auto()
1291 ... GREEN = auto()
1292 ... BLUE = auto()
1293 ... MAGENTA = RED | BLUE
1294 ... YELLOW = RED | GREEN
1295 ... CYAN = GREEN | BLUE
Ethan Furman3515dcc2016-09-18 13:15:41 -07001296 ...
Ethan Furman7aaeb2a2021-01-25 14:26:19 -08001297 >>> Color(3)
Ethan Furman23bb6f42016-11-21 09:22:05 -08001298 <Color.YELLOW: 3>
Ethan Furman7aaeb2a2021-01-25 14:26:19 -08001299 >>> Color(7)
1300 <Color.RED|GREEN|BLUE: 7>
Ethan Furman3515dcc2016-09-18 13:15:41 -07001301
Ethan Furmand986d162020-09-22 13:00:07 -07001302``StrEnum`` and :meth:`str.__str__`
1303"""""""""""""""""""""""""""""""""""
1304
1305An important difference between :class:`StrEnum` and other Enums is the
1306:meth:`__str__` method; because :class:`StrEnum` members are strings, some
1307parts of Python will read the string data directly, while others will call
1308:meth:`str()`. To make those two operations have the same result,
1309:meth:`StrEnum.__str__` will be the same as :meth:`str.__str__` so that
1310``str(StrEnum.member) == StrEnum.member`` is true.
1311
Ethan Furman7aaeb2a2021-01-25 14:26:19 -08001312``Flag`` and ``IntFlag`` minutia
1313""""""""""""""""""""""""""""""""
1314
1315The code sample::
1316
1317 >>> class Color(IntFlag):
1318 ... BLACK = 0
1319 ... RED = 1
1320 ... GREEN = 2
1321 ... BLUE = 4
1322 ... PURPLE = RED | BLUE
1323 ... WHITE = RED | GREEN | BLUE
1324 ...
1325
1326- single-bit flags are canonical
1327- multi-bit and zero-bit flags are aliases
1328- only canonical flags are returned during iteration::
1329
1330 >>> list(Color.WHITE)
1331 [<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 4>]
1332
1333- negating a flag or flag set returns a new flag/flag set with the
1334 corresponding positive integer value::
1335
1336 >>> Color.GREEN
1337 <Color.GREEN: 2>
1338
1339 >>> ~Color.GREEN
1340 <Color.PURPLE: 5>
1341
1342- names of pseudo-flags are constructed from their members' names::
1343
1344 >>> (Color.RED | Color.GREEN).name
1345 'RED|GREEN'
1346
1347- multi-bit flags, aka aliases, can be returned from operations::
1348
1349 >>> Color.RED | Color.BLUE
1350 <Color.PURPLE: 5>
1351
1352 >>> Color(7) # or Color(-1)
1353 <Color.WHITE: 7>
1354
1355- membership / containment checking has changed slightly -- zero valued flags
1356 are never considered to be contained::
1357
1358 >>> Color.BLACK in Color.WHITE
1359 False
1360
1361 otherwise, if all bits of one flag are in the other flag, True is returned::
1362
1363 >>> Color.PURPLE in Color.WHITE
1364 True
1365
1366There is a new boundary mechanism that controls how out-of-range / invalid
1367bits are handled: ``STRICT``, ``CONFORM``, ``EJECT`', and ``KEEP``:
1368
1369 * STRICT --> raises an exception when presented with invalid values
1370 * CONFORM --> discards any invalid bits
1371 * EJECT --> lose Flag status and become a normal int with the given value
1372 * KEEP --> keep the extra bits
1373 - keeps Flag status and extra bits
1374 - extra bits do not show up in iteration
1375 - extra bits do show up in repr() and str()
1376
1377The default for Flag is ``STRICT``, the default for ``IntFlag`` is ``DISCARD``,
1378and the default for ``_convert_`` is ``KEEP`` (see ``ssl.Options`` for an
1379example of when ``KEEP`` is needed).