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