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