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