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 members 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 The :attr:`~Enum._order_` attribute can be provided to help keep Python 2 / Python 3 code in sync.
311 It will be checked against the actual order of the enumeration and raise an error if the two do not match::
312
313 >>> class Color(Enum):
314 ... _order_ = 'RED GREEN BLUE'
315 ... RED = 1
316 ... BLUE = 3
317 ... GREEN = 2
318 ...
319 Traceback (most recent call last):
320 ...
321 TypeError: member order does not match _order_:
322 ['RED', 'BLUE', 'GREEN']
323 ['RED', 'GREEN', 'BLUE']
324
325 .. note::
326
327 In Python 2 code the :attr:`~Enum._order_` attribute is necessary as definition
328 order is lost before it can be recorded.
329
330 .. versionadded:: 3.6
331
332 .. attribute:: Enum._ignore_
333
334 ``_ignore_`` is only used during creation and is removed from the
335 enumeration once creation is complete.
336
337 ``_ignore_`` is a list of names that will not become members, and whose
338 names will also be removed from the completed enumeration. See
339 :ref:`TimePeriod <enum-time-period>` for an example.
340
341 .. versionadded:: 3.7
342
343 .. method:: Enum.__dir__(self)
344
345 Returns ``['__class__', '__doc__', '__module__', 'name', 'value']`` and
346 any public methods defined on *self.__class__*::
347
348 >>> from enum import Enum
349 >>> import datetime as dt
350 >>> class Weekday(Enum):
351 ... MONDAY = 1
352 ... TUESDAY = 2
353 ... WEDNESDAY = 3
354 ... THURSDAY = 4
355 ... FRIDAY = 5
356 ... SATURDAY = 6
357 ... SUNDAY = 7
358 ... @classmethod
359 ... def today(cls):
360 ... print(f'today is {cls(dt.date.today().isoweekday()).name}')
361 ...
362 >>> dir(Weekday.SATURDAY)
363 ['__class__', '__doc__', '__eq__', '__hash__', '__module__', 'name', 'today', 'value']
364
365 .. method:: Enum._generate_next_value_(name, start, count, last_values)
366
367 :name: The name of the member being defined (e.g. 'RED').
368 :start: The start value for the Enum; the default is 1.
369 :count: The number of members currently defined, not including this one.
370 :last_values: A list of the previous values.
371
372 A *staticmethod* that is used to determine the next value returned by
373 :class:`auto`.
374
375 .. note::
376 For standard :class:`Enum` classes the next value chosen is the highest
377 value seen incremented by one.
378
379 For :class:`Flag` classes the next value chosen will be the next highest
380 power-of-two.
381
382 This method may be overridden, e.g.::
383
384 >>> from enum import auto, Enum
385 >>> class PowersOfThree(Enum):
386 ... @staticmethod
387 ... def _generate_next_value_(name, start, count, last_values):
388 ... return 3 ** (count + 1)
389 ... FIRST = auto()
390 ... SECOND = auto()
391 ...
392 >>> PowersOfThree.SECOND.value
393 9
394
395 .. versionadded:: 3.6
396 .. versionchanged:: 3.13
397 Prior versions would use the last seen value instead of the highest value.
398
399 .. method:: Enum.__init__(self, *args, **kwds)
400
401 By default, does nothing. If multiple values are given in the member
402 assignment, those values become separate arguments to ``__init__``; e.g.
403
404 >>> from enum import Enum
405 >>> class Weekday(Enum):
406 ... MONDAY = 1, 'Mon'
407
408 ``Weekday.__init__()`` would be called as ``Weekday.__init__(self, 1, 'Mon')``
409
410 .. method:: Enum.__init_subclass__(cls, **kwds)
411
412 A *classmethod* that is used to further configure subsequent subclasses.
413 By default, does nothing.
414
415 .. method:: Enum._missing_(cls, value)
416
417 A *classmethod* for looking up values not found in *cls*. By default it
418 does nothing, but can be overridden to implement custom search behavior::
419
420 >>> from enum import auto, StrEnum
421 >>> class Build(StrEnum):
422 ... DEBUG = auto()
423 ... OPTIMIZED = auto()
424 ... @classmethod
425 ... def _missing_(cls, value):
426 ... value = value.lower()
427 ... for member in cls:
428 ... if member.value == value:
429 ... return member
430 ... return None
431 ...
432 >>> Build.DEBUG.value
433 'debug'
434 >>> Build('deBUG')
435 <Build.DEBUG: 'debug'>
436
437 .. versionadded:: 3.6
438
439 .. method:: Enum.__new__(cls, *args, **kwds)
440
441 By default, doesn't exist. If specified, either in the enum class
442 definition or in a mixin class (such as ``int``), all values given
443 in the member assignment will be passed; e.g.
444
445 >>> from enum import Enum
446 >>> class MyIntEnum(int, Enum):
447 ... TWENTYSIX = '1a', 16
448
449 results in the call ``int('1a', 16)`` and a value of ``26`` for the member.
450
451 .. note::
452
453 When writing a custom ``__new__``, do not use ``super().__new__`` --
454 call the appropriate ``__new__`` instead.
455
456 .. method:: Enum.__repr__(self)
457
458 Returns the string used for *repr()* calls. By default, returns the
459 *Enum* name, member name, and value, but can be overridden::
460
461 >>> from enum import auto, Enum
462 >>> class OtherStyle(Enum):
463 ... ALTERNATE = auto()
464 ... OTHER = auto()
465 ... SOMETHING_ELSE = auto()
466 ... def __repr__(self):
467 ... cls_name = self.__class__.__name__
468 ... return f'{cls_name}.{self.name}'
469 ...
470 >>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"{OtherStyle.ALTERNATE}"
471 (OtherStyle.ALTERNATE, 'OtherStyle.ALTERNATE', 'OtherStyle.ALTERNATE')
472
473 .. method:: Enum.__str__(self)
474
475 Returns the string used for *str()* calls. By default, returns the
476 *Enum* name and member name, but can be overridden::
477
478 >>> from enum import auto, Enum
479 >>> class OtherStyle(Enum):
480 ... ALTERNATE = auto()
481 ... OTHER = auto()
482 ... SOMETHING_ELSE = auto()
483 ... def __str__(self):
484 ... return f'{self.name}'
485 ...
486 >>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"{OtherStyle.ALTERNATE}"
487 (<OtherStyle.ALTERNATE: 1>, 'ALTERNATE', 'ALTERNATE')
488
489 .. method:: Enum.__format__(self)
490
491 Returns the string used for *format()* and *f-string* calls. By default,
492 returns :meth:`__str__` return value, but can be overridden::
493
494 >>> from enum import auto, Enum
495 >>> class OtherStyle(Enum):
496 ... ALTERNATE = auto()
497 ... OTHER = auto()
498 ... SOMETHING_ELSE = auto()
499 ... def __format__(self, spec):
500 ... return f'{self.name}'
501 ...
502 >>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"{OtherStyle.ALTERNATE}"
503 (<OtherStyle.ALTERNATE: 1>, 'OtherStyle.ALTERNATE', 'ALTERNATE')
504
505 .. note::
506
507 Using :class:`auto` with :class:`Enum` results in integers of increasing value,
508 starting with ``1``.
509
510 .. versionchanged:: 3.12 Added :ref:`enum-dataclass-support`
511
512 .. method:: Enum._add_alias_
513
514 Adds a new name as an alias to an existing member::
515
516 >>> Color.RED._add_alias_("ERROR")
517 >>> Color.ERROR
518 <Color.RED: 1>
519
520 Raises a :exc:`NameError` if the name is already assigned to a different member.
521
522 .. versionadded:: 3.13
523
524 .. method:: Enum._add_value_alias_
525
526 Adds a new value as an alias to an existing member::
527
528 >>> Color.RED._add_value_alias_(42)
529 >>> Color(42)
530 <Color.RED: 1>
531
532 | Raises a :exc:`ValueError` if the value is already linked with a different member.
533 | See :ref:`multi-value-enum` for an example.
534
535 .. versionadded:: 3.13
536
537
538 .. class:: IntEnum
539
540 *IntEnum* is the same as :class:`Enum`, but its members are also integers and can be
541 used anywhere that an integer can be used. If any integer operation is performed
542 with an *IntEnum* member, the resulting value loses its enumeration status.
543
544 >>> from enum import IntEnum
545 >>> class Number(IntEnum):
546 ... ONE = 1
547 ... TWO = 2
548 ... THREE = 3
549 ...
550 >>> Number.THREE
551 <Number.THREE: 3>
552 >>> Number.ONE + Number.TWO
553 3
554 >>> Number.THREE + 5
555 8
556 >>> Number.THREE == 3
557 True
558
559 .. note::
560
561 Using :class:`auto` with :class:`IntEnum` results in integers of increasing
562 value, starting with ``1``.
563
564 .. versionchanged:: 3.11 :meth:`~object.__str__` is now :meth:`!int.__str__` to
565 better support the *replacement of existing constants* use-case.
566 :meth:`~object.__format__` was already :meth:`!int.__format__` for that same reason.
567
568
569 .. class:: StrEnum
570
571 *StrEnum* is the same as :class:`Enum`, but its members are also strings and
572 can be used in most of the same places that a string can be used. The result
573 of any string operation performed on or with a *StrEnum* member is not part
574 of the enumeration.
575
576 >>> from enum import StrEnum, auto
577 >>> class Color(StrEnum):
578 ... RED = 'r'
579 ... GREEN = 'g'
580 ... BLUE = 'b'
581 ... UNKNOWN = auto()
582 ...
583 >>> Color.RED
584 <Color.RED: 'r'>
585 >>> Color.UNKNOWN
586 <Color.UNKNOWN: 'unknown'>
587 >>> str(Color.UNKNOWN)
588 'unknown'
589
590 .. note::
591
592 There are places in the stdlib that check for an exact :class:`str`
593 instead of a :class:`str` subclass (i.e. ``type(unknown) == str``
594 instead of ``isinstance(unknown, str)``), and in those locations you
595 will need to use ``str(MyStrEnum.MY_MEMBER)``.
596
597 .. note::
598
599 Using :class:`auto` with :class:`StrEnum` results in the lower-cased member
600 name as the value.
601
602 .. note::
603
604 :meth:`~object.__str__` is :meth:`!str.__str__` to better support the
605 *replacement of existing constants* use-case. :meth:`~object.__format__` is likewise
606 :meth:`!str.__format__` for that same reason.
607
608 .. versionadded:: 3.11
609
610 .. class:: Flag
611
612 ``Flag`` is the same as :class:`Enum`, but its members support the bitwise
613 operators ``&`` (*AND*), ``|`` (*OR*), ``^`` (*XOR*), and ``~`` (*INVERT*);
614 the results of those operations are (aliases of) members of the enumeration.
615
616 .. method:: __contains__(self, value)
617
618 Returns *True* if value is in self::
619
620 >>> from enum import Flag, auto
621 >>> class Color(Flag):
622 ... RED = auto()
623 ... GREEN = auto()
624 ... BLUE = auto()
625 ...
626 >>> purple = Color.RED | Color.BLUE
627 >>> white = Color.RED | Color.GREEN | Color.BLUE
628 >>> Color.GREEN in purple
629 False
630 >>> Color.GREEN in white
631 True
632 >>> purple in white
633 True
634 >>> white in purple
635 False
636
637 .. method:: __iter__(self):
638
639 Returns all contained non-alias members::
640
641 >>> list(Color.RED)
642 [<Color.RED: 1>]
643 >>> list(purple)
644 [<Color.RED: 1>, <Color.BLUE: 4>]
645
646 .. versionadded:: 3.11
647
648 .. method:: __len__(self):
649
650 Returns number of members in flag::
651
652 >>> len(Color.GREEN)
653 1
654 >>> len(white)
655 3
656
657 .. versionadded:: 3.11
658
659 .. method:: __bool__(self):
660
661 Returns *True* if any members in flag, *False* otherwise::
662
663 >>> bool(Color.GREEN)
664 True
665 >>> bool(white)
666 True
667 >>> black = Color(0)
668 >>> bool(black)
669 False
670
671 .. method:: __or__(self, other)
672
673 Returns current flag binary or'ed with other::
674
675 >>> Color.RED | Color.GREEN
676 <Color.RED|GREEN: 3>
677
678 .. method:: __and__(self, other)
679
680 Returns current flag binary and'ed with other::
681
682 >>> purple & white
683 <Color.RED|BLUE: 5>
684 >>> purple & Color.GREEN
685 <Color: 0>
686
687 .. method:: __xor__(self, other)
688
689 Returns current flag binary xor'ed with other::
690
691 >>> purple ^ white
692 <Color.GREEN: 2>
693 >>> purple ^ Color.GREEN
694 <Color.RED|GREEN|BLUE: 7>
695
696 .. method:: __invert__(self):
697
698 Returns all the flags in *type(self)* that are not in *self*::
699
700 >>> ~white
701 <Color: 0>
702 >>> ~purple
703 <Color.GREEN: 2>
704 >>> ~Color.RED
705 <Color.GREEN|BLUE: 6>
706
707 .. method:: _numeric_repr_
708
709 Function used to format any remaining unnamed numeric values. Default is
710 the value's repr; common choices are :func:`hex` and :func:`oct`.
711
712 .. note::
713
714 Using :class:`auto` with :class:`Flag` results in integers that are powers
715 of two, starting with ``1``.
716
717 .. versionchanged:: 3.11 The *repr()* of zero-valued flags has changed. It
718 is now:
719
720 >>> Color(0) # doctest: +SKIP
721 <Color: 0>
722
723 .. class:: IntFlag
724
725 ``IntFlag`` is the same as :class:`Flag`, but its members are also integers and can be
726 used anywhere that an integer can be used.
727
728 >>> from enum import IntFlag, auto
729 >>> class Color(IntFlag):
730 ... RED = auto()
731 ... GREEN = auto()
732 ... BLUE = auto()
733 ...
734 >>> Color.RED & 2
735 <Color: 0>
736 >>> Color.RED | 2
737 <Color.RED|GREEN: 3>
738
739 If any integer operation is performed with an *IntFlag* member, the result is
740 not an *IntFlag*::
741
742 >>> Color.RED + 2
743 3
744
745 If a :class:`Flag` operation is performed with an *IntFlag* member and:
746
747 * the result is a valid *IntFlag*: an *IntFlag* is returned
748 * the result is not a valid *IntFlag*: the result depends on the :class:`FlagBoundary` setting
749
750 The :func:`repr` of unnamed zero-valued flags has changed. It is now::
751
752 >>> Color(0)
753 <Color: 0>
754
755 .. note::
756
757 Using :class:`auto` with :class:`IntFlag` results in integers that are powers
758 of two, starting with ``1``.
759
760 .. versionchanged:: 3.11
761
762 :meth:`~object.__str__` is now :meth:`!int.__str__` to better support the
763 *replacement of existing constants* use-case. :meth:`~object.__format__` was
764 already :meth:`!int.__format__` for that same reason.
765
766 Inversion of an :class:`!IntFlag` now returns a positive value that is the
767 union of all flags not in the given flag, rather than a negative value.
768 This matches the existing :class:`Flag` behavior.
769
770 .. class:: ReprEnum
771
772 :class:`!ReprEnum` uses the :meth:`repr() <Enum.__repr__>` of :class:`Enum`,
773 but the :class:`str() <str>` of the mixed-in data type:
774
775 * :meth:`!int.__str__` for :class:`IntEnum` and :class:`IntFlag`
776 * :meth:`!str.__str__` for :class:`StrEnum`
777
778 Inherit from :class:`!ReprEnum` to keep the :class:`str() <str>` / :func:`format`
779 of the mixed-in data type instead of using the
780 :class:`Enum`-default :meth:`str() <Enum.__str__>`.
781
782
783 .. versionadded:: 3.11
784
785 .. class:: EnumCheck
786
787 *EnumCheck* contains the options used by the :func:`verify` decorator to ensure
788 various constraints; failed constraints result in a :exc:`ValueError`.
789
790 .. attribute:: UNIQUE
791
792 Ensure that each value has only one name::
793
794 >>> from enum import Enum, verify, UNIQUE
795 >>> @verify(UNIQUE)
796 ... class Color(Enum):
797 ... RED = 1
798 ... GREEN = 2
799 ... BLUE = 3
800 ... CRIMSON = 1
801 Traceback (most recent call last):
802 ...
803 ValueError: aliases found in <enum 'Color'>: CRIMSON -> RED
804
805
806 .. attribute:: CONTINUOUS
807
808 Ensure that there are no missing values between the lowest-valued member
809 and the highest-valued member::
810
811 >>> from enum import Enum, verify, CONTINUOUS
812 >>> @verify(CONTINUOUS)
813 ... class Color(Enum):
814 ... RED = 1
815 ... GREEN = 2
816 ... BLUE = 5
817 Traceback (most recent call last):
818 ...
819 ValueError: invalid enum 'Color': missing values 3, 4
820
821 .. attribute:: NAMED_FLAGS
822
823 Ensure that any flag groups/masks contain only named flags -- useful when
824 values are specified instead of being generated by :func:`auto`::
825
826 >>> from enum import Flag, verify, NAMED_FLAGS
827 >>> @verify(NAMED_FLAGS)
828 ... class Color(Flag):
829 ... RED = 1
830 ... GREEN = 2
831 ... BLUE = 4
832 ... WHITE = 15
833 ... NEON = 31
834 Traceback (most recent call last):
835 ...
836 ValueError: invalid Flag 'Color': aliases WHITE and NEON are missing combined values of 0x18 [use enum.show_flag_values(value) for details]
837
838 .. note::
839
840 CONTINUOUS and NAMED_FLAGS are designed to work with integer-valued members.
841
842 .. versionadded:: 3.11
843
844 .. class:: FlagBoundary
845
846 ``FlagBoundary`` controls how out-of-range values are handled in :class:`Flag` and its
847 subclasses.
848
849 .. attribute:: STRICT
850
851 Out-of-range values cause a :exc:`ValueError` to be raised. This is the
852 default for :class:`Flag`::
853
854 >>> from enum import Flag, STRICT, auto
855 >>> class StrictFlag(Flag, boundary=STRICT):
856 ... RED = auto()
857 ... GREEN = auto()
858 ... BLUE = auto()
859 ...
860 >>> StrictFlag(2**2 + 2**4)
861 Traceback (most recent call last):
862 ...
863 ValueError: <flag 'StrictFlag'> invalid value 20
864 given 0b0 10100
865 allowed 0b0 00111
866
867 .. attribute:: CONFORM
868
869 Out-of-range values have invalid values removed, leaving a valid :class:`Flag`
870 value::
871
872 >>> from enum import Flag, CONFORM, auto
873 >>> class ConformFlag(Flag, boundary=CONFORM):
874 ... RED = auto()
875 ... GREEN = auto()
876 ... BLUE = auto()
877 ...
878 >>> ConformFlag(2**2 + 2**4)
879 <ConformFlag.BLUE: 4>
880
881 .. attribute:: EJECT
882
883 Out-of-range values lose their :class:`Flag` membership and revert to :class:`int`.
884
885 >>> from enum import Flag, EJECT, auto
886 >>> class EjectFlag(Flag, boundary=EJECT):
887 ... RED = auto()
888 ... GREEN = auto()
889 ... BLUE = auto()
890 ...
891 >>> EjectFlag(2**2 + 2**4)
892 20
893
894 .. attribute:: KEEP
895
896 Out-of-range values are kept, and the :class:`Flag` membership is kept.
897 This is the default for :class:`IntFlag`::
898
899 >>> from enum import Flag, KEEP, auto
900 >>> class KeepFlag(Flag, boundary=KEEP):
901 ... RED = auto()
902 ... GREEN = auto()
903 ... BLUE = auto()
904 ...
905 >>> KeepFlag(2**2 + 2**4)
906 <KeepFlag.BLUE|16: 20>
907
908 .. versionadded:: 3.11
909
910 .. class:: EnumDict
911
912 *EnumDict* is a subclass of :class:`dict` that is used as the namespace
913 for defining enum classes (see :ref:`prepare`).
914 It is exposed to allow subclasses of :class:`EnumType` with advanced
915 behavior like having multiple values per member.
916 It should be called with the name of the enum class being created, otherwise
917 private names and internal classes will not be handled correctly.
918
919 Note that only the :class:`~collections.abc.MutableMapping` interface
920 (:meth:`~object.__setitem__` and :meth:`~dict.update`) is overridden.
921 It may be possible to bypass the checks using other :class:`!dict`
922 operations like :meth:`|= <object.__ior__>`.
923
924 .. attribute:: EnumDict.member_names
925
926 A list of member names.
927
928 .. versionadded:: 3.13
929
930 ---------------
931
932 .. _enum-dunder-sunder:
933
934 Supported ``__dunder__`` names
935 """"""""""""""""""""""""""""""
936
937 :attr:`~EnumType.__members__` is a read-only ordered mapping of ``member_name``:``member``
938 items. It is only available on the class.
939
940 :meth:`~Enum.__new__`, if specified, must create and return the enum members;
941 it is also a very good idea to set the member's :attr:`~Enum._value_` appropriately.
942 Once all the members are created it is no longer used.
943
944
945 Supported ``_sunder_`` names
946 """"""""""""""""""""""""""""
947
948 - :attr:`~Enum._name_` -- name of the member
949 - :attr:`~Enum._value_` -- value of the member; can be set in ``__new__``
950 - :meth:`~Enum._missing_` -- a lookup function used when a value is not found;
951 may be overridden
952 - :attr:`~Enum._ignore_` -- a list of names, either as a :class:`list` or a
953 :class:`str`, that will not be transformed into members, and will be removed
954 from the final class
955 - :attr:`~Enum._order_` -- no longer used, kept for backward
956 compatibility (class attribute, removed during class creation)
957
958 - :meth:`~Enum._generate_next_value_` -- used to get an appropriate value for
959 an enum member; may be overridden
960
961 - :meth:`~Enum._add_alias_` -- adds a new name as an alias to an existing
962 member.
963 - :meth:`~Enum._add_value_alias_` -- adds a new value as an alias to an
964 existing member.
965
966 - While ``_sunder_`` names are generally reserved for the further development
967 of the :class:`Enum` class and can not be used, some are explicitly allowed:
968
969 - ``_repr_*`` (e.g. ``_repr_html_``), as used in `IPython's rich display`_
970
971 .. versionadded:: 3.6 ``_missing_``, ``_order_``, ``_generate_next_value_``
972 .. versionadded:: 3.7 ``_ignore_``
973 .. versionadded:: 3.13 ``_add_alias_``, ``_add_value_alias_``, ``_repr_*``
974 .. _`IPython's rich display`: https://ipython.readthedocs.io/en/stable/config/integrating.html#rich-display
975
976 ---------------
977
978 Utilities and decorators
979 ------------------------
980
981 .. class:: auto
982
983 *auto* can be used in place of a value. If used, the *Enum* machinery will
984 call an :class:`Enum`'s :meth:`~Enum._generate_next_value_` to get an appropriate value.
985 For :class:`Enum` and :class:`IntEnum` that appropriate value will be the last value plus
986 one; for :class:`Flag` and :class:`IntFlag` it will be the first power-of-two greater
987 than the highest value; for :class:`StrEnum` it will be the lower-cased version of
988 the member's name. Care must be taken if mixing *auto()* with manually
989 specified values.
990
991 *auto* instances are only resolved when at the top level of an assignment, either by
992 itself or as part of a tuple:
993
994 * ``FIRST = auto()`` will work (auto() is replaced with ``1``);
995 * ``SECOND = auto(), -2`` will work (auto is replaced with ``2``, so ``2, -2`` is
996 used to create the ``SECOND`` enum member;
997 * ``THREE = [auto(), -3]`` will *not* work (``[<auto instance>, -3]`` is used to
998 create the ``THREE`` enum member)
999
1000 .. versionchanged:: 3.11.1
1001
1002 In prior versions, ``auto()`` had to be the only thing
1003 on the assignment line to work properly.
1004
1005 ``_generate_next_value_`` can be overridden to customize the values used by
1006 *auto*.
1007
1008 .. note:: in 3.13 the default ``_generate_next_value_`` will always return
1009 the highest member value incremented by 1, and will fail if any
1010 member is an incompatible type.
1011
1012 .. decorator:: property
1013
1014 A decorator similar to the built-in *property*, but specifically for
1015 enumerations. It allows member attributes to have the same names as members
1016 themselves.
1017
1018 .. note:: the *property* and the member must be defined in separate classes;
1019 for example, the *value* and *name* attributes are defined in the
1020 *Enum* class, and *Enum* subclasses can define members with the
1021 names ``value`` and ``name``.
1022
1023 .. versionadded:: 3.11
1024
1025 .. decorator:: unique
1026
1027 A :keyword:`class` decorator specifically for enumerations. It searches an
1028 enumeration's :attr:`~EnumType.__members__`, gathering any aliases it finds; if any are
1029 found :exc:`ValueError` is raised with the details::
1030
1031 >>> from enum import Enum, unique
1032 >>> @unique
1033 ... class Mistake(Enum):
1034 ... ONE = 1
1035 ... TWO = 2
1036 ... THREE = 3
1037 ... FOUR = 3
1038 ...
1039 Traceback (most recent call last):
1040 ...
1041 ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
1042
1043 .. decorator:: verify
1044
1045 A :keyword:`class` decorator specifically for enumerations. Members from
1046 :class:`EnumCheck` are used to specify which constraints should be checked
1047 on the decorated enumeration.
1048
1049 .. versionadded:: 3.11
1050
1051 .. decorator:: member
1052
1053 A decorator for use in enums: its target will become a member.
1054
1055 .. versionadded:: 3.11
1056
1057 .. decorator:: nonmember
1058
1059 A decorator for use in enums: its target will not become a member.
1060
1061 .. versionadded:: 3.11
1062
1063 .. decorator:: global_enum
1064
1065 A decorator to change the :class:`str() <str>` and :func:`repr` of an enum
1066 to show its members as belonging to the module instead of its class.
1067 Should only be used when the enum members are exported
1068 to the module global namespace (see :class:`re.RegexFlag` for an example).
1069
1070
1071 .. versionadded:: 3.11
1072
1073 .. function:: show_flag_values(value)
1074
1075 Return a list of all power-of-two integers contained in a flag *value*.
1076
1077 .. versionadded:: 3.11
1078
1079 .. function:: bin(num, max_bits=None)
1080
1081 Like built-in :func:`bin`, except negative values are represented in
1082 two's complement, and the leading bit always indicates sign
1083 (``0`` implies positive, ``1`` implies negative).
1084
1085 >>> import enum
1086 >>> enum.bin(10)
1087 '0b0 1010'
1088 >>> enum.bin(~10) # ~10 is -11
1089 '0b1 0101'
1090
1091 .. versionadded:: 3.11
1092
1093 ---------------
1094
1095 Notes
1096 -----
1097
1098 :class:`IntEnum`, :class:`StrEnum`, and :class:`IntFlag`
1099
1100 These three enum types are designed to be drop-in replacements for existing
1101 integer- and string-based values; as such, they have extra limitations:
1102
1103 - ``__str__`` uses the value and not the name of the enum member
1104
1105 - ``__format__``, because it uses ``__str__``, will also use the value of
1106 the enum member instead of its name
1107
1108 If you do not need/want those limitations, you can either create your own
1109 base class by mixing in the ``int`` or ``str`` type yourself::
1110
1111 >>> from enum import Enum
1112 >>> class MyIntEnum(int, Enum):
1113 ... pass
1114
1115 or you can reassign the appropriate :meth:`str`, etc., in your enum::
1116
1117 >>> from enum import Enum, IntEnum
1118 >>> class MyIntEnum(IntEnum):
1119 ... __str__ = Enum.__str__