| 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 |
>>> import datetime as dt |
| 109 |
>>> Weekday.from_date(dt.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__`` and ``_sunder_`` names |
| 971 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 972 |
|
| 973 |
The supported ``__dunder__`` and ``_sunder_`` names can be found in the :ref:`Enum API documentation <enum-dunder-sunder>`. |
| 974 |
|
| 975 |
|
| 976 |
_Private__names |
| 977 |
^^^^^^^^^^^^^^^ |
| 978 |
|
| 979 |
:ref:`Private names <private-name-mangling>` are not converted to enum members, |
| 980 |
but remain normal attributes. |
| 981 |
|
| 982 |
.. versionchanged:: 3.11 |
| 983 |
|
| 984 |
|
| 985 |
``Enum`` member type |
| 986 |
^^^^^^^^^^^^^^^^^^^^ |
| 987 |
|
| 988 |
Enum members are instances of their enum class, and are normally accessed as |
| 989 |
``EnumClass.member``. In certain situations, such as writing custom enum |
| 990 |
behavior, being able to access one member directly from another is useful, |
| 991 |
and is supported; however, in order to avoid name clashes between member names |
| 992 |
and attributes/methods from mixed-in classes, upper-case names are strongly |
| 993 |
recommended. |
| 994 |
|
| 995 |
.. versionchanged:: 3.5 |
| 996 |
|
| 997 |
|
| 998 |
Creating members that are mixed with other data types |
| 999 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1000 |
|
| 1001 |
When subclassing other data types, such as :class:`int` or :class:`str`, with |
| 1002 |
an :class:`Enum`, all values after the ``=`` are passed to that data type's |
| 1003 |
constructor. For example:: |
| 1004 |
|
| 1005 |
>>> class MyEnum(IntEnum): # help(int) -> int(x, base=10) -> integer |
| 1006 |
... example = '11', 16 # so x='11' and base=16 |
| 1007 |
... |
| 1008 |
>>> MyEnum.example.value # and hex(11) is... |
| 1009 |
17 |
| 1010 |
|
| 1011 |
|
| 1012 |
Boolean value of ``Enum`` classes and members |
| 1013 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1014 |
|
| 1015 |
Enum classes that are mixed with non-:class:`Enum` types (such as |
| 1016 |
:class:`int`, :class:`str`, etc.) are evaluated according to the mixed-in |
| 1017 |
type's rules; otherwise, all members evaluate as :data:`True`. To make your |
| 1018 |
own enum's boolean evaluation depend on the member's value add the following to |
| 1019 |
your class:: |
| 1020 |
|
| 1021 |
def __bool__(self): |
| 1022 |
return bool(self.value) |
| 1023 |
|
| 1024 |
Plain :class:`Enum` classes always evaluate as :data:`True`. |
| 1025 |
|
| 1026 |
|
| 1027 |
``Enum`` classes with methods |
| 1028 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1029 |
|
| 1030 |
If you give your enum subclass extra methods, like the `Planet`_ |
| 1031 |
class below, those methods will show up in a :func:`dir` of the member, |
| 1032 |
but not of the class:: |
| 1033 |
|
| 1034 |
>>> dir(Planet) # doctest: +SKIP |
| 1035 |
['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__'] |
| 1036 |
>>> dir(Planet.EARTH) # doctest: +SKIP |
| 1037 |
['__class__', '__doc__', '__module__', 'mass', 'name', 'radius', 'surface_gravity', 'value'] |
| 1038 |
|
| 1039 |
|
| 1040 |
Combining members of ``Flag`` |
| 1041 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1042 |
|
| 1043 |
Iterating over a combination of :class:`Flag` members will only return the members that |
| 1044 |
are comprised of a single bit:: |
| 1045 |
|
| 1046 |
>>> class Color(Flag): |
| 1047 |
... RED = auto() |
| 1048 |
... GREEN = auto() |
| 1049 |
... BLUE = auto() |
| 1050 |
... MAGENTA = RED | BLUE |
| 1051 |
... YELLOW = RED | GREEN |
| 1052 |
... CYAN = GREEN | BLUE |
| 1053 |
... |
| 1054 |
>>> Color(3) # named combination |
| 1055 |
<Color.YELLOW: 3> |
| 1056 |
>>> Color(7) # not named combination |
| 1057 |
<Color.RED|GREEN|BLUE: 7> |
| 1058 |
|
| 1059 |
|
| 1060 |
``Flag`` and ``IntFlag`` minutia |
| 1061 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1062 |
|
| 1063 |
Using the following snippet for our examples:: |
| 1064 |
|
| 1065 |
>>> class Color(IntFlag): |
| 1066 |
... BLACK = 0 |
| 1067 |
... RED = 1 |
| 1068 |
... GREEN = 2 |
| 1069 |
... BLUE = 4 |
| 1070 |
... PURPLE = RED | BLUE |
| 1071 |
... WHITE = RED | GREEN | BLUE |
| 1072 |
... |
| 1073 |
|
| 1074 |
the following are true: |
| 1075 |
|
| 1076 |
- single-bit flags are canonical |
| 1077 |
- multi-bit and zero-bit flags are aliases |
| 1078 |
- only canonical flags are returned during iteration:: |
| 1079 |
|
| 1080 |
>>> list(Color.WHITE) |
| 1081 |
[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 4>] |
| 1082 |
|
| 1083 |
- negating a flag or flag set returns a new flag/flag set with the |
| 1084 |
corresponding positive integer value:: |
| 1085 |
|
| 1086 |
>>> Color.BLUE |
| 1087 |
<Color.BLUE: 4> |
| 1088 |
|
| 1089 |
>>> ~Color.BLUE |
| 1090 |
<Color.RED|GREEN: 3> |
| 1091 |
|
| 1092 |
- names of pseudo-flags are constructed from their members' names:: |
| 1093 |
|
| 1094 |
>>> (Color.RED | Color.GREEN).name |
| 1095 |
'RED|GREEN' |
| 1096 |
|
| 1097 |
>>> class Perm(IntFlag): |
| 1098 |
... R = 4 |
| 1099 |
... W = 2 |
| 1100 |
... X = 1 |
| 1101 |
... |
| 1102 |
>>> (Perm.R & Perm.W).name is None # effectively Perm(0) |
| 1103 |
True |
| 1104 |
|
| 1105 |
- multi-bit flags, aka aliases, can be returned from operations:: |
| 1106 |
|
| 1107 |
>>> Color.RED | Color.BLUE |
| 1108 |
<Color.PURPLE: 5> |
| 1109 |
|
| 1110 |
>>> Color(7) # or Color(-1) |
| 1111 |
<Color.WHITE: 7> |
| 1112 |
|
| 1113 |
>>> Color(0) |
| 1114 |
<Color.BLACK: 0> |
| 1115 |
|
| 1116 |
- membership / containment checking: zero-valued flags are always considered |
| 1117 |
to be contained:: |
| 1118 |
|
| 1119 |
>>> Color.BLACK in Color.WHITE |
| 1120 |
True |
| 1121 |
|
| 1122 |
otherwise, only if all bits of one flag are in the other flag will True |
| 1123 |
be returned:: |
| 1124 |
|
| 1125 |
>>> Color.PURPLE in Color.WHITE |
| 1126 |
True |
| 1127 |
|
| 1128 |
>>> Color.GREEN in Color.PURPLE |
| 1129 |
False |
| 1130 |
|
| 1131 |
There is a new boundary mechanism that controls how out-of-range / invalid |
| 1132 |
bits are handled: ``STRICT``, ``CONFORM``, ``EJECT``, and ``KEEP``: |
| 1133 |
|
| 1134 |
* STRICT --> raises an exception when presented with invalid values |
| 1135 |
* CONFORM --> discards any invalid bits |
| 1136 |
* EJECT --> lose Flag status and become a normal int with the given value |
| 1137 |
* KEEP --> keep the extra bits |
| 1138 |
|
| 1139 |
- keeps Flag status and extra bits |
| 1140 |
- extra bits do not show up in iteration |
| 1141 |
- extra bits do show up in repr() and str() |
| 1142 |
|
| 1143 |
The default for Flag is ``STRICT``, the default for ``IntFlag`` is ``EJECT``, |
| 1144 |
and the default for ``_convert_`` is ``KEEP`` (see ``ssl.Options`` for an |
| 1145 |
example of when ``KEEP`` is needed). |
| 1146 |
|
| 1147 |
|
| 1148 |
.. _enum-class-differences: |
| 1149 |
|
| 1150 |
How are Enums and Flags different? |
| 1151 |
---------------------------------- |
| 1152 |
|
| 1153 |
Enums have a custom metaclass that affects many aspects of both derived :class:`Enum` |
| 1154 |
classes and their instances (members). |
| 1155 |
|
| 1156 |
|
| 1157 |
Enum Classes |
| 1158 |
^^^^^^^^^^^^ |
| 1159 |
|
| 1160 |
The :class:`EnumType` metaclass is responsible for providing the |
| 1161 |
:meth:`~object.__contains__`, :meth:`~object.__dir__`, :meth:`~object.__iter__` and other methods that |
| 1162 |
allow one to do things with an :class:`Enum` class that fail on a typical |
| 1163 |
class, such as ``list(Color)`` or ``some_enum_var in Color``. :class:`EnumType` is |
| 1164 |
responsible for ensuring that various other methods on the final :class:`Enum` |
| 1165 |
class are correct (such as :meth:`~object.__new__`, :meth:`~object.__getnewargs__`, |
| 1166 |
:meth:`~object.__str__` and :meth:`~object.__repr__`). |
| 1167 |
|
| 1168 |
Flag Classes |
| 1169 |
^^^^^^^^^^^^ |
| 1170 |
|
| 1171 |
Flags have an expanded view of aliasing: to be canonical, the value of a flag |
| 1172 |
needs to be a power-of-two value, and not a duplicate name. So, in addition to the |
| 1173 |
:class:`Enum` definition of alias, a flag with no value (a.k.a. ``0``) or with more than one |
| 1174 |
power-of-two value (e.g. ``3``) is considered an alias. |
| 1175 |
|
| 1176 |
Enum Members (aka instances) |
| 1177 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1178 |
|
| 1179 |
The most interesting thing about enum members is that they are singletons. |
| 1180 |
:class:`EnumType` creates them all while it is creating the enum class itself, |
| 1181 |
and then puts a custom :meth:`~object.__new__` in place to ensure that no new ones are |
| 1182 |
ever instantiated by returning only the existing member instances. |
| 1183 |
|
| 1184 |
Flag Members |
| 1185 |
^^^^^^^^^^^^ |
| 1186 |
|
| 1187 |
Flag members can be iterated over just like the :class:`Flag` class, and only the |
| 1188 |
canonical members will be returned. For example:: |
| 1189 |
|
| 1190 |
>>> list(Color) |
| 1191 |
[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 4>] |
| 1192 |
|
| 1193 |
(Note that ``BLACK``, ``PURPLE``, and ``WHITE`` do not show up.) |
| 1194 |
|
| 1195 |
Inverting a flag member returns the corresponding positive value, |
| 1196 |
rather than a negative value --- for example:: |
| 1197 |
|
| 1198 |
>>> ~Color.RED |
| 1199 |
<Color.GREEN|BLUE: 6> |
| 1200 |
|
| 1201 |
Flag members have a length corresponding to the number of power-of-two values |
| 1202 |
they contain. For example:: |
| 1203 |
|
| 1204 |
>>> len(Color.PURPLE) |
| 1205 |
2 |
| 1206 |
|
| 1207 |
|
| 1208 |
.. _enum-cookbook: |
| 1209 |
|
| 1210 |
Enum Cookbook |
| 1211 |
------------- |
| 1212 |
|
| 1213 |
|
| 1214 |
While :class:`Enum`, :class:`IntEnum`, :class:`StrEnum`, :class:`Flag`, and |
| 1215 |
:class:`IntFlag` are expected to cover the majority of use-cases, they cannot |
| 1216 |
cover them all. Here are recipes for some different types of enumerations |
| 1217 |
that can be used directly, or as examples for creating one's own. |
| 1218 |
|
| 1219 |
|
| 1220 |
Omitting values |
| 1221 |
^^^^^^^^^^^^^^^ |
| 1222 |
|
| 1223 |
In many use-cases, one doesn't care what the actual value of an enumeration |
| 1224 |
is. There are several ways to define this type of simple enumeration: |
| 1225 |
|
| 1226 |
- use instances of :class:`auto` for the value |
| 1227 |
- use instances of :class:`object` as the value |
| 1228 |
- use a descriptive string as the value |
| 1229 |
- use a tuple as the value and a custom :meth:`~object.__new__` to replace the |
| 1230 |
tuple with an :class:`int` value |
| 1231 |
|
| 1232 |
Using any of these methods signifies to the user that these values are not |
| 1233 |
important, and also enables one to add, remove, or reorder members without |
| 1234 |
having to renumber the remaining members. |
| 1235 |
|
| 1236 |
|
| 1237 |
Using :class:`auto` |
| 1238 |
""""""""""""""""""" |
| 1239 |
|
| 1240 |
Using :class:`auto` would look like:: |
| 1241 |
|
| 1242 |
>>> class Color(Enum): |
| 1243 |
... RED = auto() |
| 1244 |
... BLUE = auto() |
| 1245 |
... GREEN = auto() |
| 1246 |
... |
| 1247 |
>>> Color.GREEN |
| 1248 |
<Color.GREEN: 3> |
| 1249 |
|
| 1250 |
|
| 1251 |
Using :class:`object` |
| 1252 |
""""""""""""""""""""" |
| 1253 |
|
| 1254 |
Using :class:`object` would look like:: |
| 1255 |
|
| 1256 |
>>> class Color(Enum): |
| 1257 |
... RED = object() |
| 1258 |
... GREEN = object() |
| 1259 |
... BLUE = object() |
| 1260 |
... |
| 1261 |
>>> Color.GREEN # doctest: +SKIP |
| 1262 |
<Color.GREEN: <object object at 0x...>> |
| 1263 |
|
| 1264 |
This is also a good example of why you might want to write your own |
| 1265 |
:meth:`~object.__repr__`:: |
| 1266 |
|
| 1267 |
>>> class Color(Enum): |
| 1268 |
... RED = object() |
| 1269 |
... GREEN = object() |
| 1270 |
... BLUE = object() |
| 1271 |
... def __repr__(self): |
| 1272 |
... return "<%s.%s>" % (self.__class__.__name__, self._name_) |
| 1273 |
... |
| 1274 |
>>> Color.GREEN |
| 1275 |
<Color.GREEN> |
| 1276 |
|
| 1277 |
|
| 1278 |
|
| 1279 |
Using a descriptive string |
| 1280 |
"""""""""""""""""""""""""" |
| 1281 |
|
| 1282 |
Using a string as the value would look like:: |
| 1283 |
|
| 1284 |
>>> class Color(Enum): |
| 1285 |
... RED = 'stop' |
| 1286 |
... GREEN = 'go' |
| 1287 |
... BLUE = 'too fast!' |
| 1288 |
... |
| 1289 |
>>> Color.GREEN |
| 1290 |
<Color.GREEN: 'go'> |
| 1291 |
|
| 1292 |
|
| 1293 |
Using a custom :meth:`~object.__new__` |
| 1294 |
"""""""""""""""""""""""""""""""""""""" |
| 1295 |
|
| 1296 |
Using an auto-numbering :meth:`~object.__new__` would look like:: |
| 1297 |
|
| 1298 |
>>> class AutoNumber(Enum): |
| 1299 |
... def __new__(cls): |
| 1300 |
... value = len(cls.__members__) + 1 |
| 1301 |
... obj = object.__new__(cls) |
| 1302 |
... obj._value_ = value |
| 1303 |
... return obj |
| 1304 |
... |
| 1305 |
>>> class Color(AutoNumber): |
| 1306 |
... RED = () |
| 1307 |
... GREEN = () |
| 1308 |
... BLUE = () |
| 1309 |
... |
| 1310 |
>>> Color.GREEN |
| 1311 |
<Color.GREEN: 2> |
| 1312 |
|
| 1313 |
To make a more general purpose ``AutoNumber``, add ``*args`` to the signature:: |
| 1314 |
|
| 1315 |
>>> class AutoNumber(Enum): |
| 1316 |
... def __new__(cls, *args): # this is the only change from above |
| 1317 |
... value = len(cls.__members__) + 1 |
| 1318 |
... obj = object.__new__(cls) |
| 1319 |
... obj._value_ = value |
| 1320 |
... return obj |
| 1321 |
... |
| 1322 |
|
| 1323 |
Then when you inherit from ``AutoNumber`` you can write your own ``__init__`` |
| 1324 |
to handle any extra arguments:: |
| 1325 |
|
| 1326 |
>>> class Swatch(AutoNumber): |
| 1327 |
... def __init__(self, pantone='unknown'): |
| 1328 |
... self.pantone = pantone |
| 1329 |
... AUBURN = '3497' |
| 1330 |
... SEA_GREEN = '1246' |
| 1331 |
... BLEACHED_CORAL = () # New color, no Pantone code yet! |
| 1332 |
... |
| 1333 |
>>> Swatch.SEA_GREEN |
| 1334 |
<Swatch.SEA_GREEN: 2> |
| 1335 |
>>> Swatch.SEA_GREEN.pantone |
| 1336 |
'1246' |
| 1337 |
>>> Swatch.BLEACHED_CORAL.pantone |
| 1338 |
'unknown' |
| 1339 |
|
| 1340 |
.. note:: |
| 1341 |
|
| 1342 |
The :meth:`~object.__new__` method, if defined, is used during creation of the Enum |
| 1343 |
members; it is then replaced by Enum's :meth:`~object.__new__` which is used after |
| 1344 |
class creation for lookup of existing members. |
| 1345 |
|
| 1346 |
.. warning:: |
| 1347 |
|
| 1348 |
*Do not* call ``super().__new__()``, as the lookup-only ``__new__`` is the one |
| 1349 |
that is found; instead, use the data type directly -- e.g.:: |
| 1350 |
|
| 1351 |
obj = int.__new__(cls, value) |
| 1352 |
|
| 1353 |
|
| 1354 |
OrderedEnum |
| 1355 |
^^^^^^^^^^^ |
| 1356 |
|
| 1357 |
An ordered enumeration that is not based on :class:`IntEnum` and so maintains |
| 1358 |
the normal :class:`Enum` invariants (such as not being comparable to other |
| 1359 |
enumerations):: |
| 1360 |
|
| 1361 |
>>> class OrderedEnum(Enum): |
| 1362 |
... def __ge__(self, other): |
| 1363 |
... if self.__class__ is other.__class__: |
| 1364 |
... return self.value >= other.value |
| 1365 |
... return NotImplemented |
| 1366 |
... def __gt__(self, other): |
| 1367 |
... if self.__class__ is other.__class__: |
| 1368 |
... return self.value > other.value |
| 1369 |
... return NotImplemented |
| 1370 |
... def __le__(self, other): |
| 1371 |
... if self.__class__ is other.__class__: |
| 1372 |
... return self.value <= other.value |
| 1373 |
... return NotImplemented |
| 1374 |
... def __lt__(self, other): |
| 1375 |
... if self.__class__ is other.__class__: |
| 1376 |
... return self.value < other.value |
| 1377 |
... return NotImplemented |
| 1378 |
... |
| 1379 |
>>> class Grade(OrderedEnum): |
| 1380 |
... A = 5 |
| 1381 |
... B = 4 |
| 1382 |
... C = 3 |
| 1383 |
... D = 2 |
| 1384 |
... F = 1 |
| 1385 |
... |
| 1386 |
>>> Grade.C < Grade.A |
| 1387 |
True |
| 1388 |
|
| 1389 |
|
| 1390 |
DuplicateFreeEnum |
| 1391 |
^^^^^^^^^^^^^^^^^ |
| 1392 |
|
| 1393 |
Raises an error if a duplicate member value is found instead of creating an |
| 1394 |
alias:: |
| 1395 |
|
| 1396 |
>>> class DuplicateFreeEnum(Enum): |
| 1397 |
... def __init__(self, *args): |
| 1398 |
... cls = self.__class__ |
| 1399 |
... if any(self.value == e.value for e in cls): |
| 1400 |
... a = self.name |
| 1401 |
... e = cls(self.value).name |
| 1402 |
... raise ValueError( |
| 1403 |
... "aliases not allowed in DuplicateFreeEnum: %r --> %r" |
| 1404 |
... % (a, e)) |
| 1405 |
... |
| 1406 |
>>> class Color(DuplicateFreeEnum): |
| 1407 |
... RED = 1 |
| 1408 |
... GREEN = 2 |
| 1409 |
... BLUE = 3 |
| 1410 |
... GRENE = 2 |
| 1411 |
... |
| 1412 |
Traceback (most recent call last): |
| 1413 |
... |
| 1414 |
ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN' |
| 1415 |
|
| 1416 |
.. note:: |
| 1417 |
|
| 1418 |
This is a useful example for subclassing Enum to add or change other |
| 1419 |
behaviors as well as disallowing aliases. If the only desired change is |
| 1420 |
disallowing aliases, the :func:`unique` decorator can be used instead. |
| 1421 |
|
| 1422 |
.. _multi-value-enum: |
| 1423 |
|
| 1424 |
MultiValueEnum |
| 1425 |
^^^^^^^^^^^^^^^^^ |
| 1426 |
|
| 1427 |
Supports having more than one value per member:: |
| 1428 |
|
| 1429 |
>>> class MultiValueEnum(Enum): |
| 1430 |
... def __new__(cls, value, *values): |
| 1431 |
... self = object.__new__(cls) |
| 1432 |
... self._value_ = value |
| 1433 |
... for v in values: |
| 1434 |
... self._add_value_alias_(v) |
| 1435 |
... return self |
| 1436 |
... |
| 1437 |
>>> class DType(MultiValueEnum): |
| 1438 |
... float32 = 'f', 8 |
| 1439 |
... double64 = 'd', 9 |
| 1440 |
... |
| 1441 |
>>> DType('f') |
| 1442 |
<DType.float32: 'f'> |
| 1443 |
>>> DType(9) |
| 1444 |
<DType.double64: 'd'> |
| 1445 |
|
| 1446 |
|
| 1447 |
Planet |
| 1448 |
^^^^^^ |
| 1449 |
|
| 1450 |
If :meth:`~object.__new__` or :meth:`~object.__init__` is defined, the value of the enum member |
| 1451 |
will be passed to those methods:: |
| 1452 |
|
| 1453 |
>>> class Planet(Enum): |
| 1454 |
... MERCURY = (3.303e+23, 2.4397e6) |
| 1455 |
... VENUS = (4.869e+24, 6.0518e6) |
| 1456 |
... EARTH = (5.976e+24, 6.37814e6) |
| 1457 |
... MARS = (6.421e+23, 3.3972e6) |
| 1458 |
... JUPITER = (1.9e+27, 7.1492e7) |
| 1459 |
... SATURN = (5.688e+26, 6.0268e7) |
| 1460 |
... URANUS = (8.686e+25, 2.5559e7) |
| 1461 |
... NEPTUNE = (1.024e+26, 2.4746e7) |
| 1462 |
... def __init__(self, mass, radius): |
| 1463 |
... self.mass = mass # in kilograms |
| 1464 |
... self.radius = radius # in meters |
| 1465 |
... @property |
| 1466 |
... def surface_gravity(self): |
| 1467 |
... # universal gravitational constant (m3 kg-1 s-2) |
| 1468 |
... G = 6.67300E-11 |
| 1469 |
... return G * self.mass / (self.radius * self.radius) |
| 1470 |
... |
| 1471 |
>>> Planet.EARTH.value |
| 1472 |
(5.976e+24, 6378140.0) |
| 1473 |
>>> Planet.EARTH.surface_gravity |
| 1474 |
9.802652743337129 |
| 1475 |
|
| 1476 |
.. _enum-time-period: |
| 1477 |
|
| 1478 |
TimePeriod |
| 1479 |
^^^^^^^^^^ |
| 1480 |
|
| 1481 |
An example to show the :attr:`~Enum._ignore_` attribute in use:: |
| 1482 |
|
| 1483 |
>>> import datetime as dt |
| 1484 |
>>> class Period(dt.timedelta, Enum): |
| 1485 |
... "different lengths of time" |
| 1486 |
... _ignore_ = 'Period i' |
| 1487 |
... Period = vars() |
| 1488 |
... for i in range(367): |
| 1489 |
... Period['day_%d' % i] = i |
| 1490 |
... |
| 1491 |
>>> list(Period)[:2] |
| 1492 |
[<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>] |
| 1493 |
>>> list(Period)[-2:] |
| 1494 |
[<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>] |
| 1495 |
|
| 1496 |
|
| 1497 |
.. _enumtype-examples: |
| 1498 |
|
| 1499 |
Subclassing EnumType |
| 1500 |
-------------------- |
| 1501 |
|
| 1502 |
While most enum needs can be met by customizing :class:`Enum` subclasses, |
| 1503 |
either with class decorators or custom functions, :class:`EnumType` can be |
| 1504 |
subclassed to provide a different Enum experience. |