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