blob: d3df151b71ea942dbc5bd408cf0c1397a3c8a702 [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
Ethan Furmanb7751062021-03-30 21:17:26 -070016.. sidebar:: Important
17
18 This page contains the API reference information. For tutorial
19 information and discussion of more advanced topics, see
20
21 * :ref:`Basic Tutorial <enum-basic-tutorial>`
22 * :ref:`Advanced Tutorial <enum-advanced-tutorial>`
23 * :ref:`Enum Cookbook <enum-cookbook>`
24
Ethan Furman1b4addf2021-06-18 14:25:42 -070025---------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -070026
Ethan Furmanb7751062021-03-30 21:17:26 -070027An enumeration:
Ethan Furmanc72e6382014-02-06 08:13:14 -080028
Ethan Furmanb7751062021-03-30 21:17:26 -070029* is a set of symbolic names (members) bound to unique values
30* can be iterated over to return its members in definition order
Ethan Furman74964862021-06-10 07:24:20 -070031* uses *call* syntax to return members by value
32* uses *index* syntax to return members by name
Ethan Furman542e1df2020-09-14 13:32:44 -070033
Ethan Furmanb7751062021-03-30 21:17:26 -070034Enumerations are created either by using the :keyword:`class` syntax, or by
35using function-call syntax::
36
37 >>> from enum import Enum
38
39 >>> # class syntax
40 >>> class Color(Enum):
41 ... RED = 1
42 ... GREEN = 2
43 ... BLUE = 3
44
45 >>> # functional syntax
46 >>> Color = Enum('Color', ['RED', 'GREEN', 'BLUE'])
47
48Even though we can use the :keyword:`class` syntax to create Enums, Enums
49are not normal Python classes. See
50:ref:`How are Enums different? <enum-class-differences>` for more details.
51
52.. note:: Nomenclature
53
54 - The class :class:`Color` is an *enumeration* (or *enum*)
55 - The attributes :attr:`Color.RED`, :attr:`Color.GREEN`, etc., are
56 *enumeration members* (or *enum members*) and are functionally constants.
57 - The enum members have *names* and *values* (the name of
58 :attr:`Color.RED` is ``RED``, the value of :attr:`Color.BLUE` is
59 ``3``, etc.)
Ethan Furman542e1df2020-09-14 13:32:44 -070060
Ethan Furman1b4addf2021-06-18 14:25:42 -070061---------------
Ethan Furmanc72e6382014-02-06 08:13:14 -080062
63Module Contents
64---------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -070065
Ethan Furmanb7751062021-03-30 21:17:26 -070066 :class:`EnumType`
Ethan Furmanc72e6382014-02-06 08:13:14 -080067
Ethan Furmanb7751062021-03-30 21:17:26 -070068 The ``type`` for Enum and its subclasses.
Ethan Furmanc72e6382014-02-06 08:13:14 -080069
Ethan Furmanb7751062021-03-30 21:17:26 -070070 :class:`Enum`
Ethan Furmanc72e6382014-02-06 08:13:14 -080071
Ethan Furmanb7751062021-03-30 21:17:26 -070072 Base class for creating enumerated constants.
Ethan Furmanc72e6382014-02-06 08:13:14 -080073
Ethan Furmanb7751062021-03-30 21:17:26 -070074 :class:`IntEnum`
Ethan Furmanc72e6382014-02-06 08:13:14 -080075
Ethan Furmanb7751062021-03-30 21:17:26 -070076 Base class for creating enumerated constants that are also
Ethan Furman1b4addf2021-06-18 14:25:42 -070077 subclasses of :class:`int`. (`Notes`_)
Ethan Furman0063ff42020-09-21 17:23:13 -070078
Ethan Furmanb7751062021-03-30 21:17:26 -070079 :class:`StrEnum`
Ethan Furman0063ff42020-09-21 17:23:13 -070080
Ethan Furmanb7751062021-03-30 21:17:26 -070081 Base class for creating enumerated constants that are also
Ethan Furman1b4addf2021-06-18 14:25:42 -070082 subclasses of :class:`str`. (`Notes`_)
Ethan Furman65a5a472016-09-01 23:55:19 -070083
Ethan Furmanb7751062021-03-30 21:17:26 -070084 :class:`Flag`
Ethan Furman65a5a472016-09-01 23:55:19 -070085
Ethan Furmanb7751062021-03-30 21:17:26 -070086 Base class for creating enumerated constants that can be combined using
87 the bitwise operations without losing their :class:`Flag` membership.
Ethan Furman65a5a472016-09-01 23:55:19 -070088
Ethan Furmanb7751062021-03-30 21:17:26 -070089 :class:`IntFlag`
Ethan Furman65a5a472016-09-01 23:55:19 -070090
Ethan Furmanb7751062021-03-30 21:17:26 -070091 Base class for creating enumerated constants that can be combined using
92 the bitwise operators without losing their :class:`IntFlag` membership.
Ethan Furman1b4addf2021-06-18 14:25:42 -070093 :class:`IntFlag` members are also subclasses of :class:`int`. (`Notes`_)
Ethan Furmanc72e6382014-02-06 08:13:14 -080094
Ethan Furman74964862021-06-10 07:24:20 -070095 :class:`EnumCheck`
96
97 An enumeration with the values ``CONTINUOUS``, ``NAMED_FLAGS``, and
98 ``UNIQUE``, for use with :func:`verify` to ensure various constraints
99 are met by a given enumeration.
100
Ethan Furmanb7751062021-03-30 21:17:26 -0700101 :class:`FlagBoundary`
Ethan Furmanf24bb352013-07-18 17:05:39 -0700102
Ethan Furmanb7751062021-03-30 21:17:26 -0700103 An enumeration with the values ``STRICT``, ``CONFORM``, ``EJECT``, and
104 ``KEEP`` which allows for more fine-grained control over how invalid values
105 are dealt with in an enumeration.
Ethan Furmanc16595e2016-09-10 23:36:59 -0700106
Ethan Furmanb7751062021-03-30 21:17:26 -0700107 :class:`auto`
108
109 Instances are replaced with an appropriate value for Enum members.
110 :class:`StrEnum` defaults to the lower-cased version of the member name,
111 while other Enums default to 1 and increase from there.
112
113 :func:`global_enum`
114
115 :class:`Enum` class decorator to apply the appropriate global `__repr__`,
116 and export its members into the global name space.
117
Miss Islington (bot)377f3d42021-05-04 06:24:46 -0700118 :func:`.property`
Ethan Furmanb7751062021-03-30 21:17:26 -0700119
120 Allows :class:`Enum` members to have attributes without conflicting with
121 other members' names.
122
123 :func:`unique`
124
125 Enum class decorator that ensures only one name is bound to any one value.
126
Ethan Furman74964862021-06-10 07:24:20 -0700127 :func:`verify`
128
129 Enum class decorator that checks user-selectable constraints on an
130 enumeration.
131
Ethan Furmanc16595e2016-09-10 23:36:59 -0700132
133.. versionadded:: 3.6 ``Flag``, ``IntFlag``, ``auto``
Ethan Furman74964862021-06-10 07:24:20 -0700134.. versionadded:: 3.10 ``StrEnum``, ``EnumCheck``, ``FlagBoundary``
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700135
Ethan Furman1b4addf2021-06-18 14:25:42 -0700136---------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700137
Ethan Furmanb7751062021-03-30 21:17:26 -0700138Data Types
139----------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700140
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700141
Ethan Furmanb7751062021-03-30 21:17:26 -0700142.. class:: EnumType
Ethan Furmanc16595e2016-09-10 23:36:59 -0700143
Ethan Furmanb7751062021-03-30 21:17:26 -0700144 *EnumType* is the :term:`metaclass` for *enum* enumerations. It is possible
145 to subclass *EnumType* -- see :ref:`Subclassing EnumType <enumtype-examples>`
146 for details.
Ethan Furmanc16595e2016-09-10 23:36:59 -0700147
Ethan Furmanb7751062021-03-30 21:17:26 -0700148 .. method:: EnumType.__contains__(cls, member)
Ethan Furman455bfde2013-09-08 23:48:34 -0700149
Ethan Furmanb7751062021-03-30 21:17:26 -0700150 Returns ``True`` if member belongs to the ``cls``::
151
152 >>> some_var = Color.RED
153 >>> some_var in Color
154 True
155
Ethan Furman6bd92882021-04-27 13:05:08 -0700156 .. note::
157
158 In Python 3.12 it will be possible to check for member values and not
159 just members; until then, a ``TypeError`` will be raised if a
160 non-Enum-member is used in a containment check.
161
Ethan Furmanb7751062021-03-30 21:17:26 -0700162 .. method:: EnumType.__dir__(cls)
163
164 Returns ``['__class__', '__doc__', '__members__', '__module__']`` and the
165 names of the members in *cls*::
166
167 >>> dir(Color)
168 ['BLUE', 'GREEN', 'RED', '__class__', '__doc__', '__members__', '__module__']
169
170 .. method:: EnumType.__getattr__(cls, name)
171
172 Returns the Enum member in *cls* matching *name*, or raises an :exc:`AttributeError`::
173
174 >>> Color.GREEN
175 Color.GREEN
176
177 .. method:: EnumType.__getitem__(cls, name)
178
179 Returns the Enum member in *cls* matching *name*, or raises an :exc:`KeyError`::
180
181 >>> Color['BLUE']
182 Color.BLUE
183
184 .. method:: EnumType.__iter__(cls)
185
186 Returns each member in *cls* in definition order::
187
188 >>> list(Color)
189 [Color.RED, Color.GREEN, Color.BLUE]
190
191 .. method:: EnumType.__len__(cls)
192
193 Returns the number of member in *cls*::
194
195 >>> len(Color)
196 3
197
198 .. method:: EnumType.__reversed__(cls)
199
200 Returns each member in *cls* in reverse definition order::
201
202 >>> list(reversed(Color))
203 [Color.BLUE, Color.GREEN, Color.RED]
204
205
206.. class:: Enum
207
208 *Enum* is the base class for all *enum* enumerations.
209
210 .. attribute:: Enum.name
211
212 The name used to define the ``Enum`` member::
213
214 >>> Color.BLUE.name
215 'BLUE'
216
217 .. attribute:: Enum.value
218
219 The value given to the ``Enum`` member::
220
221 >>> Color.RED.value
222 1
223
224 .. note:: Enum member values
225
226 Member values can be anything: :class:`int`, :class:`str`, etc.. If
227 the exact value is unimportant you may use :class:`auto` instances and an
228 appropriate value will be chosen for you. Care must be taken if you mix
229 :class:`auto` with other values.
230
231 .. attribute:: Enum._ignore_
232
233 ``_ignore_`` is only used during creation and is removed from the
234 enumeration once that is complete.
235
236 ``_ignore_`` is a list of names that will not become members, and whose
237 names will also be removed from the completed enumeration. See
238 :ref:`TimePeriod <enum-time-period>` for an example.
239
240 .. method:: Enum.__call__(cls, value, names=None, \*, module=None, qualname=None, type=None, start=1, boundary=None)
241
242 This method is called in two different ways:
243
244 * to look up an existing member:
245
246 :cls: The enum class being called.
247 :value: The value to lookup.
248
249 * to use the ``cls`` enum to create a new enum:
250
251 :cls: The enum class being called.
252 :value: The name of the new Enum to create.
253 :names: The names/values of the members for the new Enum.
254 :module: The name of the module the new Enum is created in.
255 :qualname: The actual location in the module where this Enum can be found.
256 :type: A mix-in type for the new Enum.
257 :start: The first integer value for the Enum (used by :class:`auto`)
258 :boundary: How to handle out-of-range values from bit operations (:class:`Flag` only)
259
260 .. method:: Enum.__dir__(self)
261
262 Returns ``['__class__', '__doc__', '__module__', 'name', 'value']`` and
263 any public methods defined on *self.__class__*::
264
265 >>> from datetime import date
266 >>> class Weekday(Enum):
267 ... MONDAY = 1
268 ... TUESDAY = 2
269 ... WEDNESDAY = 3
270 ... THURSDAY = 4
271 ... FRIDAY = 5
272 ... SATURDAY = 6
273 ... SUNDAY = 7
274 ... @classmethod
275 ... def today(cls):
276 ... print('today is %s' % cls(date.today.isoweekday).naem)
277 >>> dir(Weekday.SATURDAY)
278 ['__class__', '__doc__', '__module__', 'name', 'today', 'value']
279
280 .. method:: Enum._generate_next_value_(name, start, count, last_values)
281
282 :name: The name of the member being defined (e.g. 'RED').
283 :start: The start value for the Enum; the default is 1.
284 :count: The number of members currently defined, not including this one.
285 :last_values: A list of the previous values.
286
287 A *staticmethod* that is used to determine the next value returned by
288 :class:`auto`::
289
290 >>> from enum import auto
291 >>> class PowersOfThree(Enum):
292 ... @staticmethod
293 ... def _generate_next_value_(name, start, count, last_values):
294 ... return (count + 1) * 3
295 ... FIRST = auto()
296 ... SECOND = auto()
297 >>> PowersOfThree.SECOND.value
298 6
299
300 .. method:: Enum._missing_(cls, value)
301
302 A *classmethod* for looking up values not found in *cls*. By default it
303 does nothing, but can be overridden to implement custom search behavior::
304
305 >>> from enum import StrEnum
306 >>> class Build(StrEnum):
307 ... DEBUG = auto()
308 ... OPTIMIZED = auto()
309 ... @classmethod
310 ... def _missing_(cls, value):
311 ... value = value.lower()
312 ... for member in cls:
313 ... if member.value == value:
314 ... return member
315 ... return None
316 >>> Build.DEBUG.value
317 'debug'
318 >>> Build('deBUG')
319 Build.DEBUG
320
321 .. method:: Enum.__repr__(self)
322
323 Returns the string used for *repr()* calls. By default, returns the
324 *Enum* name and the member name, but can be overridden::
325
326 >>> class OldStyle(Enum):
327 ... RETRO = auto()
328 ... OLD_SCHOOl = auto()
329 ... YESTERYEAR = auto()
330 ... def __repr__(self):
331 ... cls_name = self.__class__.__name__
332 ... return f'<{cls_name}.{self.name}: {self.value}>'
333 >>> OldStyle.RETRO
334 <OldStyle.RETRO: 1>
335
336 .. method:: Enum.__str__(self)
337
338 Returns the string used for *str()* calls. By default, returns the
339 member name, but can be overridden::
340
341 >>> class OldStyle(Enum):
342 ... RETRO = auto()
343 ... OLD_SCHOOl = auto()
344 ... YESTERYEAR = auto()
345 ... def __str__(self):
346 ... cls_name = self.__class__.__name__
347 ... return f'{cls_name}.{self.name}'
348 >>> OldStyle.RETRO
349 OldStyle.RETRO
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700350
Ethan Furman9a1daf52013-09-27 22:58:06 -0700351.. note::
352
Ethan Furmanb7751062021-03-30 21:17:26 -0700353 Using :class:`auto` with :class:`Enum` results in integers of increasing value,
354 starting with ``1``.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700355
356
Ethan Furmanb7751062021-03-30 21:17:26 -0700357.. class:: IntEnum
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700358
Ethan Furmanb7751062021-03-30 21:17:26 -0700359 *IntEnum* is the same as *Enum*, but its members are also integers and can be
360 used anywhere that an integer can be used. If any integer operation is performed
361 with an *IntEnum* member, the resulting value loses its enumeration status.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700362
Ethan Furmanb7751062021-03-30 21:17:26 -0700363 >>> from enum import IntEnum
364 >>> class Numbers(IntEnum):
365 ... ONE = 1
366 ... TWO = 2
367 ... THREE = 3
368 >>> Numbers.THREE
369 Numbers.THREE
370 >>> Numbers.ONE + Numbers.TWO
371 3
372 >>> Numbers.THREE + 5
373 8
374 >>> Numbers.THREE == 3
375 True
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700376
Ethan Furman101e0742013-09-15 12:34:36 -0700377.. note::
378
Ethan Furmanb7751062021-03-30 21:17:26 -0700379 Using :class:`auto` with :class:`IntEnum` results in integers of increasing value,
380 starting with ``1``.
Ethan Furman101e0742013-09-15 12:34:36 -0700381
Ethan Furmanf24bb352013-07-18 17:05:39 -0700382
Ethan Furmanb7751062021-03-30 21:17:26 -0700383.. class:: StrEnum
Ethan Furmanf24bb352013-07-18 17:05:39 -0700384
Ethan Furmanb7751062021-03-30 21:17:26 -0700385 *StrEnum* is the same as *Enum*, but its members are also strings and can be used
386 in most of the same places that a string can be used. The result of any string
387 operation performed on or with a *StrEnum* member is not part of the enumeration.
388
389 .. note:: There are places in the stdlib that check for an exact :class:`str`
390 instead of a :class:`str` subclass (i.e. ``type(unknown) == str``
391 instead of ``isinstance(str, unknown)``), and in those locations you
392 will need to use ``str(StrEnum.member)``.
393
394
395.. note::
396
397 Using :class:`auto` with :class:`StrEnum` results in values of the member name,
398 lower-cased.
399
400
401.. class:: Flag
402
403 *Flag* members support the bitwise operators ``&`` (*AND*), ``|`` (*OR*),
404 ``^`` (*XOR*), and ``~`` (*INVERT*); the results of those operators are members
405 of the enumeration.
406
407 .. method:: __contains__(self, value)
408
409 Returns *True* if value is in self::
410
411 >>> from enum import Flag, auto
412 >>> class Color(Flag):
413 ... RED = auto()
414 ... GREEN = auto()
415 ... BLUE = auto()
416 >>> purple = Color.RED | Color.BLUE
417 >>> white = Color.RED | Color.GREEN | Color.BLUE
418 >>> Color.GREEN in purple
419 False
420 >>> Color.GREEN in white
421 True
422 >>> purple in white
423 True
424 >>> white in purple
425 False
426
427 .. method:: __iter__(self):
428
429 Returns all contained members::
430
431 >>> list(Color.RED)
432 [Color.RED]
433 >>> list(purple)
434 [Color.RED, Color.BLUE]
435
436 .. method:: __len__(self):
437
438 Returns number of members in flag::
439
440 >>> len(Color.GREEN)
441 1
442 >>> len(white)
443 3
444
445 .. method:: __bool__(self):
446
447 Returns *True* if any members in flag, *False* otherwise::
448
449 >>> bool(Color.GREEN)
450 True
451 >>> bool(white)
452 True
453 >>> black = Color(0)
454 >>> bool(black)
455 False
456
457 .. method:: __or__(self, other)
458
459 Returns current flag binary or'ed with other::
460
461 >>> Color.RED | Color.GREEN
462 Color.RED|Color.GREEN
463
464 .. method:: __and__(self, other)
465
466 Returns current flag binary and'ed with other::
467
468 >>> purple & white
469 Color.RED|Color.BLUE
470 >>> purple & Color.GREEN
471 0x0
472
473 .. method:: __xor__(self, other)
474
475 Returns current flag binary xor'ed with other::
476
477 >>> purple ^ white
478 Color.GREEN
479 >>> purple ^ Color.GREEN
480 Color.RED|Color.GREEN|Color.BLUE
481
482 .. method:: __invert__(self):
483
484 Returns all the flags in *type(self)* that are not in self::
485
486 >>> ~white
487 0x0
488 >>> ~purple
489 Color.GREEN
490 >>> ~Color.RED
491 Color.GREEN|Color.BLUE
492
493.. note::
494
495 Using :class:`auto` with :class:`Flag` results in integers that are powers
496 of two, starting with ``1``.
497
498
499.. class:: IntFlag
500
501 *IntFlag* is the same as *Flag*, but its members are also integers and can be
502 used anywhere that an integer can be used.
503
504 >>> from enum import IntFlag, auto
505 >>> class Color(IntFlag):
506 ... RED = auto()
507 ... GREEN = auto()
508 ... BLUE = auto()
509 >>> Color.RED & 2
510 0x0
511 >>> Color.RED | 2
512 Color.RED|Color.GREEN
513
514 If any integer operation is performed with an *IntFlag* member, the result is
515 not an *IntFlag*::
516
517 >>> Color.RED + 2
518 3
519
520 If a *Flag* operation is performed with an *IntFlag* member and:
521
522 * the result is a valid *IntFlag*: an *IntFlag* is returned
523 * the result is not a valid *IntFlag*: the result depends on the *FlagBoundary* setting
524
525.. note::
526
527 Using :class:`auto` with :class:`IntFlag` results in integers that are powers
528 of two, starting with ``1``.
529
Ethan Furman74964862021-06-10 07:24:20 -0700530.. class:: EnumCheck
531
532 *EnumCheck* contains the options used by the :func:`verify` decorator to ensure
533 various constraints; failed constraints result in a :exc:`TypeError`.
534
535 .. attribute:: UNIQUE
536
537 Ensure that each value has only one name::
538
539 >>> from enum import Enum, verify, UNIQUE
540 >>> @verify(UNIQUE)
541 ... class Color(Enum):
542 ... RED = 1
543 ... GREEN = 2
544 ... BLUE = 3
545 ... CRIMSON = 1
546 Traceback (most recent call last):
547 ...
548 ValueError: aliases found in <enum 'Color'>: CRIMSON -> RED
549
550
551 .. attribute:: CONTINUOUS
552
553 Ensure that there are no missing values between the lowest-valued member
554 and the highest-valued member::
555
556 >>> from enum import Enum, verify, CONTINUOUS
557 >>> @verify(CONTINUOUS)
558 ... class Color(Enum):
559 ... RED = 1
560 ... GREEN = 2
561 ... BLUE = 5
562 Traceback (most recent call last):
563 ...
564 ValueError: invalid enum 'Color': missing values 3, 4
565
566 .. attribute:: NAMED_FLAGS
567
568 Ensure that any flag groups/masks contain only named flags -- useful when
569 values are specified instead of being generated by :func:`auto`
570
571 >>> from enum import Flag, verify, NAMED_FLAGS
572 >>> @verify(NAMED_FLAGS)
573 ... class Color(Flag):
574 ... RED = 1
575 ... GREEN = 2
576 ... BLUE = 4
577 ... WHITE = 15
578 ... NEON = 31
579 Traceback (most recent call last):
580 ...
Ethan Furman41c2a4a2021-06-15 18:50:59 -0700581 ValueError: invalid Flag 'Color': aliases WHITE and NEON are missing combined values of 0x18 [use enum.show_flag_values(value) for details]
Ethan Furman74964862021-06-10 07:24:20 -0700582
583.. note::
584
585 CONTINUOUS and NAMED_FLAGS are designed to work with integer-valued members.
586
587.. versionadded:: 3.10
588
Ethan Furmanb7751062021-03-30 21:17:26 -0700589.. class:: FlagBoundary
590
591 *FlagBoundary* controls how out-of-range values are handled in *Flag* and its
592 subclasses.
593
594 .. attribute:: STRICT
595
596 Out-of-range values cause a :exc:`ValueError` to be raised. This is the
597 default for :class:`Flag`::
598
Ethan Furman49aec1a2021-03-31 09:20:08 -0700599 >>> from enum import Flag, STRICT
Ethan Furmanb7751062021-03-30 21:17:26 -0700600 >>> class StrictFlag(Flag, boundary=STRICT):
601 ... RED = auto()
602 ... GREEN = auto()
603 ... BLUE = auto()
604 >>> StrictFlag(2**2 + 2**4)
605 Traceback (most recent call last):
606 ...
607 ValueError: StrictFlag: invalid value: 20
608 given 0b0 10100
609 allowed 0b0 00111
610
611 .. attribute:: CONFORM
612
613 Out-of-range values have invalid values removed, leaving a valid *Flag*
614 value::
615
Ethan Furman49aec1a2021-03-31 09:20:08 -0700616 >>> from enum import Flag, CONFORM
Ethan Furmanb7751062021-03-30 21:17:26 -0700617 >>> class ConformFlag(Flag, boundary=CONFORM):
618 ... RED = auto()
619 ... GREEN = auto()
620 ... BLUE = auto()
621 >>> ConformFlag(2**2 + 2**4)
622 ConformFlag.BLUE
623
624 .. attribute:: EJECT
625
626 Out-of-range values lose their *Flag* membership and revert to :class:`int`.
627 This is the default for :class:`IntFlag`::
628
Ethan Furman49aec1a2021-03-31 09:20:08 -0700629 >>> from enum import Flag, EJECT
Ethan Furmanb7751062021-03-30 21:17:26 -0700630 >>> class EjectFlag(Flag, boundary=EJECT):
631 ... RED = auto()
632 ... GREEN = auto()
633 ... BLUE = auto()
634 >>> EjectFlag(2**2 + 2**4)
635 20
636
637 .. attribute:: KEEP
638
639 Out-of-range values are kept, and the *Flag* membership is kept. This is
640 used for some stdlib flags:
641
Ethan Furman49aec1a2021-03-31 09:20:08 -0700642 >>> from enum import Flag, KEEP
Ethan Furmanb7751062021-03-30 21:17:26 -0700643 >>> class KeepFlag(Flag, boundary=KEEP):
644 ... RED = auto()
645 ... GREEN = auto()
646 ... BLUE = auto()
647 >>> KeepFlag(2**2 + 2**4)
648 KeepFlag.BLUE|0x10
649
Ethan Furman74964862021-06-10 07:24:20 -0700650.. versionadded:: 3.10
Ethan Furmanb7751062021-03-30 21:17:26 -0700651
Ethan Furman1b4addf2021-06-18 14:25:42 -0700652---------------
653
Ethan Furmanb7751062021-03-30 21:17:26 -0700654Utilites and Decorators
655-----------------------
656
657.. class:: auto
658
659 *auto* can be used in place of a value. If used, the *Enum* machinery will
660 call an *Enum*'s :meth:`_generate_next_value_` to get an appropriate value.
661 For *Enum* and *IntEnum* that appropriate value will be the last value plus
662 one; for *Flag* and *IntFlag* it will be the first power-of-two greater
663 than the last value; for *StrEnum* it will be the lower-cased version of the
664 member's name.
665
666 ``_generate_next_value_`` can be overridden to customize the values used by
667 *auto*.
668
669.. decorator:: global_enum
670
671 A :keyword:`class` decorator specifically for enumerations. It replaces the
672 :meth:`__repr__` method with one that shows *module_name*.*member_name*. It
Miss Islington (bot)37da1f02021-05-22 13:55:17 -0700673 also injects the members, and their aliases, into the global namespace they
674 were defined in.
Ethan Furmanb7751062021-03-30 21:17:26 -0700675
676
677.. decorator:: property
678
679 A decorator similar to the built-in *property*, but specifically for
680 enumerations. It allows member attributes to have the same names as members
681 themselves.
682
683 .. note:: the *property* and the member must be defined in separate classes;
684 for example, the *value* and *name* attributes are defined in the
685 *Enum* class, and *Enum* subclasses can define members with the
686 names ``value`` and ``name``.
Ethan Furmanf24bb352013-07-18 17:05:39 -0700687
688.. decorator:: unique
689
Ethan Furmanb7751062021-03-30 21:17:26 -0700690 A :keyword:`class` decorator specifically for enumerations. It searches an
691 enumeration's :attr:`__members__`, gathering any aliases it finds; if any are
692 found :exc:`ValueError` is raised with the details::
Ethan Furmanf24bb352013-07-18 17:05:39 -0700693
Ethan Furmanb7751062021-03-30 21:17:26 -0700694 >>> from enum import Enum, unique
695 >>> @unique
696 ... class Mistake(Enum):
697 ... ONE = 1
698 ... TWO = 2
699 ... THREE = 3
700 ... FOUR = 3
701 ...
702 Traceback (most recent call last):
703 ...
704 ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
Ethan Furman74964862021-06-10 07:24:20 -0700705
706.. decorator:: verify
707
708 A :keyword:`class` decorator specifically for enumerations. Members from
709 :class:`EnumCheck` are used to specify which constraints should be checked
710 on the decorated enumeration.
711
712.. versionadded:: 3.10
Ethan Furman1b4addf2021-06-18 14:25:42 -0700713
714---------------
715
716Notes
717-----
718
719:class:`IntEnum`, :class:`StrEnum`, and :class:`IntFlag`
720
721 These three enum types are designed to be drop-in replacements for existing
722 integer- and string-based values; as such, they have extra limitations:
723
724 - ``format()`` will use the value of the enum member, unless ``__str__``
725 has been overridden
726
727 - ``StrEnum.__str__`` uses the value and not the name of the enum member
728
729 If you do not need/want those limitations, you can create your own base
730 class by mixing in the ``int`` or ``str`` type yourself::
731
732 >>> from enum import Enum
733 >>> class MyIntEnum(int, Enum):
734 ... pass