Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 1 | :mod:`enum` --- Support for enumerations |
| 2 | ======================================== |
| 3 | |
| 4 | .. module:: enum |
Brett Cannon | 15e489f | 2013-06-14 21:59:16 -0400 | [diff] [blame] | 5 | :synopsis: Implementation of an enumeration class. |
| 6 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 7 | .. :moduleauthor:: Ethan Furman <ethan@stoneleaf.us> |
| 8 | .. :sectionauthor:: Barry Warsaw <barry@python.org>, |
| 9 | .. :sectionauthor:: Eli Bendersky <eliben@gmail.com>, |
| 10 | .. :sectionauthor:: Ethan Furman <ethan@stoneleaf.us> |
| 11 | |
| 12 | **Source code:** :source:`Lib/enum.py` |
| 13 | |
| 14 | ---------------- |
| 15 | |
| 16 | An enumeration is a set of symbolic names (members) bound to unique, constant |
| 17 | values. Within an enumeration, the members can be compared by identity, and |
| 18 | the enumeration itself can be iterated over. |
| 19 | |
| 20 | This module defines two enumeration classes that can be used to define unique |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 21 | sets of names and values: :class:`Enum` and :class:`IntEnum`. It also defines |
| 22 | one decorator, :func:`unique`, that ensures only unique member values are |
| 23 | present in an enumeration. |
| 24 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 25 | |
| 26 | Creating an Enum |
| 27 | ---------------- |
| 28 | |
| 29 | Enumerations are created using the :keyword:`class` syntax, which makes them |
| 30 | easy to read and write. An alternative creation method is described in |
| 31 | `Functional API`_. To define an enumeration, subclass :class:`Enum` as |
| 32 | follows:: |
| 33 | |
| 34 | >>> from enum import Enum |
| 35 | >>> class Color(Enum): |
| 36 | ... red = 1 |
| 37 | ... green = 2 |
| 38 | ... blue = 3 |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 39 | ... |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 40 | |
Ethan Furman | 455bfde | 2013-09-08 23:48:34 -0700 | [diff] [blame] | 41 | .. note:: Nomenclature |
| 42 | |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 43 | - The class :class:`Color` is an *enumeration* (or *enum*) |
| 44 | - The attributes :attr:`Color.red`, :attr:`Color.green`, etc., are |
| 45 | *enumeration members* (or *enum members*). |
| 46 | - The enum members have *names* and *values* (the name of |
| 47 | :attr:`Color.red` is ``red``, the value of :attr:`Color.blue` is |
| 48 | ``3``, etc.) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 49 | |
Ethan Furman | 9a1daf5 | 2013-09-27 22:58:06 -0700 | [diff] [blame] | 50 | .. note:: |
| 51 | |
| 52 | Even though we use the :keyword:`class` syntax to create Enums, Enums |
| 53 | are not normal Python classes. See `How are Enums different?`_ for |
| 54 | more details. |
| 55 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 56 | Enumeration members have human readable string representations:: |
| 57 | |
| 58 | >>> print(Color.red) |
| 59 | Color.red |
| 60 | |
| 61 | ...while their ``repr`` has more information:: |
| 62 | |
| 63 | >>> print(repr(Color.red)) |
| 64 | <Color.red: 1> |
| 65 | |
| 66 | The *type* of an enumeration member is the enumeration it belongs to:: |
| 67 | |
| 68 | >>> type(Color.red) |
| 69 | <enum 'Color'> |
| 70 | >>> isinstance(Color.green, Color) |
| 71 | True |
| 72 | >>> |
| 73 | |
| 74 | Enum members also have a property that contains just their item name:: |
| 75 | |
| 76 | >>> print(Color.red.name) |
| 77 | red |
| 78 | |
| 79 | Enumerations support iteration, in definition order:: |
| 80 | |
| 81 | >>> class Shake(Enum): |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 82 | ... vanilla = 7 |
| 83 | ... chocolate = 4 |
| 84 | ... cookies = 9 |
| 85 | ... mint = 3 |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 86 | ... |
| 87 | >>> for shake in Shake: |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 88 | ... print(shake) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 89 | ... |
| 90 | Shake.vanilla |
| 91 | Shake.chocolate |
| 92 | Shake.cookies |
| 93 | Shake.mint |
| 94 | |
| 95 | Enumeration members are hashable, so they can be used in dictionaries and sets:: |
| 96 | |
| 97 | >>> apples = {} |
| 98 | >>> apples[Color.red] = 'red delicious' |
| 99 | >>> apples[Color.green] = 'granny smith' |
| 100 | >>> apples == {Color.red: 'red delicious', Color.green: 'granny smith'} |
| 101 | True |
| 102 | |
| 103 | |
Ethan Furman | 3fe70b4a | 2013-06-28 14:02:34 -0700 | [diff] [blame] | 104 | Programmatic access to enumeration members and their attributes |
| 105 | --------------------------------------------------------------- |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 106 | |
| 107 | Sometimes it's useful to access members in enumerations programmatically (i.e. |
| 108 | situations where ``Color.red`` won't do because the exact color is not known |
| 109 | at program-writing time). ``Enum`` allows such access:: |
| 110 | |
| 111 | >>> Color(1) |
| 112 | <Color.red: 1> |
| 113 | >>> Color(3) |
| 114 | <Color.blue: 3> |
| 115 | |
| 116 | If you want to access enum members by *name*, use item access:: |
| 117 | |
| 118 | >>> Color['red'] |
| 119 | <Color.red: 1> |
| 120 | >>> Color['green'] |
| 121 | <Color.green: 2> |
| 122 | |
Ethan Furman | 3fe70b4a | 2013-06-28 14:02:34 -0700 | [diff] [blame] | 123 | If have an enum member and need its :attr:`name` or :attr:`value`:: |
| 124 | |
| 125 | >>> member = Color.red |
| 126 | >>> member.name |
| 127 | 'red' |
| 128 | >>> member.value |
| 129 | 1 |
| 130 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 131 | |
| 132 | Duplicating enum members and values |
| 133 | ----------------------------------- |
| 134 | |
| 135 | Having two enum members with the same name is invalid:: |
| 136 | |
| 137 | >>> class Shape(Enum): |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 138 | ... square = 2 |
| 139 | ... square = 3 |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 140 | ... |
| 141 | Traceback (most recent call last): |
| 142 | ... |
| 143 | TypeError: Attempted to reuse key: 'square' |
| 144 | |
| 145 | However, two enum members are allowed to have the same value. Given two members |
| 146 | A and B with the same value (and A defined first), B is an alias to A. By-value |
| 147 | lookup of the value of A and B will return A. By-name lookup of B will also |
| 148 | return A:: |
| 149 | |
| 150 | >>> class Shape(Enum): |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 151 | ... square = 2 |
| 152 | ... diamond = 1 |
| 153 | ... circle = 3 |
| 154 | ... alias_for_square = 2 |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 155 | ... |
| 156 | >>> Shape.square |
| 157 | <Shape.square: 2> |
| 158 | >>> Shape.alias_for_square |
| 159 | <Shape.square: 2> |
| 160 | >>> Shape(2) |
| 161 | <Shape.square: 2> |
| 162 | |
Ethan Furman | 101e074 | 2013-09-15 12:34:36 -0700 | [diff] [blame] | 163 | .. note:: |
| 164 | |
| 165 | Attempting to create a member with the same name as an already |
| 166 | defined attribute (another member, a method, etc.) or attempting to create |
| 167 | an attribute with the same name as a member is not allowed. |
| 168 | |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 169 | |
| 170 | Ensuring unique enumeration values |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 171 | ---------------------------------- |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 172 | |
| 173 | By default, enumerations allow multiple names as aliases for the same value. |
| 174 | When this behavior isn't desired, the following decorator can be used to |
| 175 | ensure each value is used only once in the enumeration: |
| 176 | |
| 177 | .. decorator:: unique |
| 178 | |
| 179 | A :keyword:`class` decorator specifically for enumerations. It searches an |
| 180 | enumeration's :attr:`__members__` gathering any aliases it finds; if any are |
| 181 | found :exc:`ValueError` is raised with the details:: |
| 182 | |
| 183 | >>> from enum import Enum, unique |
| 184 | >>> @unique |
| 185 | ... class Mistake(Enum): |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 186 | ... one = 1 |
| 187 | ... two = 2 |
| 188 | ... three = 3 |
| 189 | ... four = 3 |
| 190 | ... |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 191 | Traceback (most recent call last): |
| 192 | ... |
| 193 | ValueError: duplicate values found in <enum 'Mistake'>: four -> three |
| 194 | |
| 195 | |
| 196 | Iteration |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 197 | --------- |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 198 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 199 | Iterating over the members of an enum does not provide the aliases:: |
| 200 | |
| 201 | >>> list(Shape) |
| 202 | [<Shape.square: 2>, <Shape.diamond: 1>, <Shape.circle: 3>] |
| 203 | |
| 204 | The special attribute ``__members__`` is an ordered dictionary mapping names |
| 205 | to members. It includes all names defined in the enumeration, including the |
| 206 | aliases:: |
| 207 | |
| 208 | >>> for name, member in Shape.__members__.items(): |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 209 | ... name, member |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 210 | ... |
| 211 | ('square', <Shape.square: 2>) |
| 212 | ('diamond', <Shape.diamond: 1>) |
| 213 | ('circle', <Shape.circle: 3>) |
| 214 | ('alias_for_square', <Shape.square: 2>) |
| 215 | |
| 216 | The ``__members__`` attribute can be used for detailed programmatic access to |
| 217 | the enumeration members. For example, finding all the aliases:: |
| 218 | |
| 219 | >>> [name for name, member in Shape.__members__.items() if member.name != name] |
| 220 | ['alias_for_square'] |
| 221 | |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 222 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 223 | Comparisons |
| 224 | ----------- |
| 225 | |
| 226 | Enumeration members are compared by identity:: |
| 227 | |
| 228 | >>> Color.red is Color.red |
| 229 | True |
| 230 | >>> Color.red is Color.blue |
| 231 | False |
| 232 | >>> Color.red is not Color.blue |
| 233 | True |
| 234 | |
| 235 | Ordered comparisons between enumeration values are *not* supported. Enum |
| 236 | members are not integers (but see `IntEnum`_ below):: |
| 237 | |
| 238 | >>> Color.red < Color.blue |
| 239 | Traceback (most recent call last): |
| 240 | File "<stdin>", line 1, in <module> |
| 241 | TypeError: unorderable types: Color() < Color() |
| 242 | |
| 243 | Equality comparisons are defined though:: |
| 244 | |
| 245 | >>> Color.blue == Color.red |
| 246 | False |
| 247 | >>> Color.blue != Color.red |
| 248 | True |
| 249 | >>> Color.blue == Color.blue |
| 250 | True |
| 251 | |
| 252 | Comparisons against non-enumeration values will always compare not equal |
Ezio Melotti | 93d7dda | 2013-10-05 04:13:18 +0300 | [diff] [blame] | 253 | (again, :class:`IntEnum` was explicitly designed to behave differently, see |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 254 | below):: |
| 255 | |
| 256 | >>> Color.blue == 2 |
| 257 | False |
| 258 | |
| 259 | |
| 260 | Allowed members and attributes of enumerations |
| 261 | ---------------------------------------------- |
| 262 | |
| 263 | The examples above use integers for enumeration values. Using integers is |
| 264 | short and handy (and provided by default by the `Functional API`_), but not |
| 265 | strictly enforced. In the vast majority of use-cases, one doesn't care what |
| 266 | the actual value of an enumeration is. But if the value *is* important, |
| 267 | enumerations can have arbitrary values. |
| 268 | |
| 269 | Enumerations are Python classes, and can have methods and special methods as |
| 270 | usual. If we have this enumeration:: |
| 271 | |
| 272 | >>> class Mood(Enum): |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 273 | ... funky = 1 |
| 274 | ... happy = 3 |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 275 | ... |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 276 | ... def describe(self): |
| 277 | ... # self is the member here |
| 278 | ... return self.name, self.value |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 279 | ... |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 280 | ... def __str__(self): |
| 281 | ... return 'my custom str! {0}'.format(self.value) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 282 | ... |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 283 | ... @classmethod |
| 284 | ... def favorite_mood(cls): |
| 285 | ... # cls here is the enumeration |
| 286 | ... return cls.happy |
| 287 | ... |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 288 | |
| 289 | Then:: |
| 290 | |
| 291 | >>> Mood.favorite_mood() |
| 292 | <Mood.happy: 3> |
| 293 | >>> Mood.happy.describe() |
| 294 | ('happy', 3) |
| 295 | >>> str(Mood.funky) |
| 296 | 'my custom str! 1' |
| 297 | |
| 298 | The rules for what is allowed are as follows: _sunder_ names (starting and |
| 299 | ending with a single underscore) are reserved by enum and cannot be used; |
| 300 | all other attributes defined within an enumeration will become members of this |
| 301 | enumeration, with the exception of *__dunder__* names and descriptors (methods |
| 302 | are also descriptors). |
| 303 | |
| 304 | Note: if your enumeration defines :meth:`__new__` and/or :meth:`__init__` then |
| 305 | whatever value(s) were given to the enum member will be passed into those |
| 306 | methods. See `Planet`_ for an example. |
| 307 | |
| 308 | |
| 309 | Restricted subclassing of enumerations |
| 310 | -------------------------------------- |
| 311 | |
| 312 | Subclassing an enumeration is allowed only if the enumeration does not define |
| 313 | any members. So this is forbidden:: |
| 314 | |
| 315 | >>> class MoreColor(Color): |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 316 | ... pink = 17 |
| 317 | ... |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 318 | Traceback (most recent call last): |
| 319 | ... |
| 320 | TypeError: Cannot extend enumerations |
| 321 | |
| 322 | But this is allowed:: |
| 323 | |
| 324 | >>> class Foo(Enum): |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 325 | ... def some_behavior(self): |
| 326 | ... pass |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 327 | ... |
| 328 | >>> class Bar(Foo): |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 329 | ... happy = 1 |
| 330 | ... sad = 2 |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 331 | ... |
| 332 | |
| 333 | Allowing subclassing of enums that define members would lead to a violation of |
| 334 | some important invariants of types and instances. On the other hand, it makes |
| 335 | sense to allow sharing some common behavior between a group of enumerations. |
| 336 | (See `OrderedEnum`_ for an example.) |
| 337 | |
| 338 | |
| 339 | Pickling |
| 340 | -------- |
| 341 | |
| 342 | Enumerations can be pickled and unpickled:: |
| 343 | |
| 344 | >>> from test.test_enum import Fruit |
| 345 | >>> from pickle import dumps, loads |
| 346 | >>> Fruit.tomato is loads(dumps(Fruit.tomato)) |
| 347 | True |
| 348 | |
| 349 | The usual restrictions for pickling apply: picklable enums must be defined in |
| 350 | the top level of a module, since unpickling requires them to be importable |
| 351 | from that module. |
| 352 | |
| 353 | .. warning:: |
| 354 | |
| 355 | In order to support the singleton nature of enumeration members, pickle |
| 356 | protocol version 2 or higher must be used. |
| 357 | |
| 358 | |
| 359 | Functional API |
| 360 | -------------- |
| 361 | |
| 362 | The :class:`Enum` class is callable, providing the following functional API:: |
| 363 | |
| 364 | >>> Animal = Enum('Animal', 'ant bee cat dog') |
| 365 | >>> Animal |
| 366 | <enum 'Animal'> |
| 367 | >>> Animal.ant |
| 368 | <Animal.ant: 1> |
| 369 | >>> Animal.ant.value |
| 370 | 1 |
| 371 | >>> list(Animal) |
| 372 | [<Animal.ant: 1>, <Animal.bee: 2>, <Animal.cat: 3>, <Animal.dog: 4>] |
| 373 | |
Serhiy Storchaka | 98b28fd | 2013-10-13 23:12:09 +0300 | [diff] [blame] | 374 | The semantics of this API resemble :class:`~collections.namedtuple`. The first |
| 375 | argument of the call to :class:`Enum` is the name of the enumeration. |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 376 | |
| 377 | The second argument is the *source* of enumeration member names. It can be a |
| 378 | whitespace-separated string of names, a sequence of names, a sequence of |
| 379 | 2-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to |
| 380 | values. The last two options enable assigning arbitrary values to |
| 381 | enumerations; the others auto-assign increasing integers starting with 1. A |
| 382 | new class derived from :class:`Enum` is returned. In other words, the above |
| 383 | assignment to :class:`Animal` is equivalent to:: |
| 384 | |
| 385 | >>> class Animals(Enum): |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 386 | ... ant = 1 |
| 387 | ... bee = 2 |
| 388 | ... cat = 3 |
| 389 | ... dog = 4 |
| 390 | ... |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 391 | |
Ethan Furman | e256346 | 2013-06-28 19:37:17 -0700 | [diff] [blame] | 392 | The reason for defaulting to ``1`` as the starting number and not ``0`` is |
| 393 | that ``0`` is ``False`` in a boolean sense, but enum members all evaluate |
| 394 | to ``True``. |
| 395 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 396 | Pickling enums created with the functional API can be tricky as frame stack |
| 397 | implementation details are used to try and figure out which module the |
| 398 | enumeration is being created in (e.g. it will fail if you use a utility |
| 399 | function in separate module, and also may not work on IronPython or Jython). |
| 400 | The solution is to specify the module name explicitly as follows:: |
| 401 | |
| 402 | >>> Animals = Enum('Animals', 'ant bee cat dog', module=__name__) |
| 403 | |
| 404 | Derived Enumerations |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 405 | -------------------- |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 406 | |
| 407 | IntEnum |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 408 | ^^^^^^^ |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 409 | |
| 410 | A variation of :class:`Enum` is provided which is also a subclass of |
| 411 | :class:`int`. Members of an :class:`IntEnum` can be compared to integers; |
| 412 | by extension, integer enumerations of different types can also be compared |
| 413 | to each other:: |
| 414 | |
| 415 | >>> from enum import IntEnum |
| 416 | >>> class Shape(IntEnum): |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 417 | ... circle = 1 |
| 418 | ... square = 2 |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 419 | ... |
| 420 | >>> class Request(IntEnum): |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 421 | ... post = 1 |
| 422 | ... get = 2 |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 423 | ... |
| 424 | >>> Shape == 1 |
| 425 | False |
| 426 | >>> Shape.circle == 1 |
| 427 | True |
| 428 | >>> Shape.circle == Request.post |
| 429 | True |
| 430 | |
| 431 | However, they still can't be compared to standard :class:`Enum` enumerations:: |
| 432 | |
| 433 | >>> class Shape(IntEnum): |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 434 | ... circle = 1 |
| 435 | ... square = 2 |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 436 | ... |
| 437 | >>> class Color(Enum): |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 438 | ... red = 1 |
| 439 | ... green = 2 |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 440 | ... |
| 441 | >>> Shape.circle == Color.red |
| 442 | False |
| 443 | |
| 444 | :class:`IntEnum` values behave like integers in other ways you'd expect:: |
| 445 | |
| 446 | >>> int(Shape.circle) |
| 447 | 1 |
| 448 | >>> ['a', 'b', 'c'][Shape.circle] |
| 449 | 'b' |
| 450 | >>> [i for i in range(Shape.square)] |
| 451 | [0, 1] |
| 452 | |
| 453 | For the vast majority of code, :class:`Enum` is strongly recommended, |
| 454 | since :class:`IntEnum` breaks some semantic promises of an enumeration (by |
| 455 | being comparable to integers, and thus by transitivity to other |
| 456 | unrelated enumerations). It should be used only in special cases where |
| 457 | there's no other choice; for example, when integer constants are |
| 458 | replaced with enumerations and backwards compatibility is required with code |
| 459 | that still expects integers. |
| 460 | |
| 461 | |
| 462 | Others |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 463 | ^^^^^^ |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 464 | |
| 465 | While :class:`IntEnum` is part of the :mod:`enum` module, it would be very |
| 466 | simple to implement independently:: |
| 467 | |
| 468 | class IntEnum(int, Enum): |
| 469 | pass |
| 470 | |
| 471 | This demonstrates how similar derived enumerations can be defined; for example |
| 472 | a :class:`StrEnum` that mixes in :class:`str` instead of :class:`int`. |
| 473 | |
| 474 | Some rules: |
| 475 | |
| 476 | 1. When subclassing :class:`Enum`, mix-in types must appear before |
| 477 | :class:`Enum` itself in the sequence of bases, as in the :class:`IntEnum` |
| 478 | example above. |
| 479 | 2. While :class:`Enum` can have members of any type, once you mix in an |
| 480 | additional type, all the members must have values of that type, e.g. |
| 481 | :class:`int` above. This restriction does not apply to mix-ins which only |
| 482 | add methods and don't specify another data type such as :class:`int` or |
| 483 | :class:`str`. |
| 484 | 3. When another data type is mixed in, the :attr:`value` attribute is *not the |
| 485 | same* as the enum member itself, although it is equivalant and will compare |
| 486 | equal. |
Ethan Furman | ec15a82 | 2013-08-31 19:17:41 -0700 | [diff] [blame] | 487 | 4. %-style formatting: `%s` and `%r` call :class:`Enum`'s :meth:`__str__` and |
| 488 | :meth:`__repr__` respectively; other codes (such as `%i` or `%h` for |
| 489 | IntEnum) treat the enum member as its mixed-in type. |
Ethan Furman | 455bfde | 2013-09-08 23:48:34 -0700 | [diff] [blame] | 490 | 5. :meth:`str.__format__` (or :func:`format`) will use the mixed-in |
Ethan Furman | ec15a82 | 2013-08-31 19:17:41 -0700 | [diff] [blame] | 491 | type's :meth:`__format__`. If the :class:`Enum`'s :func:`str` or |
| 492 | :func:`repr` is desired use the `!s` or `!r` :class:`str` format codes. |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 493 | |
| 494 | |
| 495 | Interesting examples |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 496 | -------------------- |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 497 | |
| 498 | While :class:`Enum` and :class:`IntEnum` are expected to cover the majority of |
| 499 | use-cases, they cannot cover them all. Here are recipes for some different |
| 500 | types of enumerations that can be used directly, or as examples for creating |
| 501 | one's own. |
| 502 | |
| 503 | |
| 504 | AutoNumber |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 505 | ^^^^^^^^^^ |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 506 | |
| 507 | Avoids having to specify the value for each enumeration member:: |
| 508 | |
| 509 | >>> class AutoNumber(Enum): |
| 510 | ... def __new__(cls): |
| 511 | ... value = len(cls.__members__) + 1 |
| 512 | ... obj = object.__new__(cls) |
Ethan Furman | 9026262 | 2013-07-30 12:24:25 -0700 | [diff] [blame] | 513 | ... obj._value_ = value |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 514 | ... return obj |
| 515 | ... |
| 516 | >>> class Color(AutoNumber): |
| 517 | ... red = () |
| 518 | ... green = () |
| 519 | ... blue = () |
| 520 | ... |
| 521 | >>> Color.green.value == 2 |
| 522 | True |
| 523 | |
Ethan Furman | 9a1daf5 | 2013-09-27 22:58:06 -0700 | [diff] [blame] | 524 | .. note:: |
| 525 | |
| 526 | The :meth:`__new__` method, if defined, is used during creation of the Enum |
| 527 | members; it is then replaced by Enum's :meth:`__new__` which is used after |
| 528 | class creation for lookup of existing members. Due to the way Enums are |
| 529 | supposed to behave, there is no way to customize Enum's :meth:`__new__`. |
| 530 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 531 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 532 | OrderedEnum |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 533 | ^^^^^^^^^^^ |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 534 | |
| 535 | An ordered enumeration that is not based on :class:`IntEnum` and so maintains |
| 536 | the normal :class:`Enum` invariants (such as not being comparable to other |
| 537 | enumerations):: |
| 538 | |
| 539 | >>> class OrderedEnum(Enum): |
| 540 | ... def __ge__(self, other): |
| 541 | ... if self.__class__ is other.__class__: |
Ethan Furman | 9026262 | 2013-07-30 12:24:25 -0700 | [diff] [blame] | 542 | ... return self.value >= other.value |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 543 | ... return NotImplemented |
| 544 | ... def __gt__(self, other): |
| 545 | ... if self.__class__ is other.__class__: |
Ethan Furman | 9026262 | 2013-07-30 12:24:25 -0700 | [diff] [blame] | 546 | ... return self.value > other.value |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 547 | ... return NotImplemented |
| 548 | ... def __le__(self, other): |
| 549 | ... if self.__class__ is other.__class__: |
Ethan Furman | 9026262 | 2013-07-30 12:24:25 -0700 | [diff] [blame] | 550 | ... return self.value <= other.value |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 551 | ... return NotImplemented |
| 552 | ... def __lt__(self, other): |
| 553 | ... if self.__class__ is other.__class__: |
Ethan Furman | 9026262 | 2013-07-30 12:24:25 -0700 | [diff] [blame] | 554 | ... return self.value < other.value |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 555 | ... return NotImplemented |
| 556 | ... |
| 557 | >>> class Grade(OrderedEnum): |
| 558 | ... A = 5 |
| 559 | ... B = 4 |
| 560 | ... C = 3 |
| 561 | ... D = 2 |
| 562 | ... F = 1 |
| 563 | ... |
| 564 | >>> Grade.C < Grade.A |
| 565 | True |
| 566 | |
| 567 | |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 568 | DuplicateFreeEnum |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 569 | ^^^^^^^^^^^^^^^^^ |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 570 | |
| 571 | Raises an error if a duplicate member name is found instead of creating an |
| 572 | alias:: |
| 573 | |
| 574 | >>> class DuplicateFreeEnum(Enum): |
| 575 | ... def __init__(self, *args): |
| 576 | ... cls = self.__class__ |
| 577 | ... if any(self.value == e.value for e in cls): |
| 578 | ... a = self.name |
| 579 | ... e = cls(self.value).name |
| 580 | ... raise ValueError( |
| 581 | ... "aliases not allowed in DuplicateFreeEnum: %r --> %r" |
| 582 | ... % (a, e)) |
| 583 | ... |
| 584 | >>> class Color(DuplicateFreeEnum): |
| 585 | ... red = 1 |
| 586 | ... green = 2 |
| 587 | ... blue = 3 |
| 588 | ... grene = 2 |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 589 | ... |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 590 | Traceback (most recent call last): |
| 591 | ... |
| 592 | ValueError: aliases not allowed in DuplicateFreeEnum: 'grene' --> 'green' |
| 593 | |
| 594 | .. note:: |
| 595 | |
| 596 | This is a useful example for subclassing Enum to add or change other |
Ezio Melotti | 93d7dda | 2013-10-05 04:13:18 +0300 | [diff] [blame] | 597 | behaviors as well as disallowing aliases. If the only desired change is |
Ezio Melotti | 17f1edd | 2013-10-05 04:26:06 +0300 | [diff] [blame] | 598 | disallowing aliases, the :func:`unique` decorator can be used instead. |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 599 | |
| 600 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 601 | Planet |
Ethan Furman | ed0bf8a | 2013-09-06 19:53:30 -0700 | [diff] [blame] | 602 | ^^^^^^ |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 603 | |
| 604 | If :meth:`__new__` or :meth:`__init__` is defined the value of the enum member |
| 605 | will be passed to those methods:: |
| 606 | |
| 607 | >>> class Planet(Enum): |
| 608 | ... MERCURY = (3.303e+23, 2.4397e6) |
| 609 | ... VENUS = (4.869e+24, 6.0518e6) |
| 610 | ... EARTH = (5.976e+24, 6.37814e6) |
| 611 | ... MARS = (6.421e+23, 3.3972e6) |
| 612 | ... JUPITER = (1.9e+27, 7.1492e7) |
| 613 | ... SATURN = (5.688e+26, 6.0268e7) |
| 614 | ... URANUS = (8.686e+25, 2.5559e7) |
| 615 | ... NEPTUNE = (1.024e+26, 2.4746e7) |
| 616 | ... def __init__(self, mass, radius): |
| 617 | ... self.mass = mass # in kilograms |
| 618 | ... self.radius = radius # in meters |
| 619 | ... @property |
| 620 | ... def surface_gravity(self): |
| 621 | ... # universal gravitational constant (m3 kg-1 s-2) |
| 622 | ... G = 6.67300E-11 |
| 623 | ... return G * self.mass / (self.radius * self.radius) |
| 624 | ... |
| 625 | >>> Planet.EARTH.value |
| 626 | (5.976e+24, 6378140.0) |
| 627 | >>> Planet.EARTH.surface_gravity |
| 628 | 9.802652743337129 |
Ethan Furman | 9a1daf5 | 2013-09-27 22:58:06 -0700 | [diff] [blame] | 629 | |
| 630 | |
| 631 | How are Enums different? |
| 632 | ------------------------ |
| 633 | |
| 634 | Enums have a custom metaclass that affects many aspects of both derived Enum |
| 635 | classes and their instances (members). |
| 636 | |
| 637 | |
| 638 | Enum Classes |
| 639 | ^^^^^^^^^^^^ |
| 640 | |
| 641 | The :class:`EnumMeta` metaclass is responsible for providing the |
| 642 | :meth:`__contains__`, :meth:`__dir__`, :meth:`__iter__` and other methods that |
| 643 | allow one to do things with an :class:`Enum` class that fail on a typical |
| 644 | class, such as `list(Color)` or `some_var in Color`. :class:`EnumMeta` is |
| 645 | responsible for ensuring that various other methods on the final :class:`Enum` |
| 646 | class are correct (such as :meth:`__new__`, :meth:`__getnewargs__`, |
| 647 | :meth:`__str__` and :meth:`__repr__`) |
| 648 | |
| 649 | |
| 650 | Enum Members (aka instances) |
| 651 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 652 | |
| 653 | The most interesting thing about Enum members is that they are singletons. |
| 654 | :class:`EnumMeta` creates them all while it is creating the :class:`Enum` |
| 655 | class itself, and then puts a custom :meth:`__new__` in place to ensure |
| 656 | that no new ones are ever instantiated by returning only the existing |
| 657 | member instances. |
| 658 | |
| 659 | |
| 660 | Finer Points |
| 661 | ^^^^^^^^^^^^ |
| 662 | |
| 663 | Enum members are instances of an Enum class, and even though they are |
| 664 | accessible as `EnumClass.member`, they are not accessible directly from |
| 665 | the member:: |
| 666 | |
| 667 | >>> Color.red |
| 668 | <Color.red: 1> |
| 669 | >>> Color.red.blue |
| 670 | Traceback (most recent call last): |
| 671 | ... |
| 672 | AttributeError: 'Color' object has no attribute 'blue' |
| 673 | |
Ezio Melotti | 93d7dda | 2013-10-05 04:13:18 +0300 | [diff] [blame] | 674 | Likewise, the :attr:`__members__` is only available on the class. |
Ethan Furman | 9a1daf5 | 2013-09-27 22:58:06 -0700 | [diff] [blame] | 675 | |
Ezio Melotti | 93d7dda | 2013-10-05 04:13:18 +0300 | [diff] [blame] | 676 | If you give your :class:`Enum` subclass extra methods, like the `Planet`_ |
| 677 | class above, those methods will show up in a :func:`dir` of the member, |
| 678 | but not of the class:: |
Ethan Furman | 9a1daf5 | 2013-09-27 22:58:06 -0700 | [diff] [blame] | 679 | |
| 680 | >>> dir(Planet) |
| 681 | ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__'] |
| 682 | >>> dir(Planet.EARTH) |
| 683 | ['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value'] |
| 684 | |
| 685 | A :meth:`__new__` method will only be used for the creation of the |
| 686 | :class:`Enum` members -- after that it is replaced. This means if you wish to |
| 687 | change how :class:`Enum` members are looked up you either have to write a |
| 688 | helper function or a :func:`classmethod`. |