blob: 2d19ef6f25657bef1fa2cfed3590be9bf776bbd5 [file] [log] [blame]
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001:mod:`enum` --- Support for enumerations
2========================================
3
4.. module:: enum
Brett Cannon15e489f2013-06-14 21:59:16 -04005 :synopsis: Implementation of an enumeration class.
6
Andrés Delfino2d748382018-07-07 16:01:25 -03007.. moduleauthor:: Ethan Furman <ethan@stoneleaf.us>
8.. sectionauthor:: Barry Warsaw <barry@python.org>
9.. sectionauthor:: Eli Bendersky <eliben@gmail.com>
10.. sectionauthor:: Ethan Furman <ethan@stoneleaf.us>
Ethan Furman6b3d64a2013-06-14 16:55:46 -070011
R David Murrayfd1ff1c2013-12-20 14:20:49 -050012.. versionadded:: 3.4
13
Ethan Furman6b3d64a2013-06-14 16:55:46 -070014**Source code:** :source:`Lib/enum.py`
15
Ethan Furmanb7751062021-03-30 21:17:26 -070016.. sidebar:: Important
17
18 This page contains the API reference information. For tutorial
19 information and discussion of more advanced topics, see
20
21 * :ref:`Basic Tutorial <enum-basic-tutorial>`
22 * :ref:`Advanced Tutorial <enum-advanced-tutorial>`
23 * :ref:`Enum Cookbook <enum-cookbook>`
24
Ethan Furman6b3d64a2013-06-14 16:55:46 -070025----------------
26
Ethan Furmanb7751062021-03-30 21:17:26 -070027An enumeration:
Ethan Furmanc72e6382014-02-06 08:13:14 -080028
Ethan Furmanb7751062021-03-30 21:17:26 -070029* is a set of symbolic names (members) bound to unique values
30* can be iterated over to return its members in definition order
Ethan Furman74964862021-06-10 07:24:20 -070031* uses *call* syntax to return members by value
32* uses *index* syntax to return members by name
Ethan Furman542e1df2020-09-14 13:32:44 -070033
Ethan Furmanb7751062021-03-30 21:17:26 -070034Enumerations are created either by using the :keyword:`class` syntax, or by
35using function-call syntax::
36
37 >>> from enum import Enum
38
39 >>> # class syntax
40 >>> class Color(Enum):
41 ... RED = 1
42 ... GREEN = 2
43 ... BLUE = 3
44
45 >>> # functional syntax
46 >>> Color = Enum('Color', ['RED', 'GREEN', 'BLUE'])
47
48Even though we can use the :keyword:`class` syntax to create Enums, Enums
49are not normal Python classes. See
50:ref:`How are Enums different? <enum-class-differences>` for more details.
51
52.. note:: Nomenclature
53
54 - The class :class:`Color` is an *enumeration* (or *enum*)
55 - The attributes :attr:`Color.RED`, :attr:`Color.GREEN`, etc., are
56 *enumeration members* (or *enum members*) and are functionally constants.
57 - The enum members have *names* and *values* (the name of
58 :attr:`Color.RED` is ``RED``, the value of :attr:`Color.BLUE` is
59 ``3``, etc.)
Ethan Furman542e1df2020-09-14 13:32:44 -070060
Ethan Furmanc72e6382014-02-06 08:13:14 -080061
62Module Contents
63---------------
Ethan Furman6b3d64a2013-06-14 16:55:46 -070064
Ethan Furmanb7751062021-03-30 21:17:26 -070065 :class:`EnumType`
Ethan Furmanc72e6382014-02-06 08:13:14 -080066
Ethan Furmanb7751062021-03-30 21:17:26 -070067 The ``type`` for Enum and its subclasses.
Ethan Furmanc72e6382014-02-06 08:13:14 -080068
Ethan Furmanb7751062021-03-30 21:17:26 -070069 :class:`Enum`
Ethan Furmanc72e6382014-02-06 08:13:14 -080070
Ethan Furmanb7751062021-03-30 21:17:26 -070071 Base class for creating enumerated constants.
Ethan Furmanc72e6382014-02-06 08:13:14 -080072
Ethan Furmanb7751062021-03-30 21:17:26 -070073 :class:`IntEnum`
Ethan Furmanc72e6382014-02-06 08:13:14 -080074
Ethan Furmanb7751062021-03-30 21:17:26 -070075 Base class for creating enumerated constants that are also
76 subclasses of :class:`int`.
Ethan Furman0063ff42020-09-21 17:23:13 -070077
Ethan Furmanb7751062021-03-30 21:17:26 -070078 :class:`StrEnum`
Ethan Furman0063ff42020-09-21 17:23:13 -070079
Ethan Furmanb7751062021-03-30 21:17:26 -070080 Base class for creating enumerated constants that are also
81 subclasses of :class:`str`.
Ethan Furman65a5a472016-09-01 23:55:19 -070082
Ethan Furmanb7751062021-03-30 21:17:26 -070083 :class:`Flag`
Ethan Furman65a5a472016-09-01 23:55:19 -070084
Ethan Furmanb7751062021-03-30 21:17:26 -070085 Base class for creating enumerated constants that can be combined using
86 the bitwise operations without losing their :class:`Flag` membership.
Ethan Furman65a5a472016-09-01 23:55:19 -070087
Ethan Furmanb7751062021-03-30 21:17:26 -070088 :class:`IntFlag`
Ethan Furman65a5a472016-09-01 23:55:19 -070089
Ethan Furmanb7751062021-03-30 21:17:26 -070090 Base class for creating enumerated constants that can be combined using
91 the bitwise operators without losing their :class:`IntFlag` membership.
92 :class:`IntFlag` members are also subclasses of :class:`int`.
Ethan Furmanc72e6382014-02-06 08:13:14 -080093
Ethan Furman74964862021-06-10 07:24:20 -070094 :class:`EnumCheck`
95
96 An enumeration with the values ``CONTINUOUS``, ``NAMED_FLAGS``, and
97 ``UNIQUE``, for use with :func:`verify` to ensure various constraints
98 are met by a given enumeration.
99
Ethan Furmanb7751062021-03-30 21:17:26 -0700100 :class:`FlagBoundary`
Ethan Furmanf24bb352013-07-18 17:05:39 -0700101
Ethan Furmanb7751062021-03-30 21:17:26 -0700102 An enumeration with the values ``STRICT``, ``CONFORM``, ``EJECT``, and
103 ``KEEP`` which allows for more fine-grained control over how invalid values
104 are dealt with in an enumeration.
Ethan Furmanc16595e2016-09-10 23:36:59 -0700105
Ethan Furmanb7751062021-03-30 21:17:26 -0700106 :class:`auto`
107
108 Instances are replaced with an appropriate value for Enum members.
109 :class:`StrEnum` defaults to the lower-cased version of the member name,
110 while other Enums default to 1 and increase from there.
111
112 :func:`global_enum`
113
114 :class:`Enum` class decorator to apply the appropriate global `__repr__`,
115 and export its members into the global name space.
116
Miss Islington (bot)377f3d42021-05-04 06:24:46 -0700117 :func:`.property`
Ethan Furmanb7751062021-03-30 21:17:26 -0700118
119 Allows :class:`Enum` members to have attributes without conflicting with
120 other members' names.
121
122 :func:`unique`
123
124 Enum class decorator that ensures only one name is bound to any one value.
125
Ethan Furman74964862021-06-10 07:24:20 -0700126 :func:`verify`
127
128 Enum class decorator that checks user-selectable constraints on an
129 enumeration.
130
Ethan Furmanc16595e2016-09-10 23:36:59 -0700131
132.. versionadded:: 3.6 ``Flag``, ``IntFlag``, ``auto``
Ethan Furman74964862021-06-10 07:24:20 -0700133.. versionadded:: 3.10 ``StrEnum``, ``EnumCheck``, ``FlagBoundary``
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700134
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700135
Ethan Furmanb7751062021-03-30 21:17:26 -0700136Data Types
137----------
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700138
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700139
Ethan Furmanb7751062021-03-30 21:17:26 -0700140.. class:: EnumType
Ethan Furmanc16595e2016-09-10 23:36:59 -0700141
Ethan Furmanb7751062021-03-30 21:17:26 -0700142 *EnumType* is the :term:`metaclass` for *enum* enumerations. It is possible
143 to subclass *EnumType* -- see :ref:`Subclassing EnumType <enumtype-examples>`
144 for details.
Ethan Furmanc16595e2016-09-10 23:36:59 -0700145
Ethan Furmanb7751062021-03-30 21:17:26 -0700146 .. method:: EnumType.__contains__(cls, member)
Ethan Furman455bfde2013-09-08 23:48:34 -0700147
Ethan Furmanb7751062021-03-30 21:17:26 -0700148 Returns ``True`` if member belongs to the ``cls``::
149
150 >>> some_var = Color.RED
151 >>> some_var in Color
152 True
153
Ethan Furman6bd92882021-04-27 13:05:08 -0700154 .. note::
155
156 In Python 3.12 it will be possible to check for member values and not
157 just members; until then, a ``TypeError`` will be raised if a
158 non-Enum-member is used in a containment check.
159
Ethan Furmanb7751062021-03-30 21:17:26 -0700160 .. method:: EnumType.__dir__(cls)
161
162 Returns ``['__class__', '__doc__', '__members__', '__module__']`` and the
163 names of the members in *cls*::
164
165 >>> dir(Color)
166 ['BLUE', 'GREEN', 'RED', '__class__', '__doc__', '__members__', '__module__']
167
168 .. method:: EnumType.__getattr__(cls, name)
169
170 Returns the Enum member in *cls* matching *name*, or raises an :exc:`AttributeError`::
171
172 >>> Color.GREEN
173 Color.GREEN
174
175 .. method:: EnumType.__getitem__(cls, name)
176
177 Returns the Enum member in *cls* matching *name*, or raises an :exc:`KeyError`::
178
179 >>> Color['BLUE']
180 Color.BLUE
181
182 .. method:: EnumType.__iter__(cls)
183
184 Returns each member in *cls* in definition order::
185
186 >>> list(Color)
187 [Color.RED, Color.GREEN, Color.BLUE]
188
189 .. method:: EnumType.__len__(cls)
190
191 Returns the number of member in *cls*::
192
193 >>> len(Color)
194 3
195
196 .. method:: EnumType.__reversed__(cls)
197
198 Returns each member in *cls* in reverse definition order::
199
200 >>> list(reversed(Color))
201 [Color.BLUE, Color.GREEN, Color.RED]
202
203
204.. class:: Enum
205
206 *Enum* is the base class for all *enum* enumerations.
207
208 .. attribute:: Enum.name
209
210 The name used to define the ``Enum`` member::
211
212 >>> Color.BLUE.name
213 'BLUE'
214
215 .. attribute:: Enum.value
216
217 The value given to the ``Enum`` member::
218
219 >>> Color.RED.value
220 1
221
222 .. note:: Enum member values
223
224 Member values can be anything: :class:`int`, :class:`str`, etc.. If
225 the exact value is unimportant you may use :class:`auto` instances and an
226 appropriate value will be chosen for you. Care must be taken if you mix
227 :class:`auto` with other values.
228
229 .. attribute:: Enum._ignore_
230
231 ``_ignore_`` is only used during creation and is removed from the
232 enumeration once that is complete.
233
234 ``_ignore_`` is a list of names that will not become members, and whose
235 names will also be removed from the completed enumeration. See
236 :ref:`TimePeriod <enum-time-period>` for an example.
237
238 .. method:: Enum.__call__(cls, value, names=None, \*, module=None, qualname=None, type=None, start=1, boundary=None)
239
240 This method is called in two different ways:
241
242 * to look up an existing member:
243
244 :cls: The enum class being called.
245 :value: The value to lookup.
246
247 * to use the ``cls`` enum to create a new enum:
248
249 :cls: The enum class being called.
250 :value: The name of the new Enum to create.
251 :names: The names/values of the members for the new Enum.
252 :module: The name of the module the new Enum is created in.
253 :qualname: The actual location in the module where this Enum can be found.
254 :type: A mix-in type for the new Enum.
255 :start: The first integer value for the Enum (used by :class:`auto`)
256 :boundary: How to handle out-of-range values from bit operations (:class:`Flag` only)
257
258 .. method:: Enum.__dir__(self)
259
260 Returns ``['__class__', '__doc__', '__module__', 'name', 'value']`` and
261 any public methods defined on *self.__class__*::
262
263 >>> from datetime import date
264 >>> class Weekday(Enum):
265 ... MONDAY = 1
266 ... TUESDAY = 2
267 ... WEDNESDAY = 3
268 ... THURSDAY = 4
269 ... FRIDAY = 5
270 ... SATURDAY = 6
271 ... SUNDAY = 7
272 ... @classmethod
273 ... def today(cls):
274 ... print('today is %s' % cls(date.today.isoweekday).naem)
275 >>> dir(Weekday.SATURDAY)
276 ['__class__', '__doc__', '__module__', 'name', 'today', 'value']
277
278 .. method:: Enum._generate_next_value_(name, start, count, last_values)
279
280 :name: The name of the member being defined (e.g. 'RED').
281 :start: The start value for the Enum; the default is 1.
282 :count: The number of members currently defined, not including this one.
283 :last_values: A list of the previous values.
284
285 A *staticmethod* that is used to determine the next value returned by
286 :class:`auto`::
287
288 >>> from enum import auto
289 >>> class PowersOfThree(Enum):
290 ... @staticmethod
291 ... def _generate_next_value_(name, start, count, last_values):
292 ... return (count + 1) * 3
293 ... FIRST = auto()
294 ... SECOND = auto()
295 >>> PowersOfThree.SECOND.value
296 6
297
298 .. method:: Enum._missing_(cls, value)
299
300 A *classmethod* for looking up values not found in *cls*. By default it
301 does nothing, but can be overridden to implement custom search behavior::
302
303 >>> from enum import StrEnum
304 >>> class Build(StrEnum):
305 ... DEBUG = auto()
306 ... OPTIMIZED = auto()
307 ... @classmethod
308 ... def _missing_(cls, value):
309 ... value = value.lower()
310 ... for member in cls:
311 ... if member.value == value:
312 ... return member
313 ... return None
314 >>> Build.DEBUG.value
315 'debug'
316 >>> Build('deBUG')
317 Build.DEBUG
318
319 .. method:: Enum.__repr__(self)
320
321 Returns the string used for *repr()* calls. By default, returns the
322 *Enum* name and the member name, but can be overridden::
323
324 >>> class OldStyle(Enum):
325 ... RETRO = auto()
326 ... OLD_SCHOOl = auto()
327 ... YESTERYEAR = auto()
328 ... def __repr__(self):
329 ... cls_name = self.__class__.__name__
330 ... return f'<{cls_name}.{self.name}: {self.value}>'
331 >>> OldStyle.RETRO
332 <OldStyle.RETRO: 1>
333
334 .. method:: Enum.__str__(self)
335
336 Returns the string used for *str()* calls. By default, returns the
337 member name, but can be overridden::
338
339 >>> class OldStyle(Enum):
340 ... RETRO = auto()
341 ... OLD_SCHOOl = auto()
342 ... YESTERYEAR = auto()
343 ... def __str__(self):
344 ... cls_name = self.__class__.__name__
345 ... return f'{cls_name}.{self.name}'
346 >>> OldStyle.RETRO
347 OldStyle.RETRO
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700348
Ethan Furman9a1daf52013-09-27 22:58:06 -0700349.. note::
350
Ethan Furmanb7751062021-03-30 21:17:26 -0700351 Using :class:`auto` with :class:`Enum` results in integers of increasing value,
352 starting with ``1``.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700353
354
Ethan Furmanb7751062021-03-30 21:17:26 -0700355.. class:: IntEnum
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700356
Ethan Furmanb7751062021-03-30 21:17:26 -0700357 *IntEnum* is the same as *Enum*, but its members are also integers and can be
358 used anywhere that an integer can be used. If any integer operation is performed
359 with an *IntEnum* member, the resulting value loses its enumeration status.
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700360
Ethan Furmanb7751062021-03-30 21:17:26 -0700361 >>> from enum import IntEnum
362 >>> class Numbers(IntEnum):
363 ... ONE = 1
364 ... TWO = 2
365 ... THREE = 3
366 >>> Numbers.THREE
367 Numbers.THREE
368 >>> Numbers.ONE + Numbers.TWO
369 3
370 >>> Numbers.THREE + 5
371 8
372 >>> Numbers.THREE == 3
373 True
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700374
Ethan Furman101e0742013-09-15 12:34:36 -0700375.. note::
376
Ethan Furmanb7751062021-03-30 21:17:26 -0700377 Using :class:`auto` with :class:`IntEnum` results in integers of increasing value,
378 starting with ``1``.
Ethan Furman101e0742013-09-15 12:34:36 -0700379
Ethan Furmanf24bb352013-07-18 17:05:39 -0700380
Ethan Furmanb7751062021-03-30 21:17:26 -0700381.. class:: StrEnum
Ethan Furmanf24bb352013-07-18 17:05:39 -0700382
Ethan Furmanb7751062021-03-30 21:17:26 -0700383 *StrEnum* is the same as *Enum*, but its members are also strings and can be used
384 in most of the same places that a string can be used. The result of any string
385 operation performed on or with a *StrEnum* member is not part of the enumeration.
386
387 .. note:: There are places in the stdlib that check for an exact :class:`str`
388 instead of a :class:`str` subclass (i.e. ``type(unknown) == str``
389 instead of ``isinstance(str, unknown)``), and in those locations you
390 will need to use ``str(StrEnum.member)``.
391
392
393.. note::
394
395 Using :class:`auto` with :class:`StrEnum` results in values of the member name,
396 lower-cased.
397
398
399.. class:: Flag
400
401 *Flag* members support the bitwise operators ``&`` (*AND*), ``|`` (*OR*),
402 ``^`` (*XOR*), and ``~`` (*INVERT*); the results of those operators are members
403 of the enumeration.
404
405 .. method:: __contains__(self, value)
406
407 Returns *True* if value is in self::
408
409 >>> from enum import Flag, auto
410 >>> class Color(Flag):
411 ... RED = auto()
412 ... GREEN = auto()
413 ... BLUE = auto()
414 >>> purple = Color.RED | Color.BLUE
415 >>> white = Color.RED | Color.GREEN | Color.BLUE
416 >>> Color.GREEN in purple
417 False
418 >>> Color.GREEN in white
419 True
420 >>> purple in white
421 True
422 >>> white in purple
423 False
424
425 .. method:: __iter__(self):
426
427 Returns all contained members::
428
429 >>> list(Color.RED)
430 [Color.RED]
431 >>> list(purple)
432 [Color.RED, Color.BLUE]
433
434 .. method:: __len__(self):
435
436 Returns number of members in flag::
437
438 >>> len(Color.GREEN)
439 1
440 >>> len(white)
441 3
442
443 .. method:: __bool__(self):
444
445 Returns *True* if any members in flag, *False* otherwise::
446
447 >>> bool(Color.GREEN)
448 True
449 >>> bool(white)
450 True
451 >>> black = Color(0)
452 >>> bool(black)
453 False
454
455 .. method:: __or__(self, other)
456
457 Returns current flag binary or'ed with other::
458
459 >>> Color.RED | Color.GREEN
460 Color.RED|Color.GREEN
461
462 .. method:: __and__(self, other)
463
464 Returns current flag binary and'ed with other::
465
466 >>> purple & white
467 Color.RED|Color.BLUE
468 >>> purple & Color.GREEN
469 0x0
470
471 .. method:: __xor__(self, other)
472
473 Returns current flag binary xor'ed with other::
474
475 >>> purple ^ white
476 Color.GREEN
477 >>> purple ^ Color.GREEN
478 Color.RED|Color.GREEN|Color.BLUE
479
480 .. method:: __invert__(self):
481
482 Returns all the flags in *type(self)* that are not in self::
483
484 >>> ~white
485 0x0
486 >>> ~purple
487 Color.GREEN
488 >>> ~Color.RED
489 Color.GREEN|Color.BLUE
490
491.. note::
492
493 Using :class:`auto` with :class:`Flag` results in integers that are powers
494 of two, starting with ``1``.
495
496
497.. class:: IntFlag
498
499 *IntFlag* is the same as *Flag*, but its members are also integers and can be
500 used anywhere that an integer can be used.
501
502 >>> from enum import IntFlag, auto
503 >>> class Color(IntFlag):
504 ... RED = auto()
505 ... GREEN = auto()
506 ... BLUE = auto()
507 >>> Color.RED & 2
508 0x0
509 >>> Color.RED | 2
510 Color.RED|Color.GREEN
511
512 If any integer operation is performed with an *IntFlag* member, the result is
513 not an *IntFlag*::
514
515 >>> Color.RED + 2
516 3
517
518 If a *Flag* operation is performed with an *IntFlag* member and:
519
520 * the result is a valid *IntFlag*: an *IntFlag* is returned
521 * the result is not a valid *IntFlag*: the result depends on the *FlagBoundary* setting
522
523.. note::
524
525 Using :class:`auto` with :class:`IntFlag` results in integers that are powers
526 of two, starting with ``1``.
527
Ethan Furman74964862021-06-10 07:24:20 -0700528.. class:: EnumCheck
529
530 *EnumCheck* contains the options used by the :func:`verify` decorator to ensure
531 various constraints; failed constraints result in a :exc:`TypeError`.
532
533 .. attribute:: UNIQUE
534
535 Ensure that each value has only one name::
536
537 >>> from enum import Enum, verify, UNIQUE
538 >>> @verify(UNIQUE)
539 ... class Color(Enum):
540 ... RED = 1
541 ... GREEN = 2
542 ... BLUE = 3
543 ... CRIMSON = 1
544 Traceback (most recent call last):
545 ...
546 ValueError: aliases found in <enum 'Color'>: CRIMSON -> RED
547
548
549 .. attribute:: CONTINUOUS
550
551 Ensure that there are no missing values between the lowest-valued member
552 and the highest-valued member::
553
554 >>> from enum import Enum, verify, CONTINUOUS
555 >>> @verify(CONTINUOUS)
556 ... class Color(Enum):
557 ... RED = 1
558 ... GREEN = 2
559 ... BLUE = 5
560 Traceback (most recent call last):
561 ...
562 ValueError: invalid enum 'Color': missing values 3, 4
563
564 .. attribute:: NAMED_FLAGS
565
566 Ensure that any flag groups/masks contain only named flags -- useful when
567 values are specified instead of being generated by :func:`auto`
568
569 >>> from enum import Flag, verify, NAMED_FLAGS
570 >>> @verify(NAMED_FLAGS)
571 ... class Color(Flag):
572 ... RED = 1
573 ... GREEN = 2
574 ... BLUE = 4
575 ... WHITE = 15
576 ... NEON = 31
577 Traceback (most recent call last):
578 ...
579 ValueError: invalid Flag 'Color': 'WHITE' is missing a named flag for value 8; 'NEON' is missing named flags for values 8, 16
580
581.. note::
582
583 CONTINUOUS and NAMED_FLAGS are designed to work with integer-valued members.
584
585.. versionadded:: 3.10
586
Ethan Furmanb7751062021-03-30 21:17:26 -0700587.. class:: FlagBoundary
588
589 *FlagBoundary* controls how out-of-range values are handled in *Flag* and its
590 subclasses.
591
592 .. attribute:: STRICT
593
594 Out-of-range values cause a :exc:`ValueError` to be raised. This is the
595 default for :class:`Flag`::
596
Ethan Furman49aec1a2021-03-31 09:20:08 -0700597 >>> from enum import Flag, STRICT
Ethan Furmanb7751062021-03-30 21:17:26 -0700598 >>> class StrictFlag(Flag, boundary=STRICT):
599 ... RED = auto()
600 ... GREEN = auto()
601 ... BLUE = auto()
602 >>> StrictFlag(2**2 + 2**4)
603 Traceback (most recent call last):
604 ...
605 ValueError: StrictFlag: invalid value: 20
606 given 0b0 10100
607 allowed 0b0 00111
608
609 .. attribute:: CONFORM
610
611 Out-of-range values have invalid values removed, leaving a valid *Flag*
612 value::
613
Ethan Furman49aec1a2021-03-31 09:20:08 -0700614 >>> from enum import Flag, CONFORM
Ethan Furmanb7751062021-03-30 21:17:26 -0700615 >>> class ConformFlag(Flag, boundary=CONFORM):
616 ... RED = auto()
617 ... GREEN = auto()
618 ... BLUE = auto()
619 >>> ConformFlag(2**2 + 2**4)
620 ConformFlag.BLUE
621
622 .. attribute:: EJECT
623
624 Out-of-range values lose their *Flag* membership and revert to :class:`int`.
625 This is the default for :class:`IntFlag`::
626
Ethan Furman49aec1a2021-03-31 09:20:08 -0700627 >>> from enum import Flag, EJECT
Ethan Furmanb7751062021-03-30 21:17:26 -0700628 >>> class EjectFlag(Flag, boundary=EJECT):
629 ... RED = auto()
630 ... GREEN = auto()
631 ... BLUE = auto()
632 >>> EjectFlag(2**2 + 2**4)
633 20
634
635 .. attribute:: KEEP
636
637 Out-of-range values are kept, and the *Flag* membership is kept. This is
638 used for some stdlib flags:
639
Ethan Furman49aec1a2021-03-31 09:20:08 -0700640 >>> from enum import Flag, KEEP
Ethan Furmanb7751062021-03-30 21:17:26 -0700641 >>> class KeepFlag(Flag, boundary=KEEP):
642 ... RED = auto()
643 ... GREEN = auto()
644 ... BLUE = auto()
645 >>> KeepFlag(2**2 + 2**4)
646 KeepFlag.BLUE|0x10
647
Ethan Furman74964862021-06-10 07:24:20 -0700648.. versionadded:: 3.10
Ethan Furmanb7751062021-03-30 21:17:26 -0700649
650Utilites and Decorators
651-----------------------
652
653.. class:: auto
654
655 *auto* can be used in place of a value. If used, the *Enum* machinery will
656 call an *Enum*'s :meth:`_generate_next_value_` to get an appropriate value.
657 For *Enum* and *IntEnum* that appropriate value will be the last value plus
658 one; for *Flag* and *IntFlag* it will be the first power-of-two greater
659 than the last value; for *StrEnum* it will be the lower-cased version of the
660 member's name.
661
662 ``_generate_next_value_`` can be overridden to customize the values used by
663 *auto*.
664
665.. decorator:: global_enum
666
667 A :keyword:`class` decorator specifically for enumerations. It replaces the
668 :meth:`__repr__` method with one that shows *module_name*.*member_name*. It
Miss Islington (bot)37da1f02021-05-22 13:55:17 -0700669 also injects the members, and their aliases, into the global namespace they
670 were defined in.
Ethan Furmanb7751062021-03-30 21:17:26 -0700671
672
673.. decorator:: property
674
675 A decorator similar to the built-in *property*, but specifically for
676 enumerations. It allows member attributes to have the same names as members
677 themselves.
678
679 .. note:: the *property* and the member must be defined in separate classes;
680 for example, the *value* and *name* attributes are defined in the
681 *Enum* class, and *Enum* subclasses can define members with the
682 names ``value`` and ``name``.
Ethan Furmanf24bb352013-07-18 17:05:39 -0700683
684.. decorator:: unique
685
Ethan Furmanb7751062021-03-30 21:17:26 -0700686 A :keyword:`class` decorator specifically for enumerations. It searches an
687 enumeration's :attr:`__members__`, gathering any aliases it finds; if any are
688 found :exc:`ValueError` is raised with the details::
Ethan Furmanf24bb352013-07-18 17:05:39 -0700689
Ethan Furmanb7751062021-03-30 21:17:26 -0700690 >>> from enum import Enum, unique
691 >>> @unique
692 ... class Mistake(Enum):
693 ... ONE = 1
694 ... TWO = 2
695 ... THREE = 3
696 ... FOUR = 3
697 ...
698 Traceback (most recent call last):
699 ...
700 ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
Ethan Furman74964862021-06-10 07:24:20 -0700701
702.. decorator:: verify
703
704 A :keyword:`class` decorator specifically for enumerations. Members from
705 :class:`EnumCheck` are used to specify which constraints should be checked
706 on the decorated enumeration.
707
708.. versionadded:: 3.10