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