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. Initial value starts at 1. 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 276.. note:: 277 278 The :meth:`_generate_next_value_` method must be defined before any members. 279 280Iteration 281--------- 282 283Iterating over the members of an enum does not provide the aliases:: 284 285 >>> list(Shape) 286 [<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>] 287 288The special attribute ``__members__`` is a read-only ordered mapping of names 289to members. It includes all names defined in the enumeration, including the 290aliases:: 291 292 >>> for name, member in Shape.__members__.items(): 293 ... name, member 294 ... 295 ('SQUARE', <Shape.SQUARE: 2>) 296 ('DIAMOND', <Shape.DIAMOND: 1>) 297 ('CIRCLE', <Shape.CIRCLE: 3>) 298 ('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>) 299 300The ``__members__`` attribute can be used for detailed programmatic access to 301the enumeration members. For example, finding all the aliases:: 302 303 >>> [name for name, member in Shape.__members__.items() if member.name != name] 304 ['ALIAS_FOR_SQUARE'] 305 306 307Comparisons 308----------- 309 310Enumeration members are compared by identity:: 311 312 >>> Color.RED is Color.RED 313 True 314 >>> Color.RED is Color.BLUE 315 False 316 >>> Color.RED is not Color.BLUE 317 True 318 319Ordered comparisons between enumeration values are *not* supported. Enum 320members are not integers (but see `IntEnum`_ below):: 321 322 >>> Color.RED < Color.BLUE 323 Traceback (most recent call last): 324 File "<stdin>", line 1, in <module> 325 TypeError: '<' not supported between instances of 'Color' and 'Color' 326 327Equality comparisons are defined though:: 328 329 >>> Color.BLUE == Color.RED 330 False 331 >>> Color.BLUE != Color.RED 332 True 333 >>> Color.BLUE == Color.BLUE 334 True 335 336Comparisons against non-enumeration values will always compare not equal 337(again, :class:`IntEnum` was explicitly designed to behave differently, see 338below):: 339 340 >>> Color.BLUE == 2 341 False 342 343 344Allowed members and attributes of enumerations 345---------------------------------------------- 346 347The examples above use integers for enumeration values. Using integers is 348short and handy (and provided by default by the `Functional API`_), but not 349strictly enforced. In the vast majority of use-cases, one doesn't care what 350the actual value of an enumeration is. But if the value *is* important, 351enumerations can have arbitrary values. 352 353Enumerations are Python classes, and can have methods and special methods as 354usual. If we have this enumeration:: 355 356 >>> class Mood(Enum): 357 ... FUNKY = 1 358 ... HAPPY = 3 359 ... 360 ... def describe(self): 361 ... # self is the member here 362 ... return self.name, self.value 363 ... 364 ... def __str__(self): 365 ... return 'my custom str! {0}'.format(self.value) 366 ... 367 ... @classmethod 368 ... def favorite_mood(cls): 369 ... # cls here is the enumeration 370 ... return cls.HAPPY 371 ... 372 373Then:: 374 375 >>> Mood.favorite_mood() 376 <Mood.HAPPY: 3> 377 >>> Mood.HAPPY.describe() 378 ('HAPPY', 3) 379 >>> str(Mood.FUNKY) 380 'my custom str! 1' 381 382The rules for what is allowed are as follows: names that start and end with 383a single underscore are reserved by enum and cannot be used; all other 384attributes defined within an enumeration will become members of this 385enumeration, with the exception of special methods (:meth:`__str__`, 386:meth:`__add__`, etc.), descriptors (methods are also descriptors), and 387variable names listed in :attr:`_ignore_`. 388 389Note: if your enumeration defines :meth:`__new__` and/or :meth:`__init__` then 390whatever value(s) were given to the enum member will be passed into those 391methods. See `Planet`_ for an example. 392 393 394Restricted Enum subclassing 395--------------------------- 396 397A new :class:`Enum` class must have one base Enum class, up to one concrete 398data type, and as many :class:`object`-based mixin classes as needed. The 399order of these base classes is:: 400 401 class EnumName([mix-in, ...,] [data-type,] base-enum): 402 pass 403 404Also, subclassing an enumeration is allowed only if the enumeration does not define 405any members. So this is forbidden:: 406 407 >>> class MoreColor(Color): 408 ... PINK = 17 409 ... 410 Traceback (most recent call last): 411 ... 412 TypeError: Cannot extend enumerations 413 414But this is allowed:: 415 416 >>> class Foo(Enum): 417 ... def some_behavior(self): 418 ... pass 419 ... 420 >>> class Bar(Foo): 421 ... HAPPY = 1 422 ... SAD = 2 423 ... 424 425Allowing subclassing of enums that define members would lead to a violation of 426some important invariants of types and instances. On the other hand, it makes 427sense to allow sharing some common behavior between a group of enumerations. 428(See `OrderedEnum`_ for an example.) 429 430 431Pickling 432-------- 433 434Enumerations can be pickled and unpickled:: 435 436 >>> from test.test_enum import Fruit 437 >>> from pickle import dumps, loads 438 >>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO)) 439 True 440 441The usual restrictions for pickling apply: picklable enums must be defined in 442the top level of a module, since unpickling requires them to be importable 443from that module. 444 445.. note:: 446 447 With pickle protocol version 4 it is possible to easily pickle enums 448 nested in other classes. 449 450It is possible to modify how Enum members are pickled/unpickled by defining 451:meth:`__reduce_ex__` in the enumeration class. 452 453 454Functional API 455-------------- 456 457The :class:`Enum` class is callable, providing the following functional API:: 458 459 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG') 460 >>> Animal 461 <enum 'Animal'> 462 >>> Animal.ANT 463 <Animal.ANT: 1> 464 >>> Animal.ANT.value 465 1 466 >>> list(Animal) 467 [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>] 468 469The semantics of this API resemble :class:`~collections.namedtuple`. The first 470argument of the call to :class:`Enum` is the name of the enumeration. 471 472The second argument is the *source* of enumeration member names. It can be a 473whitespace-separated string of names, a sequence of names, a sequence of 4742-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to 475values. The last two options enable assigning arbitrary values to 476enumerations; the others auto-assign increasing integers starting with 1 (use 477the ``start`` parameter to specify a different starting value). A 478new class derived from :class:`Enum` is returned. In other words, the above 479assignment to :class:`Animal` is equivalent to:: 480 481 >>> class Animal(Enum): 482 ... ANT = 1 483 ... BEE = 2 484 ... CAT = 3 485 ... DOG = 4 486 ... 487 488The reason for defaulting to ``1`` as the starting number and not ``0`` is 489that ``0`` is ``False`` in a boolean sense, but enum members all evaluate 490to ``True``. 491 492Pickling enums created with the functional API can be tricky as frame stack 493implementation details are used to try and figure out which module the 494enumeration is being created in (e.g. it will fail if you use a utility 495function in separate module, and also may not work on IronPython or Jython). 496The solution is to specify the module name explicitly as follows:: 497 498 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__) 499 500.. warning:: 501 502 If ``module`` is not supplied, and Enum cannot determine what it is, 503 the new Enum members will not be unpicklable; to keep errors closer to 504 the source, pickling will be disabled. 505 506The new pickle protocol 4 also, in some circumstances, relies on 507:attr:`~definition.__qualname__` being set to the location where pickle will be able 508to find the class. For example, if the class was made available in class 509SomeData in the global scope:: 510 511 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal') 512 513The complete signature is:: 514 515 Enum(value='NewEnumName', names=<...>, *, module='...', qualname='...', type=<mixed-in class>, start=1) 516 517:value: What the new Enum class will record as its name. 518 519:names: The Enum members. This can be a whitespace or comma separated string 520 (values will start at 1 unless otherwise specified):: 521 522 'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE' 523 524 or an iterator of names:: 525 526 ['RED', 'GREEN', 'BLUE'] 527 528 or an iterator of (name, value) pairs:: 529 530 [('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)] 531 532 or a mapping:: 533 534 {'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42} 535 536:module: name of module where new Enum class can be found. 537 538:qualname: where in module new Enum class can be found. 539 540:type: type to mix in to new Enum class. 541 542:start: number to start counting at if only names are passed in. 543 544.. versionchanged:: 3.5 545 The *start* parameter was added. 546 547 548Derived Enumerations 549-------------------- 550 551IntEnum 552^^^^^^^ 553 554The first variation of :class:`Enum` that is provided is also a subclass of 555:class:`int`. Members of an :class:`IntEnum` can be compared to integers; 556by extension, integer enumerations of different types can also be compared 557to each other:: 558 559 >>> from enum import IntEnum 560 >>> class Shape(IntEnum): 561 ... CIRCLE = 1 562 ... SQUARE = 2 563 ... 564 >>> class Request(IntEnum): 565 ... POST = 1 566 ... GET = 2 567 ... 568 >>> Shape == 1 569 False 570 >>> Shape.CIRCLE == 1 571 True 572 >>> Shape.CIRCLE == Request.POST 573 True 574 575However, they still can't be compared to standard :class:`Enum` enumerations:: 576 577 >>> class Shape(IntEnum): 578 ... CIRCLE = 1 579 ... SQUARE = 2 580 ... 581 >>> class Color(Enum): 582 ... RED = 1 583 ... GREEN = 2 584 ... 585 >>> Shape.CIRCLE == Color.RED 586 False 587 588:class:`IntEnum` values behave like integers in other ways you'd expect:: 589 590 >>> int(Shape.CIRCLE) 591 1 592 >>> ['a', 'b', 'c'][Shape.CIRCLE] 593 'b' 594 >>> [i for i in range(Shape.SQUARE)] 595 [0, 1] 596 597 598IntFlag 599^^^^^^^ 600 601The next variation of :class:`Enum` provided, :class:`IntFlag`, is also based 602on :class:`int`. The difference being :class:`IntFlag` members can be combined 603using the bitwise operators (&, \|, ^, ~) and the result is still an 604:class:`IntFlag` member. However, as the name implies, :class:`IntFlag` 605members also subclass :class:`int` and can be used wherever an :class:`int` is 606used. Any operation on an :class:`IntFlag` member besides the bit-wise 607operations will lose the :class:`IntFlag` membership. 608 609.. versionadded:: 3.6 610 611Sample :class:`IntFlag` class:: 612 613 >>> from enum import IntFlag 614 >>> class Perm(IntFlag): 615 ... R = 4 616 ... W = 2 617 ... X = 1 618 ... 619 >>> Perm.R | Perm.W 620 <Perm.R|W: 6> 621 >>> Perm.R + Perm.W 622 6 623 >>> RW = Perm.R | Perm.W 624 >>> Perm.R in RW 625 True 626 627It is also possible to name the combinations:: 628 629 >>> class Perm(IntFlag): 630 ... R = 4 631 ... W = 2 632 ... X = 1 633 ... RWX = 7 634 >>> Perm.RWX 635 <Perm.RWX: 7> 636 >>> ~Perm.RWX 637 <Perm.-8: -8> 638 639Another important difference between :class:`IntFlag` and :class:`Enum` is that 640if no flags are set (the value is 0), its boolean evaluation is :data:`False`:: 641 642 >>> Perm.R & Perm.X 643 <Perm.0: 0> 644 >>> bool(Perm.R & Perm.X) 645 False 646 647Because :class:`IntFlag` members are also subclasses of :class:`int` they can 648be combined with them:: 649 650 >>> Perm.X | 8 651 <Perm.8|X: 9> 652 653 654Flag 655^^^^ 656 657The last variation is :class:`Flag`. Like :class:`IntFlag`, :class:`Flag` 658members can be combined using the bitwise operators (&, \|, ^, ~). Unlike 659:class:`IntFlag`, they cannot be combined with, nor compared against, any 660other :class:`Flag` enumeration, nor :class:`int`. While it is possible to 661specify the values directly it is recommended to use :class:`auto` as the 662value and let :class:`Flag` select an appropriate value. 663 664.. versionadded:: 3.6 665 666Like :class:`IntFlag`, if a combination of :class:`Flag` members results in no 667flags being set, the boolean evaluation is :data:`False`:: 668 669 >>> from enum import Flag, auto 670 >>> class Color(Flag): 671 ... RED = auto() 672 ... BLUE = auto() 673 ... GREEN = auto() 674 ... 675 >>> Color.RED & Color.GREEN 676 <Color.0: 0> 677 >>> bool(Color.RED & Color.GREEN) 678 False 679 680Individual flags should have values that are powers of two (1, 2, 4, 8, ...), 681while combinations of flags won't:: 682 683 >>> class Color(Flag): 684 ... RED = auto() 685 ... BLUE = auto() 686 ... GREEN = auto() 687 ... WHITE = RED | BLUE | GREEN 688 ... 689 >>> Color.WHITE 690 <Color.WHITE: 7> 691 692Giving a name to the "no flags set" condition does not change its boolean 693value:: 694 695 >>> class Color(Flag): 696 ... BLACK = 0 697 ... RED = auto() 698 ... BLUE = auto() 699 ... GREEN = auto() 700 ... 701 >>> Color.BLACK 702 <Color.BLACK: 0> 703 >>> bool(Color.BLACK) 704 False 705 706.. note:: 707 708 For the majority of new code, :class:`Enum` and :class:`Flag` are strongly 709 recommended, since :class:`IntEnum` and :class:`IntFlag` break some 710 semantic promises of an enumeration (by being comparable to integers, and 711 thus by transitivity to other unrelated enumerations). :class:`IntEnum` 712 and :class:`IntFlag` should be used only in cases where :class:`Enum` and 713 :class:`Flag` will not do; for example, when integer constants are replaced 714 with enumerations, or for interoperability with other systems. 715 716 717Others 718^^^^^^ 719 720While :class:`IntEnum` is part of the :mod:`enum` module, it would be very 721simple to implement independently:: 722 723 class IntEnum(int, Enum): 724 pass 725 726This demonstrates how similar derived enumerations can be defined; for example 727a :class:`StrEnum` that mixes in :class:`str` instead of :class:`int`. 728 729Some rules: 730 7311. When subclassing :class:`Enum`, mix-in types must appear before 732 :class:`Enum` itself in the sequence of bases, as in the :class:`IntEnum` 733 example above. 7342. While :class:`Enum` can have members of any type, once you mix in an 735 additional type, all the members must have values of that type, e.g. 736 :class:`int` above. This restriction does not apply to mix-ins which only 737 add methods and don't specify another data type such as :class:`int` or 738 :class:`str`. 7393. When another data type is mixed in, the :attr:`value` attribute is *not the 740 same* as the enum member itself, although it is equivalent and will compare 741 equal. 7424. %-style formatting: `%s` and `%r` call the :class:`Enum` class's 743 :meth:`__str__` and :meth:`__repr__` respectively; other codes (such as 744 `%i` or `%h` for IntEnum) treat the enum member as its mixed-in type. 7455. :ref:`Formatted string literals <f-strings>`, :meth:`str.format`, 746 and :func:`format` will use the mixed-in 747 type's :meth:`__format__`. If the :class:`Enum` class's :func:`str` or 748 :func:`repr` is desired, use the `!s` or `!r` format codes. 749 750When to use :meth:`__new__` vs. :meth:`__init__` 751------------------------------------------------ 752 753:meth:`__new__` must be used whenever you want to customize the actual value of 754the :class:`Enum` member. Any other modifications may go in either 755:meth:`__new__` or :meth:`__init__`, with :meth:`__init__` being preferred. 756 757For example, if you want to pass several items to the constructor, but only 758want one of them to be the value:: 759 760 >>> class Coordinate(bytes, Enum): 761 ... """ 762 ... Coordinate with binary codes that can be indexed by the int code. 763 ... """ 764 ... def __new__(cls, value, label, unit): 765 ... obj = bytes.__new__(cls, [value]) 766 ... obj._value_ = value 767 ... obj.label = label 768 ... obj.unit = unit 769 ... return obj 770 ... PX = (0, 'P.X', 'km') 771 ... PY = (1, 'P.Y', 'km') 772 ... VX = (2, 'V.X', 'km/s') 773 ... VY = (3, 'V.Y', 'km/s') 774 ... 775 776 >>> print(Coordinate['PY']) 777 Coordinate.PY 778 779 >>> print(Coordinate(3)) 780 Coordinate.VY 781 782Interesting examples 783-------------------- 784 785While :class:`Enum`, :class:`IntEnum`, :class:`IntFlag`, and :class:`Flag` are 786expected to cover the majority of use-cases, they cannot cover them all. Here 787are recipes for some different types of enumerations that can be used directly, 788or as examples for creating one's own. 789 790 791Omitting values 792^^^^^^^^^^^^^^^ 793 794In many use-cases one doesn't care what the actual value of an enumeration 795is. There are several ways to define this type of simple enumeration: 796 797- use instances of :class:`auto` for the value 798- use instances of :class:`object` as the value 799- use a descriptive string as the value 800- use a tuple as the value and a custom :meth:`__new__` to replace the 801 tuple with an :class:`int` value 802 803Using any of these methods signifies to the user that these values are not 804important, and also enables one to add, remove, or reorder members without 805having to renumber the remaining members. 806 807Whichever method you choose, you should provide a :meth:`repr` that also hides 808the (unimportant) value:: 809 810 >>> class NoValue(Enum): 811 ... def __repr__(self): 812 ... return '<%s.%s>' % (self.__class__.__name__, self.name) 813 ... 814 815 816Using :class:`auto` 817""""""""""""""""""" 818 819Using :class:`auto` would look like:: 820 821 >>> class Color(NoValue): 822 ... RED = auto() 823 ... BLUE = auto() 824 ... GREEN = auto() 825 ... 826 >>> Color.GREEN 827 <Color.GREEN> 828 829 830Using :class:`object` 831""""""""""""""""""""" 832 833Using :class:`object` would look like:: 834 835 >>> class Color(NoValue): 836 ... RED = object() 837 ... GREEN = object() 838 ... BLUE = object() 839 ... 840 >>> Color.GREEN 841 <Color.GREEN> 842 843 844Using a descriptive string 845"""""""""""""""""""""""""" 846 847Using a string as the value would look like:: 848 849 >>> class Color(NoValue): 850 ... RED = 'stop' 851 ... GREEN = 'go' 852 ... BLUE = 'too fast!' 853 ... 854 >>> Color.GREEN 855 <Color.GREEN> 856 >>> Color.GREEN.value 857 'go' 858 859 860Using a custom :meth:`__new__` 861"""""""""""""""""""""""""""""" 862 863Using an auto-numbering :meth:`__new__` would look like:: 864 865 >>> class AutoNumber(NoValue): 866 ... def __new__(cls): 867 ... value = len(cls.__members__) + 1 868 ... obj = object.__new__(cls) 869 ... obj._value_ = value 870 ... return obj 871 ... 872 >>> class Color(AutoNumber): 873 ... RED = () 874 ... GREEN = () 875 ... BLUE = () 876 ... 877 >>> Color.GREEN 878 <Color.GREEN> 879 >>> Color.GREEN.value 880 2 881 882 883.. note:: 884 885 The :meth:`__new__` method, if defined, is used during creation of the Enum 886 members; it is then replaced by Enum's :meth:`__new__` which is used after 887 class creation for lookup of existing members. 888 889 890OrderedEnum 891^^^^^^^^^^^ 892 893An ordered enumeration that is not based on :class:`IntEnum` and so maintains 894the normal :class:`Enum` invariants (such as not being comparable to other 895enumerations):: 896 897 >>> class OrderedEnum(Enum): 898 ... def __ge__(self, other): 899 ... if self.__class__ is other.__class__: 900 ... return self.value >= other.value 901 ... return NotImplemented 902 ... def __gt__(self, other): 903 ... if self.__class__ is other.__class__: 904 ... return self.value > other.value 905 ... return NotImplemented 906 ... def __le__(self, other): 907 ... if self.__class__ is other.__class__: 908 ... return self.value <= other.value 909 ... return NotImplemented 910 ... def __lt__(self, other): 911 ... if self.__class__ is other.__class__: 912 ... return self.value < other.value 913 ... return NotImplemented 914 ... 915 >>> class Grade(OrderedEnum): 916 ... A = 5 917 ... B = 4 918 ... C = 3 919 ... D = 2 920 ... F = 1 921 ... 922 >>> Grade.C < Grade.A 923 True 924 925 926DuplicateFreeEnum 927^^^^^^^^^^^^^^^^^ 928 929Raises an error if a duplicate member name is found instead of creating an 930alias:: 931 932 >>> class DuplicateFreeEnum(Enum): 933 ... def __init__(self, *args): 934 ... cls = self.__class__ 935 ... if any(self.value == e.value for e in cls): 936 ... a = self.name 937 ... e = cls(self.value).name 938 ... raise ValueError( 939 ... "aliases not allowed in DuplicateFreeEnum: %r --> %r" 940 ... % (a, e)) 941 ... 942 >>> class Color(DuplicateFreeEnum): 943 ... RED = 1 944 ... GREEN = 2 945 ... BLUE = 3 946 ... GRENE = 2 947 ... 948 Traceback (most recent call last): 949 ... 950 ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN' 951 952.. note:: 953 954 This is a useful example for subclassing Enum to add or change other 955 behaviors as well as disallowing aliases. If the only desired change is 956 disallowing aliases, the :func:`unique` decorator can be used instead. 957 958 959Planet 960^^^^^^ 961 962If :meth:`__new__` or :meth:`__init__` is defined the value of the enum member 963will be passed to those methods:: 964 965 >>> class Planet(Enum): 966 ... MERCURY = (3.303e+23, 2.4397e6) 967 ... VENUS = (4.869e+24, 6.0518e6) 968 ... EARTH = (5.976e+24, 6.37814e6) 969 ... MARS = (6.421e+23, 3.3972e6) 970 ... JUPITER = (1.9e+27, 7.1492e7) 971 ... SATURN = (5.688e+26, 6.0268e7) 972 ... URANUS = (8.686e+25, 2.5559e7) 973 ... NEPTUNE = (1.024e+26, 2.4746e7) 974 ... def __init__(self, mass, radius): 975 ... self.mass = mass # in kilograms 976 ... self.radius = radius # in meters 977 ... @property 978 ... def surface_gravity(self): 979 ... # universal gravitational constant (m3 kg-1 s-2) 980 ... G = 6.67300E-11 981 ... return G * self.mass / (self.radius * self.radius) 982 ... 983 >>> Planet.EARTH.value 984 (5.976e+24, 6378140.0) 985 >>> Planet.EARTH.surface_gravity 986 9.802652743337129 987 988 989TimePeriod 990^^^^^^^^^^ 991 992An example to show the :attr:`_ignore_` attribute in use:: 993 994 >>> from datetime import timedelta 995 >>> class Period(timedelta, Enum): 996 ... "different lengths of time" 997 ... _ignore_ = 'Period i' 998 ... Period = vars() 999 ... for i in range(367): 1000 ... Period['day_%d' % i] = i 1001 ... 1002 >>> list(Period)[:2] 1003 [<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>] 1004 >>> list(Period)[-2:] 1005 [<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>] 1006 1007 1008How are Enums different? 1009------------------------ 1010 1011Enums have a custom metaclass that affects many aspects of both derived Enum 1012classes and their instances (members). 1013 1014 1015Enum Classes 1016^^^^^^^^^^^^ 1017 1018The :class:`EnumMeta` metaclass is responsible for providing the 1019:meth:`__contains__`, :meth:`__dir__`, :meth:`__iter__` and other methods that 1020allow one to do things with an :class:`Enum` class that fail on a typical 1021class, such as `list(Color)` or `some_enum_var in Color`. :class:`EnumMeta` is 1022responsible for ensuring that various other methods on the final :class:`Enum` 1023class are correct (such as :meth:`__new__`, :meth:`__getnewargs__`, 1024:meth:`__str__` and :meth:`__repr__`). 1025 1026 1027Enum Members (aka instances) 1028^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1029 1030The most interesting thing about Enum members is that they are singletons. 1031:class:`EnumMeta` creates them all while it is creating the :class:`Enum` 1032class itself, and then puts a custom :meth:`__new__` in place to ensure 1033that no new ones are ever instantiated by returning only the existing 1034member instances. 1035 1036 1037Finer Points 1038^^^^^^^^^^^^ 1039 1040Supported ``__dunder__`` names 1041"""""""""""""""""""""""""""""" 1042 1043:attr:`__members__` is a read-only ordered mapping of ``member_name``:``member`` 1044items. It is only available on the class. 1045 1046:meth:`__new__`, if specified, must create and return the enum members; it is 1047also a very good idea to set the member's :attr:`_value_` appropriately. Once 1048all the members are created it is no longer used. 1049 1050 1051Supported ``_sunder_`` names 1052"""""""""""""""""""""""""""" 1053 1054- ``_name_`` -- name of the member 1055- ``_value_`` -- value of the member; can be set / modified in ``__new__`` 1056 1057- ``_missing_`` -- a lookup function used when a value is not found; may be 1058 overridden 1059- ``_ignore_`` -- a list of names, either as a :func:`list` or a :func:`str`, 1060 that will not be transformed into members, and will be removed from the final 1061 class 1062- ``_order_`` -- used in Python 2/3 code to ensure member order is consistent 1063 (class attribute, removed during class creation) 1064- ``_generate_next_value_`` -- used by the `Functional API`_ and by 1065 :class:`auto` to get an appropriate value for an enum member; may be 1066 overridden 1067 1068.. versionadded:: 3.6 ``_missing_``, ``_order_``, ``_generate_next_value_`` 1069.. versionadded:: 3.7 ``_ignore_`` 1070 1071To help keep Python 2 / Python 3 code in sync an :attr:`_order_` attribute can 1072be provided. It will be checked against the actual order of the enumeration 1073and raise an error if the two do not match:: 1074 1075 >>> class Color(Enum): 1076 ... _order_ = 'RED GREEN BLUE' 1077 ... RED = 1 1078 ... BLUE = 3 1079 ... GREEN = 2 1080 ... 1081 Traceback (most recent call last): 1082 ... 1083 TypeError: member order does not match _order_ 1084 1085.. note:: 1086 1087 In Python 2 code the :attr:`_order_` attribute is necessary as definition 1088 order is lost before it can be recorded. 1089 1090``Enum`` member type 1091"""""""""""""""""""" 1092 1093:class:`Enum` members are instances of their :class:`Enum` class, and are 1094normally accessed as ``EnumClass.member``. Under certain circumstances they 1095can also be accessed as ``EnumClass.member.member``, but you should never do 1096this as that lookup may fail or, worse, return something besides the 1097:class:`Enum` member you are looking for (this is another good reason to use 1098all-uppercase names for members):: 1099 1100 >>> class FieldTypes(Enum): 1101 ... name = 0 1102 ... value = 1 1103 ... size = 2 1104 ... 1105 >>> FieldTypes.value.size 1106 <FieldTypes.size: 2> 1107 >>> FieldTypes.size.value 1108 2 1109 1110.. versionchanged:: 3.5 1111 1112 1113Boolean value of ``Enum`` classes and members 1114""""""""""""""""""""""""""""""""""""""""""""" 1115 1116:class:`Enum` members that are mixed with non-:class:`Enum` types (such as 1117:class:`int`, :class:`str`, etc.) are evaluated according to the mixed-in 1118type's rules; otherwise, all members evaluate as :data:`True`. To make your 1119own Enum's boolean evaluation depend on the member's value add the following to 1120your class:: 1121 1122 def __bool__(self): 1123 return bool(self.value) 1124 1125:class:`Enum` classes always evaluate as :data:`True`. 1126 1127 1128``Enum`` classes with methods 1129""""""""""""""""""""""""""""" 1130 1131If you give your :class:`Enum` subclass extra methods, like the `Planet`_ 1132class above, those methods will show up in a :func:`dir` of the member, 1133but not of the class:: 1134 1135 >>> dir(Planet) 1136 ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__'] 1137 >>> dir(Planet.EARTH) 1138 ['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value'] 1139 1140 1141Combining members of ``Flag`` 1142""""""""""""""""""""""""""""" 1143 1144If a combination of Flag members is not named, the :func:`repr` will include 1145all named flags and all named combinations of flags that are in the value:: 1146 1147 >>> class Color(Flag): 1148 ... RED = auto() 1149 ... GREEN = auto() 1150 ... BLUE = auto() 1151 ... MAGENTA = RED | BLUE 1152 ... YELLOW = RED | GREEN 1153 ... CYAN = GREEN | BLUE 1154 ... 1155 >>> Color(3) # named combination 1156 <Color.YELLOW: 3> 1157 >>> Color(7) # not named combination 1158 <Color.CYAN|MAGENTA|BLUE|YELLOW|GREEN|RED: 7> 1159 1160