Debian Codegraph @

Doc/howto/enum.rst

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