Debian Codegraph @

Doc/library/enum.rst

raw
1 :mod:`!enum` --- Support for enumerations
2 =========================================
3
4 .. module:: enum
5 :synopsis: Implementation of an enumeration class.
6
7 .. moduleauthor:: Ethan Furman <[email protected]>
8 .. sectionauthor:: Barry Warsaw <[email protected]>
9 .. sectionauthor:: Eli Bendersky <[email protected]>
10 .. sectionauthor:: Ethan Furman <[email protected]>
11
12 .. versionadded:: 3.4
13
14 **Source code:** :source:`Lib/enum.py`
15
16 .. 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
25 ---------------
26
27 An enumeration:
28
29 * is a set of symbolic names (members) bound to unique values
30 * can be iterated over to return its canonical (i.e. non-alias) members in
31 definition order
32 * uses *call* syntax to return members by value
33 * uses *index* syntax to return members by name
34
35 Enumerations are created either by using :keyword:`class` syntax, or by
36 using function-call syntax::
37
38 >>> from enum import Enum
39
40 >>> # class syntax
41 >>> class Color(Enum):
42 ... RED = 1
43 ... GREEN = 2
44 ... BLUE = 3
45
46 >>> # functional syntax
47 >>> Color = Enum('Color', [('RED', 1), ('GREEN', 2), ('BLUE', 3)])
48
49 Even though we can use :keyword:`class` syntax to create Enums, Enums
50 are not normal Python classes. See
51 :ref:`How are Enums different? <enum-class-differences>` for more details.
52
53 .. note:: Nomenclature
54
55 - The class :class:`!Color` is an *enumeration* (or *enum*)
56 - The attributes :attr:`!Color.RED`, :attr:`!Color.GREEN`, etc., are
57 *enumeration members* (or *members*) and are functionally constants.
58 - The enum members have *names* and *values* (the name of
59 :attr:`!Color.RED` is ``RED``, the value of :attr:`!Color.BLUE` is
60 ``3``, etc.)
61
62 ---------------
63
64 Module Contents
65 ---------------
66
67 :class:`EnumType`
68
69 The ``type`` for Enum and its subclasses.
70
71 :class:`Enum`
72
73 Base class for creating enumerated constants.
74
75 :class:`IntEnum`
76
77 Base class for creating enumerated constants that are also
78 subclasses of :class:`int`. (`Notes`_)
79
80 :class:`StrEnum`
81
82 Base class for creating enumerated constants that are also
83 subclasses of :class:`str`. (`Notes`_)
84
85 :class:`Flag`
86
87 Base class for creating enumerated constants that can be combined using
88 the bitwise operations without losing their :class:`Flag` membership.
89
90 :class:`IntFlag`
91
92 Base class for creating enumerated constants that can be combined using
93 the bitwise operators without losing their :class:`IntFlag` membership.
94 :class:`IntFlag` members are also subclasses of :class:`int`. (`Notes`_)
95
96 :class:`ReprEnum`
97
98 Used by :class:`IntEnum`, :class:`StrEnum`, and :class:`IntFlag`
99 to keep the :class:`str() <str>` of the mixed-in type.
100
101 :class:`EnumCheck`
102
103 An enumeration with the values ``CONTINUOUS``, ``NAMED_FLAGS``, and
104 ``UNIQUE``, for use with :func:`verify` to ensure various constraints
105 are met by a given enumeration.
106
107 :class:`FlagBoundary`
108
109 An enumeration with the values ``STRICT``, ``CONFORM``, ``EJECT``, and
110 ``KEEP`` which allows for more fine-grained control over how invalid values
111 are dealt with in an enumeration.
112
113 :class:`EnumDict`
114
115 A subclass of :class:`dict` for use when subclassing :class:`EnumType`.
116
117 :class:`auto`
118
119 Instances are replaced with an appropriate value for Enum members.
120 :class:`StrEnum` defaults to the lower-cased version of the member name,
121 while other Enums default to 1 and increase from there.
122
123 :func:`~enum.property`
124
125 Allows :class:`Enum` members to have attributes without conflicting with
126 member names. The ``value`` and ``name`` attributes are implemented this
127 way.
128
129 :func:`unique`
130
131 Enum class decorator that ensures only one name is bound to any one value.
132
133 :func:`verify`
134
135 Enum class decorator that checks user-selectable constraints on an
136 enumeration.
137
138 :func:`member`
139
140 Make ``obj`` a member. Can be used as a decorator.
141
142 :func:`nonmember`
143
144 Do not make ``obj`` a member. Can be used as a decorator.
145
146 :func:`global_enum`
147
148 Modify the :class:`str() <str>` and :func:`repr` of an enum
149 to show its members as belonging to the module instead of its class,
150 and export the enum members to the global namespace.
151
152 :func:`show_flag_values`
153
154 Return a list of all power-of-two integers contained in a flag.
155
156 :func:`enum.bin`
157
158 Like built-in :func:`bin`, except negative values are represented in
159 two's complement, and the leading bit always indicates sign
160 (``0`` implies positive, ``1`` implies negative).
161
162
163 .. versionadded:: 3.6 ``Flag``, ``IntFlag``, ``auto``
164 .. versionadded:: 3.11 ``StrEnum``, ``EnumCheck``, ``ReprEnum``, ``FlagBoundary``, ``property``, ``member``, ``nonmember``, ``global_enum``, ``show_flag_values``
165 .. versionadded:: 3.13 ``EnumDict``
166
167 ---------------
168
169 Data Types
170 ----------
171
172
173 .. class:: EnumType
174
175 *EnumType* is the :term:`metaclass` for *enum* enumerations. It is possible
176 to subclass *EnumType* -- see :ref:`Subclassing EnumType <enumtype-examples>`
177 for details.
178
179 ``EnumType`` is responsible for setting the correct :meth:`!__repr__`,
180 :meth:`!__str__`, :meth:`!__format__`, and :meth:`!__reduce__` methods on the
181 final *enum*, as well as creating the enum members, properly handling
182 duplicates, providing iteration over the enum class, etc.
183
184 .. versionadded:: 3.11
185
186 Before 3.11 ``EnumType`` was called ``EnumMeta``, which is still available as an alias.
187
188 .. method:: EnumType.__call__(cls, value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
189
190 This method is called in two different ways:
191
192 * to look up an existing member:
193
194 :cls: The enum class being called.
195 :value: The value to lookup.
196
197 * to use the ``cls`` enum to create a new enum (only if the existing enum
198 does not have any members):
199
200 :cls: The enum class being called.
201 :value: The name of the new Enum to create.
202 :names: The names/values of the members for the new Enum.
203 :module: The name of the module the new Enum is created in.
204 :qualname: The actual location in the module where this Enum can be found.
205 :type: A mix-in type for the new Enum.
206 :start: The first integer value for the Enum (used by :class:`auto`).
207 :boundary: How to handle out-of-range values from bit operations (:class:`Flag` only).
208
209 .. method:: EnumType.__contains__(cls, member)
210
211 Returns ``True`` if member belongs to the ``cls``::
212
213 >>> some_var = Color.RED
214 >>> some_var in Color
215 True
216 >>> Color.RED.value in Color
217 True
218
219 .. versionchanged:: 3.12
220
221 Before Python 3.12, a ``TypeError`` is raised if a
222 non-Enum-member is used in a containment check.
223
224 .. method:: EnumType.__dir__(cls)
225
226 Returns ``['__class__', '__doc__', '__members__', '__module__']`` and the
227 names of the members in *cls*::
228
229 >>> dir(Color)
230 ['BLUE', 'GREEN', 'RED', '__class__', '__contains__', '__doc__', '__getitem__', '__init_subclass__', '__iter__', '__len__', '__members__', '__module__', '__name__', '__qualname__']
231
232 .. method:: EnumType.__getitem__(cls, name)
233
234 Returns the Enum member in *cls* matching *name*, or raises a :exc:`KeyError`::
235
236 >>> Color['BLUE']
237 <Color.BLUE: 3>
238
239 .. method:: EnumType.__iter__(cls)
240
241 Returns each member in *cls* in definition order::
242
243 >>> list(Color)
244 [<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]
245
246 .. method:: EnumType.__len__(cls)
247
248 Returns the number of member in *cls*::
249
250 >>> len(Color)
251 3
252
253 .. attribute:: EnumType.__members__
254
255 Returns a mapping of every enum name to its member, including aliases
256
257 .. method:: EnumType.__reversed__(cls)
258
259 Returns each member in *cls* in reverse definition order::
260
261 >>> list(reversed(Color))
262 [<Color.BLUE: 3>, <Color.GREEN: 2>, <Color.RED: 1>]
263
264
265 .. class:: Enum
266
267 *Enum* is the base class for all *enum* enumerations.
268
269 .. attribute:: Enum.name
270
271 The name used to define the ``Enum`` member::
272
273 >>> Color.BLUE.name
274 'BLUE'
275
276 .. attribute:: Enum.value
277
278 The value given to the ``Enum`` member::
279
280 >>> Color.RED.value
281 1
282
283 Value of the member, can be set in :meth:`~Enum.__new__`.
284
285 .. note:: Enum member values
286
287 Member values can be anything: :class:`int`, :class:`str`, etc. If
288 the exact value is unimportant you may use :class:`auto` instances and an
289 appropriate value will be chosen for you. See :class:`auto` for the
290 details.
291
292 While mutable/unhashable values, such as :class:`dict`, :class:`list` or
293 a mutable :class:`~dataclasses.dataclass`, can be used, they will have a
294 quadratic performance impact during creation relative to the
295 total number of mutable/unhashable values in the enum.
296
297 .. attribute:: Enum._name_
298
299 Name of the member.
300
301 .. attribute:: Enum._value_
302
303 Value of the member, can be set in :meth:`~Enum.__new__`.
304
305 .. attribute:: Enum._order_
306
307 No longer used, kept for backward compatibility.
308 (class attribute, removed during class creation).
309
310 .. attribute:: Enum._ignore_
311
312 ``_ignore_`` is only used during creation and is removed from the
313 enumeration once creation is complete.
314
315 ``_ignore_`` is a list of names that will not become members, and whose
316 names will also be removed from the completed enumeration. See
317 :ref:`TimePeriod <enum-time-period>` for an example.
318
319 .. method:: Enum.__dir__(self)
320
321 Returns ``['__class__', '__doc__', '__module__', 'name', 'value']`` and
322 any public methods defined on *self.__class__*::
323
324 >>> from enum import Enum
325 >>> from datetime import date
326 >>> class Weekday(Enum):
327 ... MONDAY = 1
328 ... TUESDAY = 2
329 ... WEDNESDAY = 3
330 ... THURSDAY = 4
331 ... FRIDAY = 5
332 ... SATURDAY = 6
333 ... SUNDAY = 7
334 ... @classmethod
335 ... def today(cls):
336 ... print('today is %s' % cls(date.today().isoweekday()).name)
337 ...
338 >>> dir(Weekday.SATURDAY)
339 ['__class__', '__doc__', '__eq__', '__hash__', '__module__', 'name', 'today', 'value']
340
341 .. method:: Enum._generate_next_value_(name, start, count, last_values)
342
343 :name: The name of the member being defined (e.g. 'RED').
344 :start: The start value for the Enum; the default is 1.
345 :count: The number of members currently defined, not including this one.
346 :last_values: A list of the previous values.
347
348 A *staticmethod* that is used to determine the next value returned by
349 :class:`auto`::
350
351 >>> from enum import auto, Enum
352 >>> class PowersOfThree(Enum):
353 ... @staticmethod
354 ... def _generate_next_value_(name, start, count, last_values):
355 ... return 3 ** (count + 1)
356 ... FIRST = auto()
357 ... SECOND = auto()
358 ...
359 >>> PowersOfThree.SECOND.value
360 9
361
362 .. method:: Enum.__init__(self, *args, **kwds)
363
364 By default, does nothing. If multiple values are given in the member
365 assignment, those values become separate arguments to ``__init__``; e.g.
366
367 >>> from enum import Enum
368 >>> class Weekday(Enum):
369 ... MONDAY = 1, 'Mon'
370
371 ``Weekday.__init__()`` would be called as ``Weekday.__init__(self, 1, 'Mon')``
372
373 .. method:: Enum.__init_subclass__(cls, **kwds)
374
375 A *classmethod* that is used to further configure subsequent subclasses.
376 By default, does nothing.
377
378 .. method:: Enum._missing_(cls, value)
379
380 A *classmethod* for looking up values not found in *cls*. By default it
381 does nothing, but can be overridden to implement custom search behavior::
382
383 >>> from enum import auto, StrEnum
384 >>> class Build(StrEnum):
385 ... DEBUG = auto()
386 ... OPTIMIZED = auto()
387 ... @classmethod
388 ... def _missing_(cls, value):
389 ... value = value.lower()
390 ... for member in cls:
391 ... if member.value == value:
392 ... return member
393 ... return None
394 ...
395 >>> Build.DEBUG.value
396 'debug'
397 >>> Build('deBUG')
398 <Build.DEBUG: 'debug'>
399
400 .. method:: Enum.__new__(cls, *args, **kwds)
401
402 By default, doesn't exist. If specified, either in the enum class
403 definition or in a mixin class (such as ``int``), all values given
404 in the member assignment will be passed; e.g.
405
406 >>> from enum import Enum
407 >>> class MyIntEnum(int, Enum):
408 ... TWENTYSIX = '1a', 16
409
410 results in the call ``int('1a', 16)`` and a value of ``26`` for the member.
411
412 .. note::
413
414 When writing a custom ``__new__``, do not use ``super().__new__`` --
415 call the appropriate ``__new__`` instead.
416
417 .. method:: Enum.__repr__(self)
418
419 Returns the string used for *repr()* calls. By default, returns the
420 *Enum* name, member name, and value, but can be overridden::
421
422 >>> from enum import auto, Enum
423 >>> class OtherStyle(Enum):
424 ... ALTERNATE = auto()
425 ... OTHER = auto()
426 ... SOMETHING_ELSE = auto()
427 ... def __repr__(self):
428 ... cls_name = self.__class__.__name__
429 ... return f'{cls_name}.{self.name}'
430 ...
431 >>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"{OtherStyle.ALTERNATE}"
432 (OtherStyle.ALTERNATE, 'OtherStyle.ALTERNATE', 'OtherStyle.ALTERNATE')
433
434 .. method:: Enum.__str__(self)
435
436 Returns the string used for *str()* calls. By default, returns the
437 *Enum* name and member name, but can be overridden::
438
439 >>> from enum import auto, Enum
440 >>> class OtherStyle(Enum):
441 ... ALTERNATE = auto()
442 ... OTHER = auto()
443 ... SOMETHING_ELSE = auto()
444 ... def __str__(self):
445 ... return f'{self.name}'
446 ...
447 >>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"{OtherStyle.ALTERNATE}"
448 (<OtherStyle.ALTERNATE: 1>, 'ALTERNATE', 'ALTERNATE')
449
450 .. method:: Enum.__format__(self)
451
452 Returns the string used for *format()* and *f-string* calls. By default,
453 returns :meth:`__str__` return value, but can be overridden::
454
455 >>> from enum import auto, Enum
456 >>> class OtherStyle(Enum):
457 ... ALTERNATE = auto()
458 ... OTHER = auto()
459 ... SOMETHING_ELSE = auto()
460 ... def __format__(self, spec):
461 ... return f'{self.name}'
462 ...
463 >>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"{OtherStyle.ALTERNATE}"
464 (<OtherStyle.ALTERNATE: 1>, 'OtherStyle.ALTERNATE', 'ALTERNATE')
465
466 .. note::
467
468 Using :class:`auto` with :class:`Enum` results in integers of increasing value,
469 starting with ``1``.
470
471 .. versionchanged:: 3.12 Added :ref:`enum-dataclass-support`
472
473 .. method:: Enum._add_alias_
474
475 Adds a new name as an alias to an existing member::
476
477 >>> Color.RED._add_alias_("ERROR")
478 >>> Color.ERROR
479 <Color.RED: 1>
480
481 Raises a :exc:`NameError` if the name is already assigned to a different member.
482
483 .. versionadded:: 3.13
484
485 .. method:: Enum._add_value_alias_
486
487 Adds a new value as an alias to an existing member::
488
489 >>> Color.RED._add_value_alias_(42)
490 >>> Color(42)
491 <Color.RED: 1>
492
493 Raises a :exc:`ValueError` if the value is already linked with a different member.
494
495 .. versionadded:: 3.13
496
497
498 .. class:: IntEnum
499
500 *IntEnum* is the same as :class:`Enum`, but its members are also integers and can be
501 used anywhere that an integer can be used. If any integer operation is performed
502 with an *IntEnum* member, the resulting value loses its enumeration status.
503
504 >>> from enum import IntEnum
505 >>> class Number(IntEnum):
506 ... ONE = 1
507 ... TWO = 2
508 ... THREE = 3
509 ...
510 >>> Number.THREE
511 <Number.THREE: 3>
512 >>> Number.ONE + Number.TWO
513 3
514 >>> Number.THREE + 5
515 8
516 >>> Number.THREE == 3
517 True
518
519 .. note::
520
521 Using :class:`auto` with :class:`IntEnum` results in integers of increasing
522 value, starting with ``1``.
523
524 .. versionchanged:: 3.11 :meth:`~object.__str__` is now :meth:`!int.__str__` to
525 better support the *replacement of existing constants* use-case.
526 :meth:`~object.__format__` was already :meth:`!int.__format__` for that same reason.
527
528
529 .. class:: StrEnum
530
531 *StrEnum* is the same as :class:`Enum`, but its members are also strings and
532 can be used in most of the same places that a string can be used. The result
533 of any string operation performed on or with a *StrEnum* member is not part
534 of the enumeration.
535
536 >>> from enum import StrEnum, auto
537 >>> class Color(StrEnum):
538 ... RED = 'r'
539 ... GREEN = 'g'
540 ... BLUE = 'b'
541 ... UNKNOWN = auto()
542 ...
543 >>> Color.RED
544 <Color.RED: 'r'>
545 >>> Color.UNKNOWN
546 <Color.UNKNOWN: 'unknown'>
547 >>> str(Color.UNKNOWN)
548 'unknown'
549
550 .. note::
551
552 There are places in the stdlib that check for an exact :class:`str`
553 instead of a :class:`str` subclass (i.e. ``type(unknown) == str``
554 instead of ``isinstance(unknown, str)``), and in those locations you
555 will need to use ``str(MyStrEnum.MY_MEMBER)``.
556
557 .. note::
558
559 Using :class:`auto` with :class:`StrEnum` results in the lower-cased member
560 name as the value.
561
562 .. note::
563
564 :meth:`~object.__str__` is :meth:`!str.__str__` to better support the
565 *replacement of existing constants* use-case. :meth:`~object.__format__` is likewise
566 :meth:`!str.__format__` for that same reason.
567
568 .. versionadded:: 3.11
569
570 .. class:: Flag
571
572 ``Flag`` is the same as :class:`Enum`, but its members support the bitwise
573 operators ``&`` (*AND*), ``|`` (*OR*), ``^`` (*XOR*), and ``~`` (*INVERT*);
574 the results of those operations are (aliases of) members of the enumeration.
575
576 .. method:: __contains__(self, value)
577
578 Returns *True* if value is in self::
579
580 >>> from enum import Flag, auto
581 >>> class Color(Flag):
582 ... RED = auto()
583 ... GREEN = auto()
584 ... BLUE = auto()
585 ...
586 >>> purple = Color.RED | Color.BLUE
587 >>> white = Color.RED | Color.GREEN | Color.BLUE
588 >>> Color.GREEN in purple
589 False
590 >>> Color.GREEN in white
591 True
592 >>> purple in white
593 True
594 >>> white in purple
595 False
596
597 .. method:: __iter__(self):
598
599 Returns all contained non-alias members::
600
601 >>> list(Color.RED)
602 [<Color.RED: 1>]
603 >>> list(purple)
604 [<Color.RED: 1>, <Color.BLUE: 4>]
605
606 .. versionadded:: 3.11
607
608 .. method:: __len__(self):
609
610 Returns number of members in flag::
611
612 >>> len(Color.GREEN)
613 1
614 >>> len(white)
615 3
616
617 .. versionadded:: 3.11
618
619 .. method:: __bool__(self):
620
621 Returns *True* if any members in flag, *False* otherwise::
622
623 >>> bool(Color.GREEN)
624 True
625 >>> bool(white)
626 True
627 >>> black = Color(0)
628 >>> bool(black)
629 False
630
631 .. method:: __or__(self, other)
632
633 Returns current flag binary or'ed with other::
634
635 >>> Color.RED | Color.GREEN
636 <Color.RED|GREEN: 3>
637
638 .. method:: __and__(self, other)
639
640 Returns current flag binary and'ed with other::
641
642 >>> purple & white
643 <Color.RED|BLUE: 5>
644 >>> purple & Color.GREEN
645 <Color: 0>
646
647 .. method:: __xor__(self, other)
648
649 Returns current flag binary xor'ed with other::
650
651 >>> purple ^ white
652 <Color.GREEN: 2>
653 >>> purple ^ Color.GREEN
654 <Color.RED|GREEN|BLUE: 7>
655
656 .. method:: __invert__(self):
657
658 Returns all the flags in *type(self)* that are not in *self*::
659
660 >>> ~white
661 <Color: 0>
662 >>> ~purple
663 <Color.GREEN: 2>
664 >>> ~Color.RED
665 <Color.GREEN|BLUE: 6>
666
667 .. method:: _numeric_repr_
668
669 Function used to format any remaining unnamed numeric values. Default is
670 the value's repr; common choices are :func:`hex` and :func:`oct`.
671
672 .. note::
673
674 Using :class:`auto` with :class:`Flag` results in integers that are powers
675 of two, starting with ``1``.
676
677 .. versionchanged:: 3.11 The *repr()* of zero-valued flags has changed. It
678 is now::
679
680 >>> Color(0) # doctest: +SKIP
681 <Color: 0>
682
683 .. class:: IntFlag
684
685 ``IntFlag`` is the same as :class:`Flag`, but its members are also integers and can be
686 used anywhere that an integer can be used.
687
688 >>> from enum import IntFlag, auto
689 >>> class Color(IntFlag):
690 ... RED = auto()
691 ... GREEN = auto()
692 ... BLUE = auto()
693 ...
694 >>> Color.RED & 2
695 <Color: 0>
696 >>> Color.RED | 2
697 <Color.RED|GREEN: 3>
698
699 If any integer operation is performed with an *IntFlag* member, the result is
700 not an *IntFlag*::
701
702 >>> Color.RED + 2
703 3
704
705 If a :class:`Flag` operation is performed with an *IntFlag* member and:
706
707 * the result is a valid *IntFlag*: an *IntFlag* is returned
708 * the result is not a valid *IntFlag*: the result depends on the :class:`FlagBoundary` setting
709
710 The :func:`repr` of unnamed zero-valued flags has changed. It is now:
711
712 >>> Color(0)
713 <Color: 0>
714
715 .. note::
716
717 Using :class:`auto` with :class:`IntFlag` results in integers that are powers
718 of two, starting with ``1``.
719
720 .. versionchanged:: 3.11
721
722 :meth:`~object.__str__` is now :meth:`!int.__str__` to better support the
723 *replacement of existing constants* use-case. :meth:`~object.__format__` was
724 already :meth:`!int.__format__` for that same reason.
725
726 Inversion of an :class:`!IntFlag` now returns a positive value that is the
727 union of all flags not in the given flag, rather than a negative value.
728 This matches the existing :class:`Flag` behavior.
729
730 .. class:: ReprEnum
731
732 :class:`!ReprEnum` uses the :meth:`repr() <Enum.__repr__>` of :class:`Enum`,
733 but the :class:`str() <str>` of the mixed-in data type:
734
735 * :meth:`!int.__str__` for :class:`IntEnum` and :class:`IntFlag`
736 * :meth:`!str.__str__` for :class:`StrEnum`
737
738 Inherit from :class:`!ReprEnum` to keep the :class:`str() <str>` / :func:`format`
739 of the mixed-in data type instead of using the
740 :class:`Enum`-default :meth:`str() <Enum.__str__>`.
741
742
743 .. versionadded:: 3.11
744
745 .. class:: EnumCheck
746
747 *EnumCheck* contains the options used by the :func:`verify` decorator to ensure
748 various constraints; failed constraints result in a :exc:`ValueError`.
749
750 .. attribute:: UNIQUE
751
752 Ensure that each value has only one name::
753
754 >>> from enum import Enum, verify, UNIQUE
755 >>> @verify(UNIQUE)
756 ... class Color(Enum):
757 ... RED = 1
758 ... GREEN = 2
759 ... BLUE = 3
760 ... CRIMSON = 1
761 Traceback (most recent call last):
762 ...
763 ValueError: aliases found in <enum 'Color'>: CRIMSON -> RED
764
765
766 .. attribute:: CONTINUOUS
767
768 Ensure that there are no missing values between the lowest-valued member
769 and the highest-valued member::
770
771 >>> from enum import Enum, verify, CONTINUOUS
772 >>> @verify(CONTINUOUS)
773 ... class Color(Enum):
774 ... RED = 1
775 ... GREEN = 2
776 ... BLUE = 5
777 Traceback (most recent call last):
778 ...
779 ValueError: invalid enum 'Color': missing values 3, 4
780
781 .. attribute:: NAMED_FLAGS
782
783 Ensure that any flag groups/masks contain only named flags -- useful when
784 values are specified instead of being generated by :func:`auto`::
785
786 >>> from enum import Flag, verify, NAMED_FLAGS
787 >>> @verify(NAMED_FLAGS)
788 ... class Color(Flag):
789 ... RED = 1
790 ... GREEN = 2
791 ... BLUE = 4
792 ... WHITE = 15
793 ... NEON = 31
794 Traceback (most recent call last):
795 ...
796 ValueError: invalid Flag 'Color': aliases WHITE and NEON are missing combined values of 0x18 [use enum.show_flag_values(value) for details]
797
798 .. note::
799
800 CONTINUOUS and NAMED_FLAGS are designed to work with integer-valued members.
801
802 .. versionadded:: 3.11
803
804 .. class:: FlagBoundary
805
806 ``FlagBoundary`` controls how out-of-range values are handled in :class:`Flag` and its
807 subclasses.
808
809 .. attribute:: STRICT
810
811 Out-of-range values cause a :exc:`ValueError` to be raised. This is the
812 default for :class:`Flag`::
813
814 >>> from enum import Flag, STRICT, auto
815 >>> class StrictFlag(Flag, boundary=STRICT):
816 ... RED = auto()
817 ... GREEN = auto()
818 ... BLUE = auto()
819 ...
820 >>> StrictFlag(2**2 + 2**4)
821 Traceback (most recent call last):
822 ...
823 ValueError: <flag 'StrictFlag'> invalid value 20
824 given 0b0 10100
825 allowed 0b0 00111
826
827 .. attribute:: CONFORM
828
829 Out-of-range values have invalid values removed, leaving a valid :class:`Flag`
830 value::
831
832 >>> from enum import Flag, CONFORM, auto
833 >>> class ConformFlag(Flag, boundary=CONFORM):
834 ... RED = auto()
835 ... GREEN = auto()
836 ... BLUE = auto()
837 ...
838 >>> ConformFlag(2**2 + 2**4)
839 <ConformFlag.BLUE: 4>
840
841 .. attribute:: EJECT
842
843 Out-of-range values lose their :class:`Flag` membership and revert to :class:`int`.
844
845 >>> from enum import Flag, EJECT, auto
846 >>> class EjectFlag(Flag, boundary=EJECT):
847 ... RED = auto()
848 ... GREEN = auto()
849 ... BLUE = auto()
850 ...
851 >>> EjectFlag(2**2 + 2**4)
852 20
853
854 .. attribute:: KEEP
855
856 Out-of-range values are kept, and the :class:`Flag` membership is kept.
857 This is the default for :class:`IntFlag`::
858
859 >>> from enum import Flag, KEEP, auto
860 >>> class KeepFlag(Flag, boundary=KEEP):
861 ... RED = auto()
862 ... GREEN = auto()
863 ... BLUE = auto()
864 ...
865 >>> KeepFlag(2**2 + 2**4)
866 <KeepFlag.BLUE|16: 20>
867
868 .. versionadded:: 3.11
869
870 .. class:: EnumDict
871
872 *EnumDict* is a subclass of :class:`dict` that is used as the namespace
873 for defining enum classes (see :ref:`prepare`).
874 It is exposed to allow subclasses of :class:`EnumType` with advanced
875 behavior like having multiple values per member.
876 It should be called with the name of the enum class being created, otherwise
877 private names and internal classes will not be handled correctly.
878
879 Note that only the :class:`~collections.abc.MutableMapping` interface
880 (:meth:`~object.__setitem__` and :meth:`~dict.update`) is overridden.
881 It may be possible to bypass the checks using other :class:`!dict`
882 operations like :meth:`|= <object.__ior__>`.
883
884 .. attribute:: EnumDict.member_names
885
886 A list of member names.
887
888 .. versionadded:: 3.13
889
890 ---------------
891
892 Supported ``__dunder__`` names
893 """"""""""""""""""""""""""""""
894
895 :attr:`~EnumType.__members__` is a read-only ordered mapping of ``member_name``:``member``
896 items. It is only available on the class.
897
898 :meth:`~Enum.__new__`, if specified, must create and return the enum members;
899 it is also a very good idea to set the member's :attr:`!_value_` appropriately.
900 Once all the members are created it is no longer used.
901
902
903 Supported ``_sunder_`` names
904 """"""""""""""""""""""""""""
905
906 - :attr:`~Enum._name_` -- name of the member
907 - :attr:`~Enum._value_` -- value of the member; can be set in ``__new__``
908 - :meth:`~Enum._missing_` -- a lookup function used when a value is not found;
909 may be overridden
910 - :attr:`~Enum._ignore_` -- a list of names, either as a :class:`list` or a
911 :class:`str`, that will not be transformed into members, and will be removed
912 from the final class
913 - :attr:`~Enum._order_` -- no longer used, kept for backward
914 compatibility (class attribute, removed during class creation)
915 - :meth:`~Enum._generate_next_value_` -- used to get an appropriate value for
916 an enum member; may be overridden
917
918 .. note::
919
920 For standard :class:`Enum` classes the next value chosen is the highest
921 value seen incremented by one.
922
923 For :class:`Flag` classes the next value chosen will be the next highest
924 power-of-two.
925
926 - :meth:`~Enum._add_alias_` -- adds a new name as an alias to an existing
927 member.
928 - :meth:`~Enum._add_value_alias_` -- adds a new value as an alias to an
929 existing member.
930
931 - While ``_sunder_`` names are generally reserved for the further development
932 of the :class:`Enum` class and can not be used, some are explicitly allowed:
933
934 - ``_repr_*`` (e.g. ``_repr_html_``), as used in `IPython's rich display`_
935
936 .. versionadded:: 3.6 ``_missing_``, ``_order_``, ``_generate_next_value_``
937 .. versionadded:: 3.7 ``_ignore_``
938 .. versionadded:: 3.13 ``_add_alias_``, ``_add_value_alias_``, ``_repr_*``
939 .. _`IPython's rich display`: https://ipython.readthedocs.io/en/stable/config/integrating.html#rich-display
940
941 ---------------
942
943 Utilities and Decorators
944 ------------------------
945
946 .. class:: auto
947
948 *auto* can be used in place of a value. If used, the *Enum* machinery will
949 call an :class:`Enum`'s :meth:`~Enum._generate_next_value_` to get an appropriate value.
950 For :class:`Enum` and :class:`IntEnum` that appropriate value will be the last value plus
951 one; for :class:`Flag` and :class:`IntFlag` it will be the first power-of-two greater
952 than the highest value; for :class:`StrEnum` it will be the lower-cased version of
953 the member's name. Care must be taken if mixing *auto()* with manually
954 specified values.
955
956 *auto* instances are only resolved when at the top level of an assignment, either by
957 itself or as part of a tuple:
958
959 * ``FIRST = auto()`` will work (auto() is replaced with ``1``);
960 * ``SECOND = auto(), -2`` will work (auto is replaced with ``2``, so ``2, -2`` is
961 used to create the ``SECOND`` enum member;
962 * ``THREE = [auto(), -3]`` will *not* work (``[<auto instance>, -3]`` is used to
963 create the ``THREE`` enum member)
964
965 .. versionchanged:: 3.11.1
966
967 In prior versions, ``auto()`` had to be the only thing
968 on the assignment line to work properly.
969
970 ``_generate_next_value_`` can be overridden to customize the values used by
971 *auto*.
972
973 .. note:: in 3.13 the default ``_generate_next_value_`` will always return
974 the highest member value incremented by 1, and will fail if any
975 member is an incompatible type.
976
977 .. decorator:: property
978
979 A decorator similar to the built-in *property*, but specifically for
980 enumerations. It allows member attributes to have the same names as members
981 themselves.
982
983 .. note:: the *property* and the member must be defined in separate classes;
984 for example, the *value* and *name* attributes are defined in the
985 *Enum* class, and *Enum* subclasses can define members with the
986 names ``value`` and ``name``.
987
988 .. versionadded:: 3.11
989
990 .. decorator:: unique
991
992 A :keyword:`class` decorator specifically for enumerations. It searches an
993 enumeration's :attr:`~EnumType.__members__`, gathering any aliases it finds; if any are
994 found :exc:`ValueError` is raised with the details::
995
996 >>> from enum import Enum, unique
997 >>> @unique
998 ... class Mistake(Enum):
999 ... ONE = 1
1000 ... TWO = 2
1001 ... THREE = 3
1002 ... FOUR = 3
1003 ...
1004 Traceback (most recent call last):
1005 ...
1006 ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
1007
1008 .. decorator:: verify
1009
1010 A :keyword:`class` decorator specifically for enumerations. Members from
1011 :class:`EnumCheck` are used to specify which constraints should be checked
1012 on the decorated enumeration.
1013
1014 .. versionadded:: 3.11
1015
1016 .. decorator:: member
1017
1018 A decorator for use in enums: its target will become a member.
1019
1020 .. versionadded:: 3.11
1021
1022 .. decorator:: nonmember
1023
1024 A decorator for use in enums: its target will not become a member.
1025
1026 .. versionadded:: 3.11
1027
1028 .. decorator:: global_enum
1029
1030 A decorator to change the :class:`str() <str>` and :func:`repr` of an enum
1031 to show its members as belonging to the module instead of its class.
1032 Should only be used when the enum members are exported
1033 to the module global namespace (see :class:`re.RegexFlag` for an example).
1034
1035 .. versionadded:: 3.11
1036
1037 .. function:: show_flag_values(value)
1038
1039 Return a list of all power-of-two integers contained in a flag *value*.
1040
1041 .. versionadded:: 3.11
1042
1043 .. function:: bin(num, max_bits=None)
1044
1045 Like built-in :func:`bin`, except negative values are represented in
1046 two's complement, and the leading bit always indicates sign
1047 (``0`` implies positive, ``1`` implies negative).
1048
1049 >>> import enum
1050 >>> enum.bin(10)
1051 '0b0 1010'
1052 >>> enum.bin(~10) # ~10 is -11
1053 '0b1 0101'
1054
1055 .. versionadded:: 3.10
1056
1057 ---------------
1058
1059 Notes
1060 -----
1061
1062 :class:`IntEnum`, :class:`StrEnum`, and :class:`IntFlag`
1063
1064 These three enum types are designed to be drop-in replacements for existing
1065 integer- and string-based values; as such, they have extra limitations:
1066
1067 - ``__str__`` uses the value and not the name of the enum member
1068
1069 - ``__format__``, because it uses ``__str__``, will also use the value of
1070 the enum member instead of its name
1071
1072 If you do not need/want those limitations, you can either create your own
1073 base class by mixing in the ``int`` or ``str`` type yourself::
1074
1075 >>> from enum import Enum
1076 >>> class MyIntEnum(int, Enum):
1077 ... pass
1078
1079 or you can reassign the appropriate :meth:`str`, etc., in your enum::
1080
1081 >>> from enum import Enum, IntEnum
1082 >>> class MyIntEnum(IntEnum):
1083 ... __str__ = Enum.__str__