1========== 2Enum HOWTO 3========== 4 5.. _enum-basic-tutorial: 6 7.. currentmodule:: enum 8 9An :class:`Enum` is a set of symbolic names bound to unique values. They are 10similar to global variables, but they offer a more useful :func:`repr()`, 11grouping, type-safety, and a few other features. 12 13They are most useful when you have a variable that can take one of a limited 14selection of values. For example, the days of the week:: 15 16 >>> from enum import Enum 17 >>> class Weekday(Enum): 18 ... MONDAY = 1 19 ... TUESDAY = 2 20 ... WEDNESDAY = 3 21 ... THURSDAY = 4 22 ... FRIDAY = 5 23 ... SATURDAY = 6 24 ... SUNDAY = 7 25 26Or perhaps the RGB primary colors:: 27 28 >>> from enum import Enum 29 >>> class Color(Enum): 30 ... RED = 1 31 ... GREEN = 2 32 ... BLUE = 3 33 34As you can see, creating an :class:`Enum` is as simple as writing a class that 35inherits from :class:`Enum` itself. 36 37.. note:: Case of Enum Members 38 39 Because Enums are used to represent constants we recommend using 40 UPPER_CASE names for members, and will be using that style in our examples. 41 42Depending on the nature of the enum a member's value may or may not be 43important, but either way that value can be used to get the corresponding 44member:: 45 46 >>> Weekday(3) 47 <Weekday.WEDNESDAY: 3> 48 49As you can see, the ``repr()`` of a member shows the enum name, the member name, 50and the value. The ``str()`` of a member shows only the enum name and member 51name:: 52 53 >>> print(Weekday.THURSDAY) 54 Weekday.THURSDAY 55 56The *type* of an enumeration member is the enum it belongs to:: 57 58 >>> type(Weekday.MONDAY) 59 <enum 'Weekday'> 60 >>> isinstance(Weekday.FRIDAY, Weekday) 61 True 62 63Enum members have an attribute that contains just their :attr:`name`:: 64 65 >>> print(Weekday.TUESDAY.name) 66 TUESDAY 67 68Likewise, they have an attribute for their :attr:`value`:: 69 70 71 >>> Weekday.WEDNESDAY.value 72 3 73 74Unlike many languages that treat enumerations solely as name/value pairs, 75Python Enums can have behavior added. For example, :class:`datetime.date` 76has two methods for returning the weekday: :meth:`weekday` and :meth:`isoweekday`. 77The difference is that one of them counts from 0-6 and the other from 1-7. 78Rather than keep track of that ourselves we can add a method to the :class:`Weekday` 79enum to extract the day from the :class:`date` instance and return the matching 80enum member:: 81 82 @classmethod 83 def from_date(cls, date): 84 return cls(date.isoweekday()) 85 86The complete :class:`Weekday` enum now looks like this:: 87 88 >>> class Weekday(Enum): 89 ... MONDAY = 1 90 ... TUESDAY = 2 91 ... WEDNESDAY = 3 92 ... THURSDAY = 4 93 ... FRIDAY = 5 94 ... SATURDAY = 6 95 ... SUNDAY = 7 96 ... # 97 ... @classmethod 98 ... def from_date(cls, date): 99 ... return cls(date.isoweekday()) 100 101Now we can find out what today is! Observe:: 102 103 >>> from datetime import date 104 >>> Weekday.from_date(date.today()) # doctest: +SKIP 105 <Weekday.TUESDAY: 2> 106 107Of course, if you're reading this on some other day, you'll see that day instead. 108 109This :class:`Weekday` enum is great if our variable only needs one day, but 110what if we need several? Maybe we're writing a function to plot chores during 111a week, and don't want to use a :class:`list` -- we could use a different type 112of :class:`Enum`:: 113 114 >>> from enum import Flag 115 >>> class Weekday(Flag): 116 ... MONDAY = 1 117 ... TUESDAY = 2 118 ... WEDNESDAY = 4 119 ... THURSDAY = 8 120 ... FRIDAY = 16 121 ... SATURDAY = 32 122 ... SUNDAY = 64 123 124We've changed two things: we're inherited from :class:`Flag`, and the values are 125all powers of 2. 126 127Just like the original :class:`Weekday` enum above, we can have a single selection:: 128 129 >>> first_week_day = Weekday.MONDAY 130 >>> first_week_day 131 <Weekday.MONDAY: 1> 132 133But :class:`Flag` also allows us to combine several members into a single 134variable:: 135 136 >>> weekend = Weekday.SATURDAY | Weekday.SUNDAY 137 >>> weekend 138 <Weekday.SATURDAY|SUNDAY: 96> 139 140You can even iterate over a :class:`Flag` variable:: 141 142 >>> for day in weekend: 143 ... print(day) 144 Weekday.SATURDAY 145 Weekday.SUNDAY 146 147Okay, let's get some chores set up:: 148 149 >>> chores_for_ethan = { 150 ... 'feed the cat': Weekday.MONDAY | Weekday.WEDNESDAY | Weekday.FRIDAY, 151 ... 'do the dishes': Weekday.TUESDAY | Weekday.THURSDAY, 152 ... 'answer SO questions': Weekday.SATURDAY, 153 ... } 154 155And a function to display the chores for a given day:: 156 157 >>> def show_chores(chores, day): 158 ... for chore, days in chores.items(): 159 ... if day in days: 160 ... print(chore) 161 >>> show_chores(chores_for_ethan, Weekday.SATURDAY) 162 answer SO questions 163 164In cases where the actual values of the members do not matter, you can save 165yourself some work and use :func:`auto()` for the values:: 166 167 >>> from enum import auto 168 >>> class Weekday(Flag): 169 ... MONDAY = auto() 170 ... TUESDAY = auto() 171 ... WEDNESDAY = auto() 172 ... THURSDAY = auto() 173 ... FRIDAY = auto() 174 ... SATURDAY = auto() 175 ... SUNDAY = auto() 176 ... WEEKEND = SATURDAY | SUNDAY 177 178 179.. _enum-advanced-tutorial: 180 181 182Programmatic access to enumeration members and their attributes 183--------------------------------------------------------------- 184 185Sometimes it's useful to access members in enumerations programmatically (i.e. 186situations where ``Color.RED`` won't do because the exact color is not known 187at program-writing time). ``Enum`` allows such access:: 188 189 >>> Color(1) 190 <Color.RED: 1> 191 >>> Color(3) 192 <Color.BLUE: 3> 193 194If you want to access enum members by *name*, use item access:: 195 196 >>> Color['RED'] 197 <Color.RED: 1> 198 >>> Color['GREEN'] 199 <Color.GREEN: 2> 200 201If you have an enum member and need its :attr:`name` or :attr:`value`:: 202 203 >>> member = Color.RED 204 >>> member.name 205 'RED' 206 >>> member.value 207 1 208 209 210Duplicating enum members and values 211----------------------------------- 212 213Having two enum members with the same name is invalid:: 214 215 >>> class Shape(Enum): 216 ... SQUARE = 2 217 ... SQUARE = 3 218 ... 219 Traceback (most recent call last): 220 ... 221 TypeError: 'SQUARE' already defined as 2 222 223However, an enum member can have other names associated with it. Given two 224entries ``A`` and ``B`` with the same value (and ``A`` defined first), ``B`` 225is an alias for the member ``A``. By-value lookup of the value of ``A`` will 226return the member ``A``. By-name lookup of ``A`` will return the member ``A``. 227By-name lookup of ``B`` will also return the member ``A``:: 228 229 >>> class Shape(Enum): 230 ... SQUARE = 2 231 ... DIAMOND = 1 232 ... CIRCLE = 3 233 ... ALIAS_FOR_SQUARE = 2 234 ... 235 >>> Shape.SQUARE 236 <Shape.SQUARE: 2> 237 >>> Shape.ALIAS_FOR_SQUARE 238 <Shape.SQUARE: 2> 239 >>> Shape(2) 240 <Shape.SQUARE: 2> 241 242.. note:: 243 244 Attempting to create a member with the same name as an already 245 defined attribute (another member, a method, etc.) or attempting to create 246 an attribute with the same name as a member is not allowed. 247 248 249Ensuring unique enumeration values 250---------------------------------- 251 252By default, enumerations allow multiple names as aliases for the same value. 253When this behavior isn't desired, you can use the :func:`unique` decorator:: 254 255 >>> from enum import Enum, unique 256 >>> @unique 257 ... class Mistake(Enum): 258 ... ONE = 1 259 ... TWO = 2 260 ... THREE = 3 261 ... FOUR = 3 262 ... 263 Traceback (most recent call last): 264 ... 265 ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE 266 267 268Using automatic values 269---------------------- 270 271If the exact value is unimportant you can use :class:`auto`:: 272 273 >>> from enum import Enum, auto 274 >>> class Color(Enum): 275 ... RED = auto() 276 ... BLUE = auto() 277 ... GREEN = auto() 278 ... 279 >>> [member.value for member in Color] 280 [1, 2, 3] 281 282The values are chosen by :func:`_generate_next_value_`, which can be 283overridden:: 284 285 >>> class AutoName(Enum): 286 ... def _generate_next_value_(name, start, count, last_values): 287 ... return name 288 ... 289 >>> class Ordinal(AutoName): 290 ... NORTH = auto() 291 ... SOUTH = auto() 292 ... EAST = auto() 293 ... WEST = auto() 294 ... 295 >>> [member.value for member in Ordinal] 296 ['NORTH', 'SOUTH', 'EAST', 'WEST'] 297 298.. note:: 299 300 The :meth:`_generate_next_value_` method must be defined before any members. 301 302Iteration 303--------- 304 305Iterating over the members of an enum does not provide the aliases:: 306 307 >>> list(Shape) 308 [<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>] 309 >>> list(Weekday) 310 [<Weekday.MONDAY: 1>, <Weekday.TUESDAY: 2>, <Weekday.WEDNESDAY: 4>, <Weekday.THURSDAY: 8>, <Weekday.FRIDAY: 16>, <Weekday.SATURDAY: 32>, <Weekday.SUNDAY: 64>] 311 312Note that the aliases ``Shape.ALIAS_FOR_SQUARE`` and ``Weekday.WEEKEND`` aren't shown. 313 314The special attribute ``__members__`` is a read-only ordered mapping of names 315to members. It includes all names defined in the enumeration, including the 316aliases:: 317 318 >>> for name, member in Shape.__members__.items(): 319 ... name, member 320 ... 321 ('SQUARE', <Shape.SQUARE: 2>) 322 ('DIAMOND', <Shape.DIAMOND: 1>) 323 ('CIRCLE', <Shape.CIRCLE: 3>) 324 ('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>) 325 326The ``__members__`` attribute can be used for detailed programmatic access to 327the enumeration members. For example, finding all the aliases:: 328 329 >>> [name for name, member in Shape.__members__.items() if member.name != name] 330 ['ALIAS_FOR_SQUARE'] 331 332.. note:: 333 334 Aliases for flags include values with multiple flags set, such as ``3``, 335 and no flags set, i.e. ``0``. 336 337 338Comparisons 339----------- 340 341Enumeration members are compared by identity:: 342 343 >>> Color.RED is Color.RED 344 True 345 >>> Color.RED is Color.BLUE 346 False 347 >>> Color.RED is not Color.BLUE 348 True 349 350Ordered comparisons between enumeration values are *not* supported. Enum 351members are not integers (but see `IntEnum`_ below):: 352 353 >>> Color.RED < Color.BLUE 354 Traceback (most recent call last): 355 File "<stdin>", line 1, in <module> 356 TypeError: '<' not supported between instances of 'Color' and 'Color' 357 358Equality comparisons are defined though:: 359 360 >>> Color.BLUE == Color.RED 361 False 362 >>> Color.BLUE != Color.RED 363 True 364 >>> Color.BLUE == Color.BLUE 365 True 366 367Comparisons against non-enumeration values will always compare not equal 368(again, :class:`IntEnum` was explicitly designed to behave differently, see 369below):: 370 371 >>> Color.BLUE == 2 372 False 373 374.. warning:: 375 376 It is possible to reload modules -- if a reloaded module contains 377 enums, they will be recreated, and the new members may not 378 compare identical/equal to the original members. 379 380Allowed members and attributes of enumerations 381---------------------------------------------- 382 383Most of the examples above use integers for enumeration values. Using integers 384is short and handy (and provided by default by the `Functional API`_), but not 385strictly enforced. In the vast majority of use-cases, one doesn't care what 386the actual value of an enumeration is. But if the value *is* important, 387enumerations can have arbitrary values. 388 389Enumerations are Python classes, and can have methods and special methods as 390usual. If we have this enumeration:: 391 392 >>> class Mood(Enum): 393 ... FUNKY = 1 394 ... HAPPY = 3 395 ... 396 ... def describe(self): 397 ... # self is the member here 398 ... return self.name, self.value 399 ... 400 ... def __str__(self): 401 ... return 'my custom str! {0}'.format(self.value) 402 ... 403 ... @classmethod 404 ... def favorite_mood(cls): 405 ... # cls here is the enumeration 406 ... return cls.HAPPY 407 ... 408 409Then:: 410 411 >>> Mood.favorite_mood() 412 <Mood.HAPPY: 3> 413 >>> Mood.HAPPY.describe() 414 ('HAPPY', 3) 415 >>> str(Mood.FUNKY) 416 'my custom str! 1' 417 418The rules for what is allowed are as follows: names that start and end with 419a single underscore are reserved by enum and cannot be used; all other 420attributes defined within an enumeration will become members of this 421enumeration, with the exception of special methods (:meth:`__str__`, 422:meth:`__add__`, etc.), descriptors (methods are also descriptors), and 423variable names listed in :attr:`_ignore_`. 424 425Note: if your enumeration defines :meth:`__new__` and/or :meth:`__init__` then 426any value(s) given to the enum member will be passed into those methods. 427See `Planet`_ for an example. 428 429 430Restricted Enum subclassing 431--------------------------- 432 433A new :class:`Enum` class must have one base enum class, up to one concrete 434data type, and as many :class:`object`-based mixin classes as needed. The 435order of these base classes is:: 436 437 class EnumName([mix-in, ...,] [data-type,] base-enum): 438 pass 439 440Also, subclassing an enumeration is allowed only if the enumeration does not define 441any members. So this is forbidden:: 442 443 >>> class MoreColor(Color): 444 ... PINK = 17 445 ... 446 Traceback (most recent call last): 447 ... 448 TypeError: <enum 'MoreColor'> cannot extend <enum 'Color'> 449 450But this is allowed:: 451 452 >>> class Foo(Enum): 453 ... def some_behavior(self): 454 ... pass 455 ... 456 >>> class Bar(Foo): 457 ... HAPPY = 1 458 ... SAD = 2 459 ... 460 461Allowing subclassing of enums that define members would lead to a violation of 462some important invariants of types and instances. On the other hand, it makes 463sense to allow sharing some common behavior between a group of enumerations. 464(See `OrderedEnum`_ for an example.) 465 466 467Pickling 468-------- 469 470Enumerations can be pickled and unpickled:: 471 472 >>> from test.test_enum import Fruit 473 >>> from pickle import dumps, loads 474 >>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO)) 475 True 476 477The usual restrictions for pickling apply: picklable enums must be defined in 478the top level of a module, since unpickling requires them to be importable 479from that module. 480 481.. note:: 482 483 With pickle protocol version 4 it is possible to easily pickle enums 484 nested in other classes. 485 486It is possible to modify how enum members are pickled/unpickled by defining 487:meth:`__reduce_ex__` in the enumeration class. 488 489 490Functional API 491-------------- 492 493The :class:`Enum` class is callable, providing the following functional API:: 494 495 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG') 496 >>> Animal 497 <enum 'Animal'> 498 >>> Animal.ANT 499 <Animal.ANT: 1> 500 >>> list(Animal) 501 [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>] 502 503The semantics of this API resemble :class:`~collections.namedtuple`. The first 504argument of the call to :class:`Enum` is the name of the enumeration. 505 506The second argument is the *source* of enumeration member names. It can be a 507whitespace-separated string of names, a sequence of names, a sequence of 5082-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to 509values. The last two options enable assigning arbitrary values to 510enumerations; the others auto-assign increasing integers starting with 1 (use 511the ``start`` parameter to specify a different starting value). A 512new class derived from :class:`Enum` is returned. In other words, the above 513assignment to :class:`Animal` is equivalent to:: 514 515 >>> class Animal(Enum): 516 ... ANT = 1 517 ... BEE = 2 518 ... CAT = 3 519 ... DOG = 4 520 ... 521 522The reason for defaulting to ``1`` as the starting number and not ``0`` is 523that ``0`` is ``False`` in a boolean sense, but by default enum members all 524evaluate to ``True``. 525 526Pickling enums created with the functional API can be tricky as frame stack 527implementation details are used to try and figure out which module the 528enumeration is being created in (e.g. it will fail if you use a utility 529function in a separate module, and also may not work on IronPython or Jython). 530The solution is to specify the module name explicitly as follows:: 531 532 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__) 533 534.. warning:: 535 536 If ``module`` is not supplied, and Enum cannot determine what it is, 537 the new Enum members will not be unpicklable; to keep errors closer to 538 the source, pickling will be disabled. 539 540The new pickle protocol 4 also, in some circumstances, relies on 541:attr:`~definition.__qualname__` being set to the location where pickle will be able 542to find the class. For example, if the class was made available in class 543SomeData in the global scope:: 544 545 >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal') 546 547The complete signature is:: 548 549 Enum( 550 value='NewEnumName', 551 names=<...>, 552 *, 553 module='...', 554 qualname='...', 555 type=<mixed-in class>, 556 start=1, 557 ) 558 559:value: What the new enum class will record as its name. 560 561:names: The enum members. This can be a whitespace- or comma-separated string 562 (values will start at 1 unless otherwise specified):: 563 564 'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE' 565 566 or an iterator of names:: 567 568 ['RED', 'GREEN', 'BLUE'] 569 570 or an iterator of (name, value) pairs:: 571 572 [('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)] 573 574 or a mapping:: 575 576 {'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42} 577 578:module: name of module where new enum class can be found. 579 580:qualname: where in module new enum class can be found. 581 582:type: type to mix in to new enum class. 583 584:start: number to start counting at if only names are passed in. 585 586.. versionchanged:: 3.5 587 The *start* parameter was added. 588 589 590Derived Enumerations 591-------------------- 592 593IntEnum 594^^^^^^^ 595 596The first variation of :class:`Enum` that is provided is also a subclass of 597:class:`int`. Members of an :class:`IntEnum` can be compared to integers; 598by extension, integer enumerations of different types can also be compared 599to each other:: 600 601 >>> from enum import IntEnum 602 >>> class Shape(IntEnum): 603 ... CIRCLE = 1 604 ... SQUARE = 2 605 ... 606 >>> class Request(IntEnum): 607 ... POST = 1 608 ... GET = 2 609 ... 610 >>> Shape == 1 611 False 612 >>> Shape.CIRCLE == 1 613 True 614 >>> Shape.CIRCLE == Request.POST 615 True 616 617However, they still can't be compared to standard :class:`Enum` enumerations:: 618 619 >>> class Shape(IntEnum): 620 ... CIRCLE = 1 621 ... SQUARE = 2 622 ... 623 >>> class Color(Enum): 624 ... RED = 1 625 ... GREEN = 2 626 ... 627 >>> Shape.CIRCLE == Color.RED 628 False 629 630:class:`IntEnum` values behave like integers in other ways you'd expect:: 631 632 >>> int(Shape.CIRCLE) 633 1 634 >>> ['a', 'b', 'c'][Shape.CIRCLE] 635 'b' 636 >>> [i for i in range(Shape.SQUARE)] 637 [0, 1] 638 639 640StrEnum 641^^^^^^^ 642 643The second variation of :class:`Enum` that is provided is also a subclass of 644:class:`str`. Members of a :class:`StrEnum` can be compared to strings; 645by extension, string enumerations of different types can also be compared 646to each other. 647 648.. versionadded:: 3.11 649 650 651IntFlag 652^^^^^^^ 653 654The next variation of :class:`Enum` provided, :class:`IntFlag`, is also based 655on :class:`int`. The difference being :class:`IntFlag` members can be combined 656using the bitwise operators (&, \|, ^, ~) and the result is still an 657:class:`IntFlag` member, if possible. Like :class:`IntEnum`, :class:`IntFlag` 658members are also integers and can be used wherever an :class:`int` is used. 659 660.. note:: 661 662 Any operation on an :class:`IntFlag` member besides the bit-wise operations will 663 lose the :class:`IntFlag` membership. 664 665 Bit-wise operations that result in invalid :class:`IntFlag` values will lose the 666 :class:`IntFlag` membership. See :class:`FlagBoundary` for 667 details. 668 669.. versionadded:: 3.6 670.. versionchanged:: 3.11 671 672Sample :class:`IntFlag` class:: 673 674 >>> from enum import IntFlag 675 >>> class Perm(IntFlag): 676 ... R = 4 677 ... W = 2 678 ... X = 1 679 ... 680 >>> Perm.R | Perm.W 681 <Perm.R|W: 6> 682 >>> Perm.R + Perm.W 683 6 684 >>> RW = Perm.R | Perm.W 685 >>> Perm.R in RW 686 True 687 688It is also possible to name the combinations:: 689 690 >>> class Perm(IntFlag): 691 ... R = 4 692 ... W = 2 693 ... X = 1 694 ... RWX = 7 695 >>> Perm.RWX 696 <Perm.RWX: 7> 697 >>> ~Perm.RWX 698 <Perm: 0> 699 >>> Perm(7) 700 <Perm.RWX: 7> 701 702.. note:: 703 704 Named combinations are considered aliases. Aliases do not show up during 705 iteration, but can be returned from by-value lookups. 706 707.. versionchanged:: 3.11 708 709Another important difference between :class:`IntFlag` and :class:`Enum` is that 710if no flags are set (the value is 0), its boolean evaluation is :data:`False`:: 711 712 >>> Perm.R & Perm.X 713 <Perm: 0> 714 >>> bool(Perm.R & Perm.X) 715 False 716 717Because :class:`IntFlag` members are also subclasses of :class:`int` they can 718be combined with them (but may lose :class:`IntFlag` membership:: 719 720 >>> Perm.X | 4 721 <Perm.R|X: 5> 722 723 >>> Perm.X | 8 724 9 725 726.. note:: 727 728 The negation operator, ``~``, always returns an :class:`IntFlag` member with a 729 positive value:: 730 731 >>> (~Perm.X).value == (Perm.R|Perm.W).value == 6 732 True 733 734:class:`IntFlag` members can also be iterated over:: 735 736 >>> list(RW) 737 [<Perm.R: 4>, <Perm.W: 2>] 738 739.. versionadded:: 3.11 740 741 742Flag 743^^^^ 744 745The last variation is :class:`Flag`. Like :class:`IntFlag`, :class:`Flag` 746members can be combined using the bitwise operators (&, \|, ^, ~). Unlike 747:class:`IntFlag`, they cannot be combined with, nor compared against, any 748other :class:`Flag` enumeration, nor :class:`int`. While it is possible to 749specify the values directly it is recommended to use :class:`auto` as the 750value and let :class:`Flag` select an appropriate value. 751 752.. versionadded:: 3.6 753 754Like :class:`IntFlag`, if a combination of :class:`Flag` members results in no 755flags being set, the boolean evaluation is :data:`False`:: 756 757 >>> from enum import Flag, auto 758 >>> class Color(Flag): 759 ... RED = auto() 760 ... BLUE = auto() 761 ... GREEN = auto() 762 ... 763 >>> Color.RED & Color.GREEN 764 <Color: 0> 765 >>> bool(Color.RED & Color.GREEN) 766 False 767 768Individual flags should have values that are powers of two (1, 2, 4, 8, ...), 769while combinations of flags will not:: 770 771 >>> class Color(Flag): 772 ... RED = auto() 773 ... BLUE = auto() 774 ... GREEN = auto() 775 ... WHITE = RED | BLUE | GREEN 776 ... 777 >>> Color.WHITE 778 <Color.WHITE: 7> 779 780Giving a name to the "no flags set" condition does not change its boolean 781value:: 782 783 >>> class Color(Flag): 784 ... BLACK = 0 785 ... RED = auto() 786 ... BLUE = auto() 787 ... GREEN = auto() 788 ... 789 >>> Color.BLACK 790 <Color.BLACK: 0> 791 >>> bool(Color.BLACK) 792 False 793 794:class:`Flag` members can also be iterated over:: 795 796 >>> purple = Color.RED | Color.BLUE 797 >>> list(purple) 798 [<Color.RED: 1>, <Color.BLUE: 2>] 799 800.. versionadded:: 3.11 801 802.. note:: 803 804 For the majority of new code, :class:`Enum` and :class:`Flag` are strongly 805 recommended, since :class:`IntEnum` and :class:`IntFlag` break some 806 semantic promises of an enumeration (by being comparable to integers, and 807 thus by transitivity to other unrelated enumerations). :class:`IntEnum` 808 and :class:`IntFlag` should be used only in cases where :class:`Enum` and 809 :class:`Flag` will not do; for example, when integer constants are replaced 810 with enumerations, or for interoperability with other systems. 811 812 813Others 814^^^^^^ 815 816While :class:`IntEnum` is part of the :mod:`enum` module, it would be very 817simple to implement independently:: 818 819 class IntEnum(int, Enum): 820 pass 821 822This demonstrates how similar derived enumerations can be defined; for example 823a :class:`FloatEnum` that mixes in :class:`float` instead of :class:`int`. 824 825Some rules: 826 8271. When subclassing :class:`Enum`, mix-in types must appear before 828 :class:`Enum` itself in the sequence of bases, as in the :class:`IntEnum` 829 example above. 8302. Mix-in types must be subclassable. For example, :class:`bool` and 831 :class:`range` are not subclassable and will throw an error during Enum 832 creation if used as the mix-in type. 8333. While :class:`Enum` can have members of any type, once you mix in an 834 additional type, all the members must have values of that type, e.g. 835 :class:`int` above. This restriction does not apply to mix-ins which only 836 add methods and don't specify another type. 8374. When another data type is mixed in, the :attr:`value` attribute is *not the 838 same* as the enum member itself, although it is equivalent and will compare 839 equal. 8405. A ``data type`` is a mixin that defines :meth:`__new__`. 8416. %-style formatting: ``%s`` and ``%r`` call the :class:`Enum` class's 842 :meth:`__str__` and :meth:`__repr__` respectively; other codes (such as 843 ``%i`` or ``%h`` for IntEnum) treat the enum member as its mixed-in type. 8447. :ref:`Formatted string literals <f-strings>`, :meth:`str.format`, 845 and :func:`format` will use the enum's :meth:`__str__` method. 846 847.. note:: 848 849 Because :class:`IntEnum`, :class:`IntFlag`, and :class:`StrEnum` are 850 designed to be drop-in replacements for existing constants, their 851 :meth:`__str__` method has been reset to their data types' 852 :meth:`__str__` method. 853 854When to use :meth:`__new__` vs. :meth:`__init__` 855------------------------------------------------ 856 857:meth:`__new__` must be used whenever you want to customize the actual value of 858the :class:`Enum` member. Any other modifications may go in either 859:meth:`__new__` or :meth:`__init__`, with :meth:`__init__` being preferred. 860 861For example, if you want to pass several items to the constructor, but only 862want one of them to be the value:: 863 864 >>> class Coordinate(bytes, Enum): 865 ... """ 866 ... Coordinate with binary codes that can be indexed by the int code. 867 ... """ 868 ... def __new__(cls, value, label, unit): 869 ... obj = bytes.__new__(cls, [value]) 870 ... obj._value_ = value 871 ... obj.label = label 872 ... obj.unit = unit 873 ... return obj 874 ... PX = (0, 'P.X', 'km') 875 ... PY = (1, 'P.Y', 'km') 876 ... VX = (2, 'V.X', 'km/s') 877 ... VY = (3, 'V.Y', 'km/s') 878 ... 879 880 >>> print(Coordinate['PY']) 881 Coordinate.PY 882 883 >>> print(Coordinate(3)) 884 Coordinate.VY 885 886 887Finer Points 888^^^^^^^^^^^^ 889 890Supported ``__dunder__`` names 891"""""""""""""""""""""""""""""" 892 893:attr:`__members__` is a read-only ordered mapping of ``member_name``:``member`` 894items. It is only available on the class. 895 896:meth:`__new__`, if specified, must create and return the enum members; it is 897also a very good idea to set the member's :attr:`_value_` appropriately. Once 898all the members are created it is no longer used. 899 900 901Supported ``_sunder_`` names 902"""""""""""""""""""""""""""" 903 904- ``_name_`` -- name of the member 905- ``_value_`` -- value of the member; can be set / modified in ``__new__`` 906 907- ``_missing_`` -- a lookup function used when a value is not found; may be 908 overridden 909- ``_ignore_`` -- a list of names, either as a :class:`list` or a :class:`str`, 910 that will not be transformed into members, and will be removed from the final 911 class 912- ``_order_`` -- used in Python 2/3 code to ensure member order is consistent 913 (class attribute, removed during class creation) 914- ``_generate_next_value_`` -- used by the `Functional API`_ and by 915 :class:`auto` to get an appropriate value for an enum member; may be 916 overridden 917 918.. note:: 919 920 For standard :class:`Enum` classes the next value chosen is the last value seen 921 incremented by one. 922 923 For :class:`Flag` classes the next value chosen will be the next highest 924 power-of-two, regardless of the last value seen. 925 926.. versionadded:: 3.6 ``_missing_``, ``_order_``, ``_generate_next_value_`` 927.. versionadded:: 3.7 ``_ignore_`` 928 929To help keep Python 2 / Python 3 code in sync an :attr:`_order_` attribute can 930be provided. It will be checked against the actual order of the enumeration 931and raise an error if the two do not match:: 932 933 >>> class Color(Enum): 934 ... _order_ = 'RED GREEN BLUE' 935 ... RED = 1 936 ... BLUE = 3 937 ... GREEN = 2 938 ... 939 Traceback (most recent call last): 940 ... 941 TypeError: member order does not match _order_: 942 ['RED', 'BLUE', 'GREEN'] 943 ['RED', 'GREEN', 'BLUE'] 944 945.. note:: 946 947 In Python 2 code the :attr:`_order_` attribute is necessary as definition 948 order is lost before it can be recorded. 949 950 951_Private__names 952""""""""""""""" 953 954:ref:`Private names <private-name-mangling>` are not converted to enum members, 955but remain normal attributes. 956 957.. versionchanged:: 3.11 958 959 960``Enum`` member type 961"""""""""""""""""""" 962 963Enum members are instances of their enum class, and are normally accessed as 964``EnumClass.member``. In certain situations, such as writing custom enum 965behavior, being able to access one member directly from another is useful, 966and is supported. 967 968.. versionchanged:: 3.5 969 970 971Creating members that are mixed with other data types 972""""""""""""""""""""""""""""""""""""""""""""""""""""" 973 974When subclassing other data types, such as :class:`int` or :class:`str`, with 975an :class:`Enum`, all values after the ``=`` are passed to that data type's 976constructor. For example:: 977 978 >>> class MyEnum(IntEnum): # help(int) -> int(x, base=10) -> integer 979 ... example = '11', 16 # so x='11' and base=16 980 ... 981 >>> MyEnum.example.value # and hex(11) is... 982 17 983 984 985Boolean value of ``Enum`` classes and members 986""""""""""""""""""""""""""""""""""""""""""""" 987 988Enum classes that are mixed with non-:class:`Enum` types (such as 989:class:`int`, :class:`str`, etc.) are evaluated according to the mixed-in 990type's rules; otherwise, all members evaluate as :data:`True`. To make your 991own enum's boolean evaluation depend on the member's value add the following to 992your class:: 993 994 def __bool__(self): 995 return bool(self.value) 996 997Plain :class:`Enum` classes always evaluate as :data:`True`. 998 999 1000``Enum`` classes with methods 1001""""""""""""""""""""""""""""" 1002 1003If you give your enum subclass extra methods, like the `Planet`_ 1004class below, those methods will show up in a :func:`dir` of the member, 1005but not of the class:: 1006 1007 >>> dir(Planet) # doctest: +SKIP 1008 ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__'] 1009 >>> dir(Planet.EARTH) # doctest: +SKIP 1010 ['__class__', '__doc__', '__module__', 'mass', 'name', 'radius', 'surface_gravity', 'value'] 1011 1012 1013Combining members of ``Flag`` 1014""""""""""""""""""""""""""""" 1015 1016Iterating over a combination of :class:`Flag` members will only return the members that 1017are comprised of a single bit:: 1018 1019 >>> class Color(Flag): 1020 ... RED = auto() 1021 ... GREEN = auto() 1022 ... BLUE = auto() 1023 ... MAGENTA = RED | BLUE 1024 ... YELLOW = RED | GREEN 1025 ... CYAN = GREEN | BLUE 1026 ... 1027 >>> Color(3) # named combination 1028 <Color.YELLOW: 3> 1029 >>> Color(7) # not named combination 1030 <Color.RED|GREEN|BLUE: 7> 1031 1032 1033``Flag`` and ``IntFlag`` minutia 1034"""""""""""""""""""""""""""""""" 1035 1036Using the following snippet for our examples:: 1037 1038 >>> class Color(IntFlag): 1039 ... BLACK = 0 1040 ... RED = 1 1041 ... GREEN = 2 1042 ... BLUE = 4 1043 ... PURPLE = RED | BLUE 1044 ... WHITE = RED | GREEN | BLUE 1045 ... 1046 1047the following are true: 1048 1049- single-bit flags are canonical 1050- multi-bit and zero-bit flags are aliases 1051- only canonical flags are returned during iteration:: 1052 1053 >>> list(Color.WHITE) 1054 [<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 4>] 1055 1056- negating a flag or flag set returns a new flag/flag set with the 1057 corresponding positive integer value:: 1058 1059 >>> Color.BLUE 1060 <Color.BLUE: 4> 1061 1062 >>> ~Color.BLUE 1063 <Color.RED|GREEN: 3> 1064 1065- names of pseudo-flags are constructed from their members' names:: 1066 1067 >>> (Color.RED | Color.GREEN).name 1068 'RED|GREEN' 1069 1070- multi-bit flags, aka aliases, can be returned from operations:: 1071 1072 >>> Color.RED | Color.BLUE 1073 <Color.PURPLE: 5> 1074 1075 >>> Color(7) # or Color(-1) 1076 <Color.WHITE: 7> 1077 1078 >>> Color(0) 1079 <Color.BLACK: 0> 1080 1081- membership / containment checking: zero-valued flags are always considered 1082 to be contained:: 1083 1084 >>> Color.BLACK in Color.WHITE 1085 True 1086 1087 otherwise, only if all bits of one flag are in the other flag will True 1088 be returned:: 1089 1090 >>> Color.PURPLE in Color.WHITE 1091 True 1092 1093 >>> Color.GREEN in Color.PURPLE 1094 False 1095 1096There is a new boundary mechanism that controls how out-of-range / invalid 1097bits are handled: ``STRICT``, ``CONFORM``, ``EJECT``, and ``KEEP``: 1098 1099 * STRICT --> raises an exception when presented with invalid values 1100 * CONFORM --> discards any invalid bits 1101 * EJECT --> lose Flag status and become a normal int with the given value 1102 * KEEP --> keep the extra bits 1103 - keeps Flag status and extra bits 1104 - extra bits do not show up in iteration 1105 - extra bits do show up in repr() and str() 1106 1107The default for Flag is ``STRICT``, the default for ``IntFlag`` is ``EJECT``, 1108and the default for ``_convert_`` is ``KEEP`` (see ``ssl.Options`` for an 1109example of when ``KEEP`` is needed). 1110 1111 1112.. _enum-class-differences: 1113 1114How are Enums and Flags different? 1115---------------------------------- 1116 1117Enums have a custom metaclass that affects many aspects of both derived :class:`Enum` 1118classes and their instances (members). 1119 1120 1121Enum Classes 1122^^^^^^^^^^^^ 1123 1124The :class:`EnumType` metaclass is responsible for providing the 1125:meth:`__contains__`, :meth:`__dir__`, :meth:`__iter__` and other methods that 1126allow one to do things with an :class:`Enum` class that fail on a typical 1127class, such as ``list(Color)`` or ``some_enum_var in Color``. :class:`EnumType` is 1128responsible for ensuring that various other methods on the final :class:`Enum` 1129class are correct (such as :meth:`__new__`, :meth:`__getnewargs__`, 1130:meth:`__str__` and :meth:`__repr__`). 1131 1132Flag Classes 1133^^^^^^^^^^^^ 1134 1135Flags have an expanded view of aliasing: to be canonical, the value of a flag 1136needs to be a power-of-two value, and not a duplicate name. So, in addition to the 1137:class:`Enum` definition of alias, a flag with no value (a.k.a. ``0``) or with more than one 1138power-of-two value (e.g. ``3``) is considered an alias. 1139 1140Enum Members (aka instances) 1141^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1142 1143The most interesting thing about enum members is that they are singletons. 1144:class:`EnumType` creates them all while it is creating the enum class itself, 1145and then puts a custom :meth:`__new__` in place to ensure that no new ones are 1146ever instantiated by returning only the existing member instances. 1147 1148Flag Members 1149^^^^^^^^^^^^ 1150 1151Flag members can be iterated over just like the :class:`Flag` class, and only the 1152canonical members will be returned. For example:: 1153 1154 >>> list(Color) 1155 [<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 4>] 1156 1157(Note that ``BLACK``, ``PURPLE``, and ``WHITE`` do not show up.) 1158 1159Inverting a flag member returns the corresponding positive value, 1160rather than a negative value --- for example:: 1161 1162 >>> ~Color.RED 1163 <Color.GREEN|BLUE: 6> 1164 1165Flag members have a length corresponding to the number of power-of-two values 1166they contain. For example:: 1167 1168 >>> len(Color.PURPLE) 1169 2 1170 1171 1172.. _enum-cookbook: 1173 1174Enum Cookbook 1175------------- 1176 1177 1178While :class:`Enum`, :class:`IntEnum`, :class:`StrEnum`, :class:`Flag`, and 1179:class:`IntFlag` are expected to cover the majority of use-cases, they cannot 1180cover them all. Here are recipes for some different types of enumerations 1181that can be used directly, or as examples for creating one's own. 1182 1183 1184Omitting values 1185^^^^^^^^^^^^^^^ 1186 1187In many use-cases, one doesn't care what the actual value of an enumeration 1188is. There are several ways to define this type of simple enumeration: 1189 1190- use instances of :class:`auto` for the value 1191- use instances of :class:`object` as the value 1192- use a descriptive string as the value 1193- use a tuple as the value and a custom :meth:`__new__` to replace the 1194 tuple with an :class:`int` value 1195 1196Using any of these methods signifies to the user that these values are not 1197important, and also enables one to add, remove, or reorder members without 1198having to renumber the remaining members. 1199 1200 1201Using :class:`auto` 1202""""""""""""""""""" 1203 1204Using :class:`auto` would look like:: 1205 1206 >>> class Color(Enum): 1207 ... RED = auto() 1208 ... BLUE = auto() 1209 ... GREEN = auto() 1210 ... 1211 >>> Color.GREEN 1212 <Color.GREEN: 3> 1213 1214 1215Using :class:`object` 1216""""""""""""""""""""" 1217 1218Using :class:`object` would look like:: 1219 1220 >>> class Color(Enum): 1221 ... RED = object() 1222 ... GREEN = object() 1223 ... BLUE = object() 1224 ... 1225 >>> Color.GREEN # doctest: +SKIP 1226 <Color.GREEN: <object object at 0x...>> 1227 1228This is also a good example of why you might want to write your own 1229:meth:`__repr__`:: 1230 1231 >>> class Color(Enum): 1232 ... RED = object() 1233 ... GREEN = object() 1234 ... BLUE = object() 1235 ... def __repr__(self): 1236 ... return "<%s.%s>" % (self.__class__.__name__, self._name_) 1237 ... 1238 >>> Color.GREEN 1239 <Color.GREEN> 1240 1241 1242 1243Using a descriptive string 1244"""""""""""""""""""""""""" 1245 1246Using a string as the value would look like:: 1247 1248 >>> class Color(Enum): 1249 ... RED = 'stop' 1250 ... GREEN = 'go' 1251 ... BLUE = 'too fast!' 1252 ... 1253 >>> Color.GREEN 1254 <Color.GREEN: 'go'> 1255 1256 1257Using a custom :meth:`__new__` 1258"""""""""""""""""""""""""""""" 1259 1260Using an auto-numbering :meth:`__new__` would look like:: 1261 1262 >>> class AutoNumber(Enum): 1263 ... def __new__(cls): 1264 ... value = len(cls.__members__) + 1 1265 ... obj = object.__new__(cls) 1266 ... obj._value_ = value 1267 ... return obj 1268 ... 1269 >>> class Color(AutoNumber): 1270 ... RED = () 1271 ... GREEN = () 1272 ... BLUE = () 1273 ... 1274 >>> Color.GREEN 1275 <Color.GREEN: 2> 1276 1277To make a more general purpose ``AutoNumber``, add ``*args`` to the signature:: 1278 1279 >>> class AutoNumber(Enum): 1280 ... def __new__(cls, *args): # this is the only change from above 1281 ... value = len(cls.__members__) + 1 1282 ... obj = object.__new__(cls) 1283 ... obj._value_ = value 1284 ... return obj 1285 ... 1286 1287Then when you inherit from ``AutoNumber`` you can write your own ``__init__`` 1288to handle any extra arguments:: 1289 1290 >>> class Swatch(AutoNumber): 1291 ... def __init__(self, pantone='unknown'): 1292 ... self.pantone = pantone 1293 ... AUBURN = '3497' 1294 ... SEA_GREEN = '1246' 1295 ... BLEACHED_CORAL = () # New color, no Pantone code yet! 1296 ... 1297 >>> Swatch.SEA_GREEN 1298 <Swatch.SEA_GREEN: 2> 1299 >>> Swatch.SEA_GREEN.pantone 1300 '1246' 1301 >>> Swatch.BLEACHED_CORAL.pantone 1302 'unknown' 1303 1304.. note:: 1305 1306 The :meth:`__new__` method, if defined, is used during creation of the Enum 1307 members; it is then replaced by Enum's :meth:`__new__` which is used after 1308 class creation for lookup of existing members. 1309 1310 1311OrderedEnum 1312^^^^^^^^^^^ 1313 1314An ordered enumeration that is not based on :class:`IntEnum` and so maintains 1315the normal :class:`Enum` invariants (such as not being comparable to other 1316enumerations):: 1317 1318 >>> class OrderedEnum(Enum): 1319 ... def __ge__(self, other): 1320 ... if self.__class__ is other.__class__: 1321 ... return self.value >= other.value 1322 ... return NotImplemented 1323 ... def __gt__(self, other): 1324 ... if self.__class__ is other.__class__: 1325 ... return self.value > other.value 1326 ... return NotImplemented 1327 ... def __le__(self, other): 1328 ... if self.__class__ is other.__class__: 1329 ... return self.value <= other.value 1330 ... return NotImplemented 1331 ... def __lt__(self, other): 1332 ... if self.__class__ is other.__class__: 1333 ... return self.value < other.value 1334 ... return NotImplemented 1335 ... 1336 >>> class Grade(OrderedEnum): 1337 ... A = 5 1338 ... B = 4 1339 ... C = 3 1340 ... D = 2 1341 ... F = 1 1342 ... 1343 >>> Grade.C < Grade.A 1344 True 1345 1346 1347DuplicateFreeEnum 1348^^^^^^^^^^^^^^^^^ 1349 1350Raises an error if a duplicate member value is found instead of creating an 1351alias:: 1352 1353 >>> class DuplicateFreeEnum(Enum): 1354 ... def __init__(self, *args): 1355 ... cls = self.__class__ 1356 ... if any(self.value == e.value for e in cls): 1357 ... a = self.name 1358 ... e = cls(self.value).name 1359 ... raise ValueError( 1360 ... "aliases not allowed in DuplicateFreeEnum: %r --> %r" 1361 ... % (a, e)) 1362 ... 1363 >>> class Color(DuplicateFreeEnum): 1364 ... RED = 1 1365 ... GREEN = 2 1366 ... BLUE = 3 1367 ... GRENE = 2 1368 ... 1369 Traceback (most recent call last): 1370 ... 1371 ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN' 1372 1373.. note:: 1374 1375 This is a useful example for subclassing Enum to add or change other 1376 behaviors as well as disallowing aliases. If the only desired change is 1377 disallowing aliases, the :func:`unique` decorator can be used instead. 1378 1379 1380Planet 1381^^^^^^ 1382 1383If :meth:`__new__` or :meth:`__init__` is defined, the value of the enum member 1384will be passed to those methods:: 1385 1386 >>> class Planet(Enum): 1387 ... MERCURY = (3.303e+23, 2.4397e6) 1388 ... VENUS = (4.869e+24, 6.0518e6) 1389 ... EARTH = (5.976e+24, 6.37814e6) 1390 ... MARS = (6.421e+23, 3.3972e6) 1391 ... JUPITER = (1.9e+27, 7.1492e7) 1392 ... SATURN = (5.688e+26, 6.0268e7) 1393 ... URANUS = (8.686e+25, 2.5559e7) 1394 ... NEPTUNE = (1.024e+26, 2.4746e7) 1395 ... def __init__(self, mass, radius): 1396 ... self.mass = mass # in kilograms 1397 ... self.radius = radius # in meters 1398 ... @property 1399 ... def surface_gravity(self): 1400 ... # universal gravitational constant (m3 kg-1 s-2) 1401 ... G = 6.67300E-11 1402 ... return G * self.mass / (self.radius * self.radius) 1403 ... 1404 >>> Planet.EARTH.value 1405 (5.976e+24, 6378140.0) 1406 >>> Planet.EARTH.surface_gravity 1407 9.802652743337129 1408 1409.. _enum-time-period: 1410 1411TimePeriod 1412^^^^^^^^^^ 1413 1414An example to show the :attr:`_ignore_` attribute in use:: 1415 1416 >>> from datetime import timedelta 1417 >>> class Period(timedelta, Enum): 1418 ... "different lengths of time" 1419 ... _ignore_ = 'Period i' 1420 ... Period = vars() 1421 ... for i in range(367): 1422 ... Period['day_%d' % i] = i 1423 ... 1424 >>> list(Period)[:2] 1425 [<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>] 1426 >>> list(Period)[-2:] 1427 [<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>] 1428 1429 1430.. _enumtype-examples: 1431 1432Subclassing EnumType 1433-------------------- 1434 1435While most enum needs can be met by customizing :class:`Enum` subclasses, 1436either with class decorators or custom functions, :class:`EnumType` can be 1437subclassed to provide a different Enum experience. 1438