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