1:mod:`enum` --- Support for enumerations 2======================================== 3 4.. module:: enum 5 :synopsis: Implementation of an enumeration class. 6 7.. :moduleauthor:: Ethan Furman <ethan@stoneleaf.us> 8.. :sectionauthor:: Barry Warsaw <barry@python.org>, 9.. :sectionauthor:: Eli Bendersky <eliben@gmail.com>, 10.. :sectionauthor:: Ethan Furman <ethan@stoneleaf.us> 11 12.. versionadded:: 3.4 13 14**Source code:** :source:`Lib/enum.py` 15 16---------------- 17 18An enumeration is a set of symbolic names (members) bound to unique, 19constant values. Within an enumeration, the members can be compared 20by identity, and the enumeration itself can be iterated over. 21 22 23Module Contents 24--------------- 25 26This module defines four enumeration classes that can be used to define unique 27sets of names and values: :class:`Enum`, :class:`IntEnum`, :class:`Flag`, and 28:class:`IntFlag`. It also defines one decorator, :func:`unique`, and one 29helper, :class:`auto`. 30 31.. class:: Enum 32 33 Base class for creating enumerated constants. See section 34 `Functional API`_ for an alternate construction syntax. 35 36.. class:: IntEnum 37 38 Base class for creating enumerated constants that are also 39 subclasses of :class:`int`. 40 41.. class:: IntFlag 42 43 Base class for creating enumerated constants that can be combined using 44 the bitwise operators without losing their :class:`IntFlag` membership. 45 :class:`IntFlag` members are also subclasses of :class:`int`. 46 47.. class:: Flag 48 49 Base class for creating enumerated constants that can be combined using 50 the bitwise operations without losing their :class:`Flag` membership. 51 52.. function:: unique 53 54 Enum class decorator that ensures only one name is bound to any one value. 55 56.. class:: auto 57 58 Instances are replaced with an appropriate value for Enum members. 59 60.. versionadded:: 3.6 ``Flag``, ``IntFlag``, ``auto`` 61 62 63Creating an Enum 64---------------- 65 66Enumerations are created using the :keyword:`class` syntax, which makes them 67easy to read and write. An alternative creation method is described in 68`Functional API`_. To define an enumeration, subclass :class:`Enum` as 69follows:: 70 71 >>> from enum import Enum 72 >>> class Color(Enum): 73 ... RED = 1 74 ... GREEN = 2 75 ... BLUE = 3 76 ... 77 78.. note:: Enum member values 79 80 Member values can be anything: :class:`int`, :class:`str`, etc.. If 81 the exact value is unimportant you may use :class:`auto` instances and an 82 appropriate value will be chosen for you. Care must be taken if you mix 83 :class:`auto` with other values. 84 85.. note:: Nomenclature 86 87 - The class :class:`Color` is an *enumeration* (or *enum*) 88 - The attributes :attr:`Color.RED`, :attr:`Color.GREEN`, etc., are 89 *enumeration members* (or *enum members*) and are functionally constants. 90 - The enum members have *names* and *values* (the name of 91 :attr:`Color.RED` is ``RED``, the value of :attr:`Color.BLUE` is 92 ``3``, etc.) 93 94.. note:: 95 96 Even though we use the :keyword:`class` syntax to create Enums, Enums 97 are not normal Python classes. See `How are Enums different?`_ for 98 more details. 99 100Enumeration members have human readable string representations:: 101 102 >>> print(Color.RED) 103 Color.RED 104 105...while their ``repr`` has more information:: 106 107 >>> print(repr(Color.RED)) 108 <Color.RED: 1> 109 110The *type* of an enumeration member is the enumeration it belongs to:: 111 112 >>> type(Color.RED) 113 <enum 'Color'> 114 >>> isinstance(Color.GREEN, Color) 115 True 116 >>> 117 118Enum members also have a property that contains just their item name:: 119 120 >>> print(Color.RED.name) 121 RED 122 123Enumerations support iteration, in definition order:: 124 125 >>> class Shake(Enum): 126 ... VANILLA = 7 127 ... CHOCOLATE = 4 128 ... COOKIES = 9 129 ... MINT = 3 130 ... 131 >>> for shake in Shake: 132 ... print(shake) 133 ... 134 Shake.VANILLA 135 Shake.CHOCOLATE 136 Shake.COOKIES 137 Shake.MINT 138 139Enumeration members are hashable, so they can be used in dictionaries and sets:: 140 141 >>> apples = {} 142 >>> apples[Color.RED] = 'red delicious' 143 >>> apples[Color.GREEN] = 'granny smith' 144 >>> apples == {Color.RED: 'red delicious', Color.GREEN: 'granny smith'} 145 True 146 147 148Programmatic access to enumeration members and their attributes 149--------------------------------------------------------------- 150 151Sometimes it's useful to access members in enumerations programmatically (i.e. 152situations where ``Color.RED`` won't do because the exact color is not known 153at program-writing time). ``Enum`` allows such access:: 154 155 >>> Color(1) 156 <Color.RED: 1> 157 >>> Color(3) 158 <Color.BLUE: 3> 159 160If you want to access enum members by *name*, use item access:: 161 162 >>> Color['RED'] 163 <Color.RED: 1> 164 >>> Color['GREEN'] 165 <Color.GREEN: 2> 166 167If you have an enum member and need its :attr:`name` or :attr:`value`:: 168 169 >>> member = Color.RED 170 >>> member.name 171 'RED' 172 >>> member.value 173 1 174 175 176Duplicating enum members and values 177----------------------------------- 178 179Having two enum members with the same name is invalid:: 180 181 >>> class Shape(Enum): 182 ... SQUARE = 2 183 ... SQUARE = 3 184 ... 185 Traceback (most recent call last): 186 ... 187 TypeError: Attempted to reuse key: 'SQUARE' 188 189However, two enum members are allowed to have the same value. Given two members 190A and B with the same value (and A defined first), B is an alias to A. By-value 191lookup of the value of A and B will return A. By-name lookup of B will also 192return A:: 193 194 >>> class Shape(Enum): 195 ... SQUARE = 2 196 ... DIAMOND = 1 197 ... CIRCLE = 3 198 ... ALIAS_FOR_SQUARE = 2 199 ... 200 >>> Shape.SQUARE 201 <Shape.SQUARE: 2> 202 >>> Shape.ALIAS_FOR_SQUARE 203 <Shape.SQUARE: 2> 204 >>> Shape(2) 205 <Shape.SQUARE: 2> 206 207.. note:: 208 209 Attempting to create a member with the same name as an already 210 defined attribute (another member, a method, etc.) or attempting to create 211 an attribute with the same name as a member is not allowed. 212 213 214Ensuring unique enumeration values 215---------------------------------- 216 217By default, enumerations allow multiple names as aliases for the same value. 218When this behavior isn't desired, the following decorator can be used to 219ensure each value is used only once in the enumeration: 220 221.. decorator:: unique 222 223A :keyword:`class` decorator specifically for enumerations. It searches an 224enumeration's :attr:`__members__` gathering any aliases it finds; if any are 225found :exc:`ValueError` is raised with the details:: 226 227 >>> from enum import Enum, unique 228 >>> @unique 229 ... class Mistake(Enum): 230 ... ONE = 1 231 ... TWO = 2 232 ... THREE = 3 233 ... FOUR = 3 234 ... 235 Traceback (most recent call last): 236 ... 237 ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE 238 239 240Using automatic values 241---------------------- 242 243If the exact value is unimportant you can use :class:`auto`:: 244 245 >>> from enum import Enum, auto 246 >>> class Color(Enum): 247 ... RED = auto() 248 ... BLUE = auto() 249 ... GREEN = auto() 250 ... 251 >>> list(Color) 252 [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>] 253 254The values are chosen by :func:`_generate_next_value_`, which can be 255overridden:: 256 257 >>> class AutoName(Enum): 258 ... def _generate_next_value_(name, start, count, last_values): 259 ... return name 260 ... 261 >>> class Ordinal(AutoName): 262 ... NORTH = auto() 263 ... SOUTH = auto() 264 ... EAST = auto() 265 ... WEST = auto() 266 ... 267 >>> list(Ordinal) 268 [<Ordinal.NORTH: 'NORTH'>, <Ordinal.SOUTH: 'SOUTH'>, <Ordinal.EAST: 'EAST'>, <Ordinal.WEST: 'WEST'>] 269 270.. note:: 271 272 The goal of the default :meth:`_generate_next_value_` methods is to provide 273 the next :class:`int` in sequence with the last :class:`int` provided, but 274 the way it does this is an implementation detail and may change. 275 276Iteration 277--------- 278 279Iterating over the members of an enum does not provide the aliases:: 280 281 >>> list(Shape) 282 [<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>] 283 284The special attribute ``__members__`` is an ordered dictionary mapping names 285to members. It includes all names defined in the enumeration, including the 286aliases:: 287 288 >>> for name, member in Shape.__members__.items(): 289 ... name, member 290 ... 291 ('SQUARE', <Shape.SQUARE: 2>) 292 ('DIAMOND', <Shape.DIAMOND: 1>) 293 ('CIRCLE', <Shape.CIRCLE: 3>) 294 ('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>) 295 296The ``__members__`` attribute can be used for detailed programmatic access to 297the enumeration members. For example, finding all the aliases:: 298 299 >>> [name for name, member in Shape.__members__.items() if member.name != name] 300 ['ALIAS_FOR_SQUARE'] 301 302 303Comparisons 304----------- 305 306Enumeration members are compared by identity:: 307 308 >>> Color.RED is Color.RED 309 True 310 >>> Color.RED is Color.BLUE 311 False 312 >>> Color.RED is not Color.BLUE 313 True 314 315Ordered comparisons between enumeration values are *not* supported. Enum 316members are not integers (but see `IntEnum`_ below):: 317 318 >>> Color.RED < Color.BLUE 319 Traceback (most recent call last): 320 File "<stdin>", line 1, in <module> 321 TypeError: '<' not supported between instances of 'Color' and 'Color' 322 323Equality comparisons are defined though:: 324 325 >>> Color.BLUE == Color.RED 326 False 327 >>> Color.BLUE != Color.RED 328 True 329 >>> Color.BLUE == Color.BLUE 330 True 331 332Comparisons against non-enumeration values will always compare not equal 333(again, :class:`IntEnum` was explicitly designed to behave differently, see 334below):: 335 336 >>> Color.BLUE == 2 337 False 338 339 340Allowed members and attributes of enumerations 341---------------------------------------------- 342 343The examples above use integers for enumeration values. Using integers is 344short and handy (and provided by default by the `Functional API`_), but not 345strictly enforced. In the vast majority of use-cases, one doesn't care what 346the actual value of an enumeration is. But if the value *is* important, 347enumerations can have arbitrary values. 348 349Enumerations are Python classes, and can have methods and special methods as 350usual. If we have this enumeration:: 351 352 >>> class Mood(Enum): 353 ... FUNKY = 1 354 ... HAPPY = 3 355 ... 356 ... def describe(self): 357 ... # self is the member here 358 ... return self.name, self.value 359 ... 360 ... def __str__(self): 361 ... return 'my custom str! {0}'.format(self.value) 362 ... 363 ... @classmethod 364 ... def favorite_mood(cls): 365 ... # cls here is the enumeration 366 ... return cls.HAPPY 367 ... 368 369Then:: 370 371 >>> Mood.favorite_mood() 372 <Mood.HAPPY: 3> 373 >>> Mood.HAPPY.describe() 374 ('HAPPY', 3) 375 >>> str(Mood.FUNKY) 376 'my custom str! 1' 377 378The rules for what is allowed are as follows: names that start and end with 379a single underscore are reserved by enum and cannot be used; all other 380attributes defined within an enumeration will become members of this 381enumeration, with the exception of special methods (:meth:`__str__`, 382:meth:`__add__`, etc.) and descriptors (methods are also descriptors). 383 384Note: if your enumeration defines :meth:`__new__` and/or :meth:`__init__` then 385whatever value(s) were given to the enum member will be passed into those 386methods. See `Planet`_ for an example. 387 388 389Restricted subclassing of enumerations 390-------------------------------------- 391 392Subclassing an enumeration is allowed only if the enumeration does not define 393any members. So this is forbidden:: 394 395 >>> class MoreColor(Color): 396 ... PINK = 17 397 ... 398 Traceback (most recent call last): 399 ... 400 TypeError: Cannot extend enumerations 401 402But this is allowed:: 403 404 >>> class Foo(Enum): 405 ... def some_behavior(self): 406 ... pass 407 ... 408 >>> class Bar(Foo): 409 ... HAPPY = 1 410 ... SAD = 2 411 ... 412 413Allowing subclassing of enums that define members would lead to a violation of 414some important invariants of types and instances. On the other hand, it makes 415sense to allow sharing some common behavior between a group of enumerations. 416(See `OrderedEnum`_ for an example.) 417 418 419Pickling 420-------- 421 422Enumerations can be pickled and unpickled:: 423 424 >>> from test.test_enum import Fruit 425 >>> from pickle import dumps, loads 426 >>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO)) 427 True 428 429The usual restrictions for pickling apply: picklable enums must be defined in 430the top level of a module, since unpickling requires them to be importable 431from that module. 432 433.. note:: 434 435 With pickle protocol version 4 it is possible to easily pickle enums 436 nested in other classes. 437 438It is possible to modify how Enum members are pickled/unpickled by defining 439:meth:`__reduce_ex__` in the enumeration class. 440 441 442Functional API 443-------------- 444 445The :class:`Enum` class is callable, providing the following functional API:: 446 447 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG') 448 >>> Animal 449 <enum 'Animal'> 450 >>> Animal.ANT 451 <Animal.ANT: 1> 452 >>> Animal.ANT.value 453 1 454 >>> list(Animal) 455 [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>] 456 457The semantics of this API resemble :class:`~collections.namedtuple`. The first 458argument of the call to :class:`Enum` is the name of the enumeration. 459 460The second argument is the *source* of enumeration member names. It can be a 461whitespace-separated string of names, a sequence of names, a sequence of 4622-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to 463values. The last two options enable assigning arbitrary values to 464enumerations; the others auto-assign increasing integers starting with 1 (use 465the ``start`` parameter to specify a different starting value). A 466new class derived from :class:`Enum` is returned. In other words, the above 467assignment to :class:`Animal` is equivalent to:: 468 469 >>> class Animal(Enum): 470 ... ANT = 1 471 ... BEE = 2 472 ... CAT = 3 473 ... DOG = 4 474 ... 475 476The reason for defaulting to ``1`` as the starting number and not ``0`` is 477that ``0`` is ``False`` in a boolean sense, but enum members all evaluate 478to ``True``. 479 480Pickling enums created with the functional API can be tricky as frame stack 481implementation details are used to try and figure out which module the 482enumeration is being created in (e.g. it will fail if you use a utility 483function in separate module, and also may not work on IronPython or Jython). 484The solution is to specify the module name explicitly as follows:: 485 486 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__) 487 488.. warning:: 489 490 If ``module`` is not supplied, and Enum cannot determine what it is, 491 the new Enum members will not be unpicklable; to keep errors closer to 492 the source, pickling will be disabled. 493 494The new pickle protocol 4 also, in some circumstances, relies on 495:attr:`~definition.__qualname__` being set to the location where pickle will be able 496to find the class. For example, if the class was made available in class 497SomeData in the global scope:: 498 499 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal') 500 501The complete signature is:: 502 503 Enum(value='NewEnumName', names=<...>, *, module='...', qualname='...', type=<mixed-in class>, start=1) 504 505:value: What the new Enum class will record as its name. 506 507:names: The Enum members. This can be a whitespace or comma separated string 508 (values will start at 1 unless otherwise specified):: 509 510 'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE' 511 512 or an iterator of names:: 513 514 ['RED', 'GREEN', 'BLUE'] 515 516 or an iterator of (name, value) pairs:: 517 518 [('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)] 519 520 or a mapping:: 521 522 {'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42} 523 524:module: name of module where new Enum class can be found. 525 526:qualname: where in module new Enum class can be found. 527 528:type: type to mix in to new Enum class. 529 530:start: number to start counting at if only names are passed in. 531 532.. versionchanged:: 3.5 533 The *start* parameter was added. 534 535 536Derived Enumerations 537-------------------- 538 539IntEnum 540^^^^^^^ 541 542The first variation of :class:`Enum` that is provided is also a subclass of 543:class:`int`. Members of an :class:`IntEnum` can be compared to integers; 544by extension, integer enumerations of different types can also be compared 545to each other:: 546 547 >>> from enum import IntEnum 548 >>> class Shape(IntEnum): 549 ... CIRCLE = 1 550 ... SQUARE = 2 551 ... 552 >>> class Request(IntEnum): 553 ... POST = 1 554 ... GET = 2 555 ... 556 >>> Shape == 1 557 False 558 >>> Shape.CIRCLE == 1 559 True 560 >>> Shape.CIRCLE == Request.POST 561 True 562 563However, they still can't be compared to standard :class:`Enum` enumerations:: 564 565 >>> class Shape(IntEnum): 566 ... CIRCLE = 1 567 ... SQUARE = 2 568 ... 569 >>> class Color(Enum): 570 ... RED = 1 571 ... GREEN = 2 572 ... 573 >>> Shape.CIRCLE == Color.RED 574 False 575 576:class:`IntEnum` values behave like integers in other ways you'd expect:: 577 578 >>> int(Shape.CIRCLE) 579 1 580 >>> ['a', 'b', 'c'][Shape.CIRCLE] 581 'b' 582 >>> [i for i in range(Shape.SQUARE)] 583 [0, 1] 584 585 586IntFlag 587^^^^^^^ 588 589The next variation of :class:`Enum` provided, :class:`IntFlag`, is also based 590on :class:`int`. The difference being :class:`IntFlag` members can be combined 591using the bitwise operators (&, \|, ^, ~) and the result is still an 592:class:`IntFlag` member. However, as the name implies, :class:`IntFlag` 593members also subclass :class:`int` and can be used wherever an :class:`int` is 594used. Any operation on an :class:`IntFlag` member besides the bit-wise 595operations will lose the :class:`IntFlag` membership. 596 597.. versionadded:: 3.6 598 599Sample :class:`IntFlag` class:: 600 601 >>> from enum import IntFlag 602 >>> class Perm(IntFlag): 603 ... R = 4 604 ... W = 2 605 ... X = 1 606 ... 607 >>> Perm.R | Perm.W 608 <Perm.R|W: 6> 609 >>> Perm.R + Perm.W 610 6 611 >>> RW = Perm.R | Perm.W 612 >>> Perm.R in RW 613 True 614 615It is also possible to name the combinations:: 616 617 >>> class Perm(IntFlag): 618 ... R = 4 619 ... W = 2 620 ... X = 1 621 ... RWX = 7 622 >>> Perm.RWX 623 <Perm.RWX: 7> 624 >>> ~Perm.RWX 625 <Perm.-8: -8> 626 627Another important difference between :class:`IntFlag` and :class:`Enum` is that 628if no flags are set (the value is 0), its boolean evaluation is :data:`False`:: 629 630 >>> Perm.R & Perm.X 631 <Perm.0: 0> 632 >>> bool(Perm.R & Perm.X) 633 False 634 635Because :class:`IntFlag` members are also subclasses of :class:`int` they can 636be combined with them:: 637 638 >>> Perm.X | 8 639 <Perm.8|X: 9> 640 641 642Flag 643^^^^ 644 645The last variation is :class:`Flag`. Like :class:`IntFlag`, :class:`Flag` 646members can be combined using the bitwise operators (&, \|, ^, ~). Unlike 647:class:`IntFlag`, they cannot be combined with, nor compared against, any 648other :class:`Flag` enumeration, nor :class:`int`. While it is possible to 649specify the values directly it is recommended to use :class:`auto` as the 650value and let :class:`Flag` select an appropriate value. 651 652.. versionadded:: 3.6 653 654Like :class:`IntFlag`, if a combination of :class:`Flag` members results in no 655flags being set, the boolean evaluation is :data:`False`:: 656 657 >>> from enum import Flag 658 >>> class Color(Flag): 659 ... RED = auto() 660 ... BLUE = auto() 661 ... GREEN = auto() 662 ... 663 >>> Color.RED & Color.GREEN 664 <Color.0: 0> 665 >>> bool(Color.RED & Color.GREEN) 666 False 667 668Individual flags should have values that are powers of two (1, 2, 4, 8, ...), 669while combinations of flags won't:: 670 671 >>> class Color(Flag): 672 ... RED = auto() 673 ... BLUE = auto() 674 ... GREEN = auto() 675 ... WHITE = RED | BLUE | GREEN 676 ... 677 >>> Color.WHITE 678 <Color.WHITE: 7> 679 680Giving a name to the "no flags set" condition does not change its boolean 681value:: 682 683 >>> class Color(Flag): 684 ... BLACK = 0 685 ... RED = auto() 686 ... BLUE = auto() 687 ... GREEN = auto() 688 ... 689 >>> Color.BLACK 690 <Color.BLACK: 0> 691 >>> bool(Color.BLACK) 692 False 693 694.. note:: 695 696 For the majority of new code, :class:`Enum` and :class:`Flag` are strongly 697 recommended, since :class:`IntEnum` and :class:`IntFlag` break some 698 semantic promises of an enumeration (by being comparable to integers, and 699 thus by transitivity to other unrelated enumerations). :class:`IntEnum` 700 and :class:`IntFlag` should be used only in cases where :class:`Enum` and 701 :class:`Flag` will not do; for example, when integer constants are replaced 702 with enumerations, or for interoperability with other systems. 703 704 705Others 706^^^^^^ 707 708While :class:`IntEnum` is part of the :mod:`enum` module, it would be very 709simple to implement independently:: 710 711 class IntEnum(int, Enum): 712 pass 713 714This demonstrates how similar derived enumerations can be defined; for example 715a :class:`StrEnum` that mixes in :class:`str` instead of :class:`int`. 716 717Some rules: 718 7191. When subclassing :class:`Enum`, mix-in types must appear before 720 :class:`Enum` itself in the sequence of bases, as in the :class:`IntEnum` 721 example above. 7222. While :class:`Enum` can have members of any type, once you mix in an 723 additional type, all the members must have values of that type, e.g. 724 :class:`int` above. This restriction does not apply to mix-ins which only 725 add methods and don't specify another data type such as :class:`int` or 726 :class:`str`. 7273. When another data type is mixed in, the :attr:`value` attribute is *not the 728 same* as the enum member itself, although it is equivalent and will compare 729 equal. 7304. %-style formatting: `%s` and `%r` call the :class:`Enum` class's 731 :meth:`__str__` and :meth:`__repr__` respectively; other codes (such as 732 `%i` or `%h` for IntEnum) treat the enum member as its mixed-in type. 7335. :ref:`Formatted string literals <f-strings>`, :meth:`str.format`, 734 and :func:`format` will use the mixed-in 735 type's :meth:`__format__`. If the :class:`Enum` class's :func:`str` or 736 :func:`repr` is desired, use the `!s` or `!r` format codes. 737 738 739Interesting examples 740-------------------- 741 742While :class:`Enum`, :class:`IntEnum`, :class:`IntFlag`, and :class:`Flag` are 743expected to cover the majority of use-cases, they cannot cover them all. Here 744are recipes for some different types of enumerations that can be used directly, 745or as examples for creating one's own. 746 747 748Omitting values 749^^^^^^^^^^^^^^^ 750 751In many use-cases one doesn't care what the actual value of an enumeration 752is. There are several ways to define this type of simple enumeration: 753 754- use instances of :class:`auto` for the value 755- use instances of :class:`object` as the value 756- use a descriptive string as the value 757- use a tuple as the value and a custom :meth:`__new__` to replace the 758 tuple with an :class:`int` value 759 760Using any of these methods signifies to the user that these values are not 761important, and also enables one to add, remove, or reorder members without 762having to renumber the remaining members. 763 764Whichever method you choose, you should provide a :meth:`repr` that also hides 765the (unimportant) value:: 766 767 >>> class NoValue(Enum): 768 ... def __repr__(self): 769 ... return '<%s.%s>' % (self.__class__.__name__, self.name) 770 ... 771 772 773Using :class:`auto` 774""""""""""""""""""" 775 776Using :class:`auto` would look like:: 777 778 >>> class Color(NoValue): 779 ... RED = auto() 780 ... BLUE = auto() 781 ... GREEN = auto() 782 ... 783 >>> Color.GREEN 784 <Color.GREEN> 785 786 787Using :class:`object` 788""""""""""""""""""""" 789 790Using :class:`object` would look like:: 791 792 >>> class Color(NoValue): 793 ... RED = object() 794 ... GREEN = object() 795 ... BLUE = object() 796 ... 797 >>> Color.GREEN 798 <Color.GREEN> 799 800 801Using a descriptive string 802"""""""""""""""""""""""""" 803 804Using a string as the value would look like:: 805 806 >>> class Color(NoValue): 807 ... RED = 'stop' 808 ... GREEN = 'go' 809 ... BLUE = 'too fast!' 810 ... 811 >>> Color.GREEN 812 <Color.GREEN> 813 >>> Color.GREEN.value 814 'go' 815 816 817Using a custom :meth:`__new__` 818"""""""""""""""""""""""""""""" 819 820Using an auto-numbering :meth:`__new__` would look like:: 821 822 >>> class AutoNumber(NoValue): 823 ... def __new__(cls): 824 ... value = len(cls.__members__) + 1 825 ... obj = object.__new__(cls) 826 ... obj._value_ = value 827 ... return obj 828 ... 829 >>> class Color(AutoNumber): 830 ... RED = () 831 ... GREEN = () 832 ... BLUE = () 833 ... 834 >>> Color.GREEN 835 <Color.GREEN> 836 >>> Color.GREEN.value 837 2 838 839 840.. note:: 841 842 The :meth:`__new__` method, if defined, is used during creation of the Enum 843 members; it is then replaced by Enum's :meth:`__new__` which is used after 844 class creation for lookup of existing members. 845 846 847OrderedEnum 848^^^^^^^^^^^ 849 850An ordered enumeration that is not based on :class:`IntEnum` and so maintains 851the normal :class:`Enum` invariants (such as not being comparable to other 852enumerations):: 853 854 >>> class OrderedEnum(Enum): 855 ... def __ge__(self, other): 856 ... if self.__class__ is other.__class__: 857 ... return self.value >= other.value 858 ... return NotImplemented 859 ... def __gt__(self, other): 860 ... if self.__class__ is other.__class__: 861 ... return self.value > other.value 862 ... return NotImplemented 863 ... def __le__(self, other): 864 ... if self.__class__ is other.__class__: 865 ... return self.value <= other.value 866 ... return NotImplemented 867 ... def __lt__(self, other): 868 ... if self.__class__ is other.__class__: 869 ... return self.value < other.value 870 ... return NotImplemented 871 ... 872 >>> class Grade(OrderedEnum): 873 ... A = 5 874 ... B = 4 875 ... C = 3 876 ... D = 2 877 ... F = 1 878 ... 879 >>> Grade.C < Grade.A 880 True 881 882 883DuplicateFreeEnum 884^^^^^^^^^^^^^^^^^ 885 886Raises an error if a duplicate member name is found instead of creating an 887alias:: 888 889 >>> class DuplicateFreeEnum(Enum): 890 ... def __init__(self, *args): 891 ... cls = self.__class__ 892 ... if any(self.value == e.value for e in cls): 893 ... a = self.name 894 ... e = cls(self.value).name 895 ... raise ValueError( 896 ... "aliases not allowed in DuplicateFreeEnum: %r --> %r" 897 ... % (a, e)) 898 ... 899 >>> class Color(DuplicateFreeEnum): 900 ... RED = 1 901 ... GREEN = 2 902 ... BLUE = 3 903 ... GRENE = 2 904 ... 905 Traceback (most recent call last): 906 ... 907 ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN' 908 909.. note:: 910 911 This is a useful example for subclassing Enum to add or change other 912 behaviors as well as disallowing aliases. If the only desired change is 913 disallowing aliases, the :func:`unique` decorator can be used instead. 914 915 916Planet 917^^^^^^ 918 919If :meth:`__new__` or :meth:`__init__` is defined the value of the enum member 920will be passed to those methods:: 921 922 >>> class Planet(Enum): 923 ... MERCURY = (3.303e+23, 2.4397e6) 924 ... VENUS = (4.869e+24, 6.0518e6) 925 ... EARTH = (5.976e+24, 6.37814e6) 926 ... MARS = (6.421e+23, 3.3972e6) 927 ... JUPITER = (1.9e+27, 7.1492e7) 928 ... SATURN = (5.688e+26, 6.0268e7) 929 ... URANUS = (8.686e+25, 2.5559e7) 930 ... NEPTUNE = (1.024e+26, 2.4746e7) 931 ... def __init__(self, mass, radius): 932 ... self.mass = mass # in kilograms 933 ... self.radius = radius # in meters 934 ... @property 935 ... def surface_gravity(self): 936 ... # universal gravitational constant (m3 kg-1 s-2) 937 ... G = 6.67300E-11 938 ... return G * self.mass / (self.radius * self.radius) 939 ... 940 >>> Planet.EARTH.value 941 (5.976e+24, 6378140.0) 942 >>> Planet.EARTH.surface_gravity 943 9.802652743337129 944 945 946How are Enums different? 947------------------------ 948 949Enums have a custom metaclass that affects many aspects of both derived Enum 950classes and their instances (members). 951 952 953Enum Classes 954^^^^^^^^^^^^ 955 956The :class:`EnumMeta` metaclass is responsible for providing the 957:meth:`__contains__`, :meth:`__dir__`, :meth:`__iter__` and other methods that 958allow one to do things with an :class:`Enum` class that fail on a typical 959class, such as `list(Color)` or `some_var in Color`. :class:`EnumMeta` is 960responsible for ensuring that various other methods on the final :class:`Enum` 961class are correct (such as :meth:`__new__`, :meth:`__getnewargs__`, 962:meth:`__str__` and :meth:`__repr__`). 963 964 965Enum Members (aka instances) 966^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 967 968The most interesting thing about Enum members is that they are singletons. 969:class:`EnumMeta` creates them all while it is creating the :class:`Enum` 970class itself, and then puts a custom :meth:`__new__` in place to ensure 971that no new ones are ever instantiated by returning only the existing 972member instances. 973 974 975Finer Points 976^^^^^^^^^^^^ 977 978Supported ``__dunder__`` names 979"""""""""""""""""""""""""""""" 980 981:attr:`__members__` is an :class:`OrderedDict` of ``member_name``:``member`` 982items. It is only available on the class. 983 984:meth:`__new__`, if specified, must create and return the enum members; it is 985also a very good idea to set the member's :attr:`_value_` appropriately. Once 986all the members are created it is no longer used. 987 988 989Supported ``_sunder_`` names 990"""""""""""""""""""""""""""" 991 992- ``_name_`` -- name of the member 993- ``_value_`` -- value of the member; can be set / modified in ``__new__`` 994 995- ``_missing_`` -- a lookup function used when a value is not found; may be 996 overridden 997- ``_order_`` -- used in Python 2/3 code to ensure member order is consistent 998 (class attribute, removed during class creation) 999- ``_generate_next_value_`` -- used by the `Functional API`_ and by 1000 :class:`auto` to get an appropriate value for an enum member; may be 1001 overridden 1002 1003.. versionadded:: 3.6 ``_missing_``, ``_order_``, ``_generate_next_value_`` 1004 1005To help keep Python 2 / Python 3 code in sync an :attr:`_order_` attribute can 1006be provided. It will be checked against the actual order of the enumeration 1007and raise an error if the two do not match:: 1008 1009 >>> class Color(Enum): 1010 ... _order_ = 'RED GREEN BLUE' 1011 ... RED = 1 1012 ... BLUE = 3 1013 ... GREEN = 2 1014 ... 1015 Traceback (most recent call last): 1016 ... 1017 TypeError: member order does not match _order_ 1018 1019.. note:: 1020 1021 In Python 2 code the :attr:`_order_` attribute is necessary as definition 1022 order is lost before it can be recorded. 1023 1024``Enum`` member type 1025"""""""""""""""""""" 1026 1027:class:`Enum` members are instances of their :class:`Enum` class, and are 1028normally accessed as ``EnumClass.member``. Under certain circumstances they 1029can also be accessed as ``EnumClass.member.member``, but you should never do 1030this as that lookup may fail or, worse, return something besides the 1031:class:`Enum` member you are looking for (this is another good reason to use 1032all-uppercase names for members):: 1033 1034 >>> class FieldTypes(Enum): 1035 ... name = 0 1036 ... value = 1 1037 ... size = 2 1038 ... 1039 >>> FieldTypes.value.size 1040 <FieldTypes.size: 2> 1041 >>> FieldTypes.size.value 1042 2 1043 1044.. versionchanged:: 3.5 1045 1046 1047Boolean value of ``Enum`` classes and members 1048""""""""""""""""""""""""""""""""""""""""""""" 1049 1050:class:`Enum` members that are mixed with non-:class:`Enum` types (such as 1051:class:`int`, :class:`str`, etc.) are evaluated according to the mixed-in 1052type's rules; otherwise, all members evaluate as :data:`True`. To make your 1053own Enum's boolean evaluation depend on the member's value add the following to 1054your class:: 1055 1056 def __bool__(self): 1057 return bool(self.value) 1058 1059:class:`Enum` classes always evaluate as :data:`True`. 1060 1061 1062``Enum`` classes with methods 1063""""""""""""""""""""""""""""" 1064 1065If you give your :class:`Enum` subclass extra methods, like the `Planet`_ 1066class above, those methods will show up in a :func:`dir` of the member, 1067but not of the class:: 1068 1069 >>> dir(Planet) 1070 ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__'] 1071 >>> dir(Planet.EARTH) 1072 ['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value'] 1073 1074 1075Combining members of ``Flag`` 1076""""""""""""""""""""""""""""" 1077 1078If a combination of Flag members is not named, the :func:`repr` will include 1079all named flags and all named combinations of flags that are in the value:: 1080 1081 >>> class Color(Flag): 1082 ... RED = auto() 1083 ... GREEN = auto() 1084 ... BLUE = auto() 1085 ... MAGENTA = RED | BLUE 1086 ... YELLOW = RED | GREEN 1087 ... CYAN = GREEN | BLUE 1088 ... 1089 >>> Color(3) # named combination 1090 <Color.YELLOW: 3> 1091 >>> Color(7) # not named combination 1092 <Color.CYAN|MAGENTA|BLUE|YELLOW|GREEN|RED: 7> 1093 1094