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 27An 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 35Enumerations are created either by using :keyword:`class` syntax, or by 36using 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', 'GREEN', 'BLUE']) 48 49Even though we can use :keyword:`class` syntax to create Enums, Enums 50are 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 64Module 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:`auto` 114 115 Instances are replaced with an appropriate value for Enum members. 116 :class:`StrEnum` defaults to the lower-cased version of the member name, 117 while other Enums default to 1 and increase from there. 118 119 :func:`~enum.property` 120 121 Allows :class:`Enum` members to have attributes without conflicting with 122 member names. 123 124 :func:`unique` 125 126 Enum class decorator that ensures only one name is bound to any one value. 127 128 :func:`verify` 129 130 Enum class decorator that checks user-selectable constraints on an 131 enumeration. 132 133 :func:`member` 134 135 Make ``obj`` a member. Can be used as a decorator. 136 137 :func:`nonmember` 138 139 Do not make ``obj`` a member. Can be used as a decorator. 140 141 :func:`global_enum` 142 143 Modify the :class:`str() <str>` and :func:`repr` of an enum 144 to show its members as belonging to the module instead of its class, 145 and export the enum members to the global namespace. 146 147 :func:`show_flag_values` 148 149 Return a list of all power-of-two integers contained in a flag. 150 151 152.. versionadded:: 3.6 ``Flag``, ``IntFlag``, ``auto`` 153.. versionadded:: 3.11 ``StrEnum``, ``EnumCheck``, ``ReprEnum``, ``FlagBoundary``, ``property``, ``member``, ``nonmember``, ``global_enum``, ``show_flag_values`` 154 155--------------- 156 157Data Types 158---------- 159 160 161.. class:: EnumType 162 163 *EnumType* is the :term:`metaclass` for *enum* enumerations. It is possible 164 to subclass *EnumType* -- see :ref:`Subclassing EnumType <enumtype-examples>` 165 for details. 166 167 *EnumType* is responsible for setting the correct :meth:`!__repr__`, 168 :meth:`!__str__`, :meth:`!__format__`, and :meth:`!__reduce__` methods on the 169 final *enum*, as well as creating the enum members, properly handling 170 duplicates, providing iteration over the enum class, etc. 171 172 .. method:: EnumType.__call__(cls, value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None) 173 174 This method is called in two different ways: 175 176 * to look up an existing member: 177 178 :cls: The enum class being called. 179 :value: The value to lookup. 180 181 * to use the ``cls`` enum to create a new enum (only if the existing enum 182 does not have any members): 183 184 :cls: The enum class being called. 185 :value: The name of the new Enum to create. 186 :names: The names/values of the members for the new Enum. 187 :module: The name of the module the new Enum is created in. 188 :qualname: The actual location in the module where this Enum can be found. 189 :type: A mix-in type for the new Enum. 190 :start: The first integer value for the Enum (used by :class:`auto`). 191 :boundary: How to handle out-of-range values from bit operations (:class:`Flag` only). 192 193 .. method:: EnumType.__contains__(cls, member) 194 195 Returns ``True`` if member belongs to the ``cls``:: 196 197 >>> some_var = Color.RED 198 >>> some_var in Color 199 True 200 201 .. note:: 202 203 In Python 3.12 it will be possible to check for member values and not 204 just members; until then, a ``TypeError`` will be raised if a 205 non-Enum-member is used in a containment check. 206 207 .. method:: EnumType.__dir__(cls) 208 209 Returns ``['__class__', '__doc__', '__members__', '__module__']`` and the 210 names of the members in *cls*:: 211 212 >>> dir(Color) 213 ['BLUE', 'GREEN', 'RED', '__class__', '__contains__', '__doc__', '__getitem__', '__init_subclass__', '__iter__', '__len__', '__members__', '__module__', '__name__', '__qualname__'] 214 215 .. method:: EnumType.__getattr__(cls, name) 216 217 Returns the Enum member in *cls* matching *name*, or raises an :exc:`AttributeError`:: 218 219 >>> Color.GREEN 220 <Color.GREEN: 2> 221 222 .. method:: EnumType.__getitem__(cls, name) 223 224 Returns the Enum member in *cls* matching *name*, or raises a :exc:`KeyError`:: 225 226 >>> Color['BLUE'] 227 <Color.BLUE: 3> 228 229 .. method:: EnumType.__iter__(cls) 230 231 Returns each member in *cls* in definition order:: 232 233 >>> list(Color) 234 [<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>] 235 236 .. method:: EnumType.__len__(cls) 237 238 Returns the number of member in *cls*:: 239 240 >>> len(Color) 241 3 242 243 .. method:: EnumType.__reversed__(cls) 244 245 Returns each member in *cls* in reverse definition order:: 246 247 >>> list(reversed(Color)) 248 [<Color.BLUE: 3>, <Color.GREEN: 2>, <Color.RED: 1>] 249 250 251.. class:: Enum 252 253 *Enum* is the base class for all *enum* enumerations. 254 255 .. attribute:: Enum.name 256 257 The name used to define the ``Enum`` member:: 258 259 >>> Color.BLUE.name 260 'BLUE' 261 262 .. attribute:: Enum.value 263 264 The value given to the ``Enum`` member:: 265 266 >>> Color.RED.value 267 1 268 269 .. note:: Enum member values 270 271 Member values can be anything: :class:`int`, :class:`str`, etc. If 272 the exact value is unimportant you may use :class:`auto` instances and an 273 appropriate value will be chosen for you. See :class:`auto` for the 274 details. 275 276 .. attribute:: Enum._ignore_ 277 278 ``_ignore_`` is only used during creation and is removed from the 279 enumeration once creation is complete. 280 281 ``_ignore_`` is a list of names that will not become members, and whose 282 names will also be removed from the completed enumeration. See 283 :ref:`TimePeriod <enum-time-period>` for an example. 284 285 .. method:: Enum.__dir__(self) 286 287 Returns ``['__class__', '__doc__', '__module__', 'name', 'value']`` and 288 any public methods defined on *self.__class__*:: 289 290 >>> from datetime import date 291 >>> class Weekday(Enum): 292 ... MONDAY = 1 293 ... TUESDAY = 2 294 ... WEDNESDAY = 3 295 ... THURSDAY = 4 296 ... FRIDAY = 5 297 ... SATURDAY = 6 298 ... SUNDAY = 7 299 ... @classmethod 300 ... def today(cls): 301 ... print('today is %s' % cls(date.today().isoweekday()).name) 302 >>> dir(Weekday.SATURDAY) 303 ['__class__', '__doc__', '__eq__', '__hash__', '__module__', 'name', 'today', 'value'] 304 305 .. method:: Enum._generate_next_value_(name, start, count, last_values) 306 307 :name: The name of the member being defined (e.g. 'RED'). 308 :start: The start value for the Enum; the default is 1. 309 :count: The number of members currently defined, not including this one. 310 :last_values: A list of the previous values. 311 312 A *staticmethod* that is used to determine the next value returned by 313 :class:`auto`:: 314 315 >>> from enum import auto 316 >>> class PowersOfThree(Enum): 317 ... @staticmethod 318 ... def _generate_next_value_(name, start, count, last_values): 319 ... return 3 ** (count + 1) 320 ... FIRST = auto() 321 ... SECOND = auto() 322 >>> PowersOfThree.SECOND.value 323 9 324 325 .. method:: Enum.__init_subclass__(cls, **kwds) 326 327 A *classmethod* that is used to further configure subsequent subclasses. 328 By default, does nothing. 329 330 .. method:: Enum._missing_(cls, value) 331 332 A *classmethod* for looking up values not found in *cls*. By default it 333 does nothing, but can be overridden to implement custom search behavior:: 334 335 >>> from enum import StrEnum 336 >>> class Build(StrEnum): 337 ... DEBUG = auto() 338 ... OPTIMIZED = auto() 339 ... @classmethod 340 ... def _missing_(cls, value): 341 ... value = value.lower() 342 ... for member in cls: 343 ... if member.value == value: 344 ... return member 345 ... return None 346 >>> Build.DEBUG.value 347 'debug' 348 >>> Build('deBUG') 349 <Build.DEBUG: 'debug'> 350 351 .. method:: Enum.__repr__(self) 352 353 Returns the string used for *repr()* calls. By default, returns the 354 *Enum* name, member name, and value, but can be overridden:: 355 356 >>> class OtherStyle(Enum): 357 ... ALTERNATE = auto() 358 ... OTHER = auto() 359 ... SOMETHING_ELSE = auto() 360 ... def __repr__(self): 361 ... cls_name = self.__class__.__name__ 362 ... return f'{cls_name}.{self.name}' 363 >>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"{OtherStyle.ALTERNATE}" 364 (OtherStyle.ALTERNATE, 'OtherStyle.ALTERNATE', 'OtherStyle.ALTERNATE') 365 366 .. method:: Enum.__str__(self) 367 368 Returns the string used for *str()* calls. By default, returns the 369 *Enum* name and member name, but can be overridden:: 370 371 >>> class OtherStyle(Enum): 372 ... ALTERNATE = auto() 373 ... OTHER = auto() 374 ... SOMETHING_ELSE = auto() 375 ... def __str__(self): 376 ... return f'{self.name}' 377 >>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"{OtherStyle.ALTERNATE}" 378 (<OtherStyle.ALTERNATE: 1>, 'ALTERNATE', 'ALTERNATE') 379 380 .. method:: Enum.__format__(self) 381 382 Returns the string used for *format()* and *f-string* calls. By default, 383 returns :meth:`__str__` return value, but can be overridden:: 384 385 >>> class OtherStyle(Enum): 386 ... ALTERNATE = auto() 387 ... OTHER = auto() 388 ... SOMETHING_ELSE = auto() 389 ... def __format__(self, spec): 390 ... return f'{self.name}' 391 >>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"{OtherStyle.ALTERNATE}" 392 (<OtherStyle.ALTERNATE: 1>, 'OtherStyle.ALTERNATE', 'ALTERNATE') 393 394 .. note:: 395 396 Using :class:`auto` with :class:`Enum` results in integers of increasing value, 397 starting with ``1``. 398 399 400.. class:: IntEnum 401 402 *IntEnum* is the same as *Enum*, but its members are also integers and can be 403 used anywhere that an integer can be used. If any integer operation is performed 404 with an *IntEnum* member, the resulting value loses its enumeration status. 405 406 >>> from enum import IntEnum 407 >>> class Number(IntEnum): 408 ... ONE = 1 409 ... TWO = 2 410 ... THREE = 3 411 ... 412 >>> Number.THREE 413 <Number.THREE: 3> 414 >>> Number.ONE + Number.TWO 415 3 416 >>> Number.THREE + 5 417 8 418 >>> Number.THREE == 3 419 True 420 421 .. note:: 422 423 Using :class:`auto` with :class:`IntEnum` results in integers of increasing 424 value, starting with ``1``. 425 426 .. versionchanged:: 3.11 :meth:`~object.__str__` is now :meth:`!int.__str__` to 427 better support the *replacement of existing constants* use-case. 428 :meth:`~object.__format__` was already :meth:`!int.__format__` for that same reason. 429 430 431.. class:: StrEnum 432 433 *StrEnum* is the same as *Enum*, but its members are also strings and can be used 434 in most of the same places that a string can be used. The result of any string 435 operation performed on or with a *StrEnum* member is not part of the enumeration. 436 437 .. note:: 438 439 There are places in the stdlib that check for an exact :class:`str` 440 instead of a :class:`str` subclass (i.e. ``type(unknown) == str`` 441 instead of ``isinstance(unknown, str)``), and in those locations you 442 will need to use ``str(StrEnum.member)``. 443 444 .. note:: 445 446 Using :class:`auto` with :class:`StrEnum` results in the lower-cased member 447 name as the value. 448 449 .. note:: 450 451 :meth:`~object.__str__` is :meth:`!str.__str__` to better support the 452 *replacement of existing constants* use-case. :meth:`~object.__format__` is likewise 453 :meth:`!str.__format__` for that same reason. 454 455 .. versionadded:: 3.11 456 457.. class:: Flag 458 459 *Flag* members support the bitwise operators ``&`` (*AND*), ``|`` (*OR*), 460 ``^`` (*XOR*), and ``~`` (*INVERT*); the results of those operators are members 461 of the enumeration. 462 463 .. method:: __contains__(self, value) 464 465 Returns *True* if value is in self:: 466 467 >>> from enum import Flag, auto 468 >>> class Color(Flag): 469 ... RED = auto() 470 ... GREEN = auto() 471 ... BLUE = auto() 472 >>> purple = Color.RED | Color.BLUE 473 >>> white = Color.RED | Color.GREEN | Color.BLUE 474 >>> Color.GREEN in purple 475 False 476 >>> Color.GREEN in white 477 True 478 >>> purple in white 479 True 480 >>> white in purple 481 False 482 483 .. method:: __iter__(self): 484 485 Returns all contained non-alias members:: 486 487 >>> list(Color.RED) 488 [<Color.RED: 1>] 489 >>> list(purple) 490 [<Color.RED: 1>, <Color.BLUE: 4>] 491 492 .. versionchanged:: 3.11 493 494 Aliases are no longer returned during iteration. 495 496 .. method:: __len__(self): 497 498 Returns number of members in flag:: 499 500 >>> len(Color.GREEN) 501 1 502 >>> len(white) 503 3 504 505 .. method:: __bool__(self): 506 507 Returns *True* if any members in flag, *False* otherwise:: 508 509 >>> bool(Color.GREEN) 510 True 511 >>> bool(white) 512 True 513 >>> black = Color(0) 514 >>> bool(black) 515 False 516 517 .. method:: __or__(self, other) 518 519 Returns current flag binary or'ed with other:: 520 521 >>> Color.RED | Color.GREEN 522 <Color.RED|GREEN: 3> 523 524 .. method:: __and__(self, other) 525 526 Returns current flag binary and'ed with other:: 527 528 >>> purple & white 529 <Color.RED|BLUE: 5> 530 >>> purple & Color.GREEN 531 <Color: 0> 532 533 .. method:: __xor__(self, other) 534 535 Returns current flag binary xor'ed with other:: 536 537 >>> purple ^ white 538 <Color.GREEN: 2> 539 >>> purple ^ Color.GREEN 540 <Color.RED|GREEN|BLUE: 7> 541 542 .. method:: __invert__(self): 543 544 Returns all the flags in *type(self)* that are not in self:: 545 546 >>> ~white 547 <Color: 0> 548 >>> ~purple 549 <Color.GREEN: 2> 550 >>> ~Color.RED 551 <Color.GREEN|BLUE: 6> 552 553 .. method:: _numeric_repr_ 554 555 Function used to format any remaining unnamed numeric values. Default is 556 the value's repr; common choices are :func:`hex` and :func:`oct`. 557 558 .. note:: 559 560 Using :class:`auto` with :class:`Flag` results in integers that are powers 561 of two, starting with ``1``. 562 563 .. versionchanged:: 3.11 The *repr()* of zero-valued flags has changed. It 564 is now:: 565 566 >>> Color(0) # doctest: +SKIP 567 <Color: 0> 568 569.. class:: IntFlag 570 571 *IntFlag* is the same as *Flag*, but its members are also integers and can be 572 used anywhere that an integer can be used. 573 574 >>> from enum import IntFlag, auto 575 >>> class Color(IntFlag): 576 ... RED = auto() 577 ... GREEN = auto() 578 ... BLUE = auto() 579 >>> Color.RED & 2 580 <Color: 0> 581 >>> Color.RED | 2 582 <Color.RED|GREEN: 3> 583 584 If any integer operation is performed with an *IntFlag* member, the result is 585 not an *IntFlag*:: 586 587 >>> Color.RED + 2 588 3 589 590 If a *Flag* operation is performed with an *IntFlag* member and: 591 592 * the result is a valid *IntFlag*: an *IntFlag* is returned 593 * the result is not a valid *IntFlag*: the result depends on the *FlagBoundary* setting 594 595 The *repr()* of unnamed zero-valued flags has changed. It is now: 596 597 >>> Color(0) 598 <Color: 0> 599 600 .. note:: 601 602 Using :class:`auto` with :class:`IntFlag` results in integers that are powers 603 of two, starting with ``1``. 604 605 .. versionchanged:: 3.11 606 607 :meth:`~object.__str__` is now :meth:`!int.__str__` to better support the 608 *replacement of existing constants* use-case. :meth:`~object.__format__` was 609 already :meth:`!int.__format__` for that same reason. 610 611 Inversion of an :class:`!IntFlag` now returns a positive value that is the 612 union of all flags not in the given flag, rather than a negative value. 613 This matches the existing :class:`Flag` behavior. 614 615.. class:: ReprEnum 616 617 :class:`!ReprEnum` uses the :meth:`repr() <Enum.__repr__>` of :class:`Enum`, 618 but the :class:`str() <str>` of the mixed-in data type: 619 620 * :meth:`!int.__str__` for :class:`IntEnum` and :class:`IntFlag` 621 * :meth:`!str.__str__` for :class:`StrEnum` 622 623 Inherit from :class:`!ReprEnum` to keep the :class:`str() <str>` / :func:`format` 624 of the mixed-in data type instead of using the 625 :class:`Enum`-default :meth:`str() <Enum.__str__>`. 626 627 628 .. versionadded:: 3.11 629 630.. class:: EnumCheck 631 632 *EnumCheck* contains the options used by the :func:`verify` decorator to ensure 633 various constraints; failed constraints result in a :exc:`ValueError`. 634 635 .. attribute:: UNIQUE 636 637 Ensure that each value has only one name:: 638 639 >>> from enum import Enum, verify, UNIQUE 640 >>> @verify(UNIQUE) 641 ... class Color(Enum): 642 ... RED = 1 643 ... GREEN = 2 644 ... BLUE = 3 645 ... CRIMSON = 1 646 Traceback (most recent call last): 647 ... 648 ValueError: aliases found in <enum 'Color'>: CRIMSON -> RED 649 650 651 .. attribute:: CONTINUOUS 652 653 Ensure that there are no missing values between the lowest-valued member 654 and the highest-valued member:: 655 656 >>> from enum import Enum, verify, CONTINUOUS 657 >>> @verify(CONTINUOUS) 658 ... class Color(Enum): 659 ... RED = 1 660 ... GREEN = 2 661 ... BLUE = 5 662 Traceback (most recent call last): 663 ... 664 ValueError: invalid enum 'Color': missing values 3, 4 665 666 .. attribute:: NAMED_FLAGS 667 668 Ensure that any flag groups/masks contain only named flags -- useful when 669 values are specified instead of being generated by :func:`auto`:: 670 671 >>> from enum import Flag, verify, NAMED_FLAGS 672 >>> @verify(NAMED_FLAGS) 673 ... class Color(Flag): 674 ... RED = 1 675 ... GREEN = 2 676 ... BLUE = 4 677 ... WHITE = 15 678 ... NEON = 31 679 Traceback (most recent call last): 680 ... 681 ValueError: invalid Flag 'Color': aliases WHITE and NEON are missing combined values of 0x18 [use enum.show_flag_values(value) for details] 682 683 .. note:: 684 685 CONTINUOUS and NAMED_FLAGS are designed to work with integer-valued members. 686 687 .. versionadded:: 3.11 688 689.. class:: FlagBoundary 690 691 *FlagBoundary* controls how out-of-range values are handled in *Flag* and its 692 subclasses. 693 694 .. attribute:: STRICT 695 696 Out-of-range values cause a :exc:`ValueError` to be raised. This is the 697 default for :class:`Flag`:: 698 699 >>> from enum import Flag, STRICT, auto 700 >>> class StrictFlag(Flag, boundary=STRICT): 701 ... RED = auto() 702 ... GREEN = auto() 703 ... BLUE = auto() 704 >>> StrictFlag(2**2 + 2**4) 705 Traceback (most recent call last): 706 ... 707 ValueError: <flag 'StrictFlag'> invalid value 20 708 given 0b0 10100 709 allowed 0b0 00111 710 711 .. attribute:: CONFORM 712 713 Out-of-range values have invalid values removed, leaving a valid *Flag* 714 value:: 715 716 >>> from enum import Flag, CONFORM, auto 717 >>> class ConformFlag(Flag, boundary=CONFORM): 718 ... RED = auto() 719 ... GREEN = auto() 720 ... BLUE = auto() 721 >>> ConformFlag(2**2 + 2**4) 722 <ConformFlag.BLUE: 4> 723 724 .. attribute:: EJECT 725 726 Out-of-range values lose their *Flag* membership and revert to :class:`int`. 727 728 >>> from enum import Flag, EJECT, auto 729 >>> class EjectFlag(Flag, boundary=EJECT): 730 ... RED = auto() 731 ... GREEN = auto() 732 ... BLUE = auto() 733 >>> EjectFlag(2**2 + 2**4) 734 20 735 736 .. attribute:: KEEP 737 738 Out-of-range values are kept, and the *Flag* membership is kept. 739 This is the default for :class:`IntFlag`:: 740 741 >>> from enum import Flag, KEEP, auto 742 >>> class KeepFlag(Flag, boundary=KEEP): 743 ... RED = auto() 744 ... GREEN = auto() 745 ... BLUE = auto() 746 >>> KeepFlag(2**2 + 2**4) 747 <KeepFlag.BLUE|16: 20> 748 749.. versionadded:: 3.11 750 751--------------- 752 753Supported ``__dunder__`` names 754"""""""""""""""""""""""""""""" 755 756:attr:`~EnumType.__members__` is a read-only ordered mapping of ``member_name``:``member`` 757items. It is only available on the class. 758 759:meth:`~object.__new__`, if specified, must create and return the enum members; it is 760also a very good idea to set the member's :attr:`!_value_` appropriately. Once 761all the members are created it is no longer used. 762 763 764Supported ``_sunder_`` names 765"""""""""""""""""""""""""""" 766 767- ``_name_`` -- name of the member 768- ``_value_`` -- value of the member; can be set / modified in ``__new__`` 769 770- ``_missing_`` -- a lookup function used when a value is not found; may be 771 overridden 772- ``_ignore_`` -- a list of names, either as a :class:`list` or a :class:`str`, 773 that will not be transformed into members, and will be removed from the final 774 class 775- ``_order_`` -- used in Python 2/3 code to ensure member order is consistent 776 (class attribute, removed during class creation) 777- ``_generate_next_value_`` -- used to get an appropriate value for an enum 778 member; may be overridden 779 780 .. note:: 781 782 For standard :class:`Enum` classes the next value chosen is the last value seen 783 incremented by one. 784 785 For :class:`Flag` classes the next value chosen will be the next highest 786 power-of-two, regardless of the last value seen. 787 788.. versionadded:: 3.6 ``_missing_``, ``_order_``, ``_generate_next_value_`` 789.. versionadded:: 3.7 ``_ignore_`` 790 791--------------- 792 793Utilities and Decorators 794------------------------ 795 796.. class:: auto 797 798 *auto* can be used in place of a value. If used, the *Enum* machinery will 799 call an *Enum*'s :meth:`~Enum._generate_next_value_` to get an appropriate value. 800 For *Enum* and *IntEnum* that appropriate value will be the last value plus 801 one; for *Flag* and *IntFlag* it will be the first power-of-two greater 802 than the highest value; for *StrEnum* it will be the lower-cased version of 803 the member's name. Care must be taken if mixing *auto()* with manually 804 specified values. 805 806 *auto* instances are only resolved when at the top level of an assignment: 807 808 * ``FIRST = auto()`` will work (auto() is replaced with ``1``); 809 * ``SECOND = auto(), -2`` will work (auto is replaced with ``2``, so ``2, -2`` is 810 used to create the ``SECOND`` enum member; 811 * ``THREE = [auto(), -3]`` will *not* work (``<auto instance>, -3`` is used to 812 create the ``THREE`` enum member) 813 814 .. versionchanged:: 3.11.1 815 816 In prior versions, ``auto()`` had to be the only thing 817 on the assignment line to work properly. 818 819 ``_generate_next_value_`` can be overridden to customize the values used by 820 *auto*. 821 822 .. note:: in 3.13 the default ``_generate_next_value_`` will always return 823 the highest member value incremented by 1, and will fail if any 824 member is an incompatible type. 825 826.. decorator:: property 827 828 A decorator similar to the built-in *property*, but specifically for 829 enumerations. It allows member attributes to have the same names as members 830 themselves. 831 832 .. note:: the *property* and the member must be defined in separate classes; 833 for example, the *value* and *name* attributes are defined in the 834 *Enum* class, and *Enum* subclasses can define members with the 835 names ``value`` and ``name``. 836 837 .. versionadded:: 3.11 838 839.. decorator:: unique 840 841 A :keyword:`class` decorator specifically for enumerations. It searches an 842 enumeration's :attr:`~EnumType.__members__`, gathering any aliases it finds; if any are 843 found :exc:`ValueError` is raised with the details:: 844 845 >>> from enum import Enum, unique 846 >>> @unique 847 ... class Mistake(Enum): 848 ... ONE = 1 849 ... TWO = 2 850 ... THREE = 3 851 ... FOUR = 3 852 ... 853 Traceback (most recent call last): 854 ... 855 ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE 856 857.. decorator:: verify 858 859 A :keyword:`class` decorator specifically for enumerations. Members from 860 :class:`EnumCheck` are used to specify which constraints should be checked 861 on the decorated enumeration. 862 863 .. versionadded:: 3.11 864 865.. decorator:: member 866 867 A decorator for use in enums: its target will become a member. 868 869 .. versionadded:: 3.11 870 871.. decorator:: nonmember 872 873 A decorator for use in enums: its target will not become a member. 874 875 .. versionadded:: 3.11 876 877.. decorator:: global_enum 878 879 A decorator to change the :class:`str() <str>` and :func:`repr` of an enum 880 to show its members as belonging to the module instead of its class. 881 Should only be used when the enum members are exported 882 to the module global namespace (see :class:`re.RegexFlag` for an example). 883 884 885 .. versionadded:: 3.11 886 887.. function:: show_flag_values(value) 888 889 Return a list of all power-of-two integers contained in a flag *value*. 890 891 .. versionadded:: 3.11 892 893--------------- 894 895Notes 896----- 897 898:class:`IntEnum`, :class:`StrEnum`, and :class:`IntFlag` 899 900 These three enum types are designed to be drop-in replacements for existing 901 integer- and string-based values; as such, they have extra limitations: 902 903 - ``__str__`` uses the value and not the name of the enum member 904 905 - ``__format__``, because it uses ``__str__``, will also use the value of 906 the enum member instead of its name 907 908 If you do not need/want those limitations, you can either create your own 909 base class by mixing in the ``int`` or ``str`` type yourself:: 910 911 >>> from enum import Enum 912 >>> class MyIntEnum(int, Enum): 913 ... pass 914 915 or you can reassign the appropriate :meth:`str`, etc., in your enum:: 916 917 >>> from enum import Enum, IntEnum 918 >>> class MyIntEnum(IntEnum): 919 ... __str__ = Enum.__str__ 920