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 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 16 | .. sidebar:: Important |
| 17 | |
| 18 | This page contains the API reference information. For tutorial |
| 19 | information and discussion of more advanced topics, see |
| 20 | |
| 21 | * :ref:`Basic Tutorial <enum-basic-tutorial>` |
| 22 | * :ref:`Advanced Tutorial <enum-advanced-tutorial>` |
| 23 | * :ref:`Enum Cookbook <enum-cookbook>` |
| 24 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 25 | ---------------- |
| 26 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 27 | An enumeration: |
Ethan Furman | c72e638 | 2014-02-06 08:13:14 -0800 | [diff] [blame] | 28 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 29 | * is a set of symbolic names (members) bound to unique values |
| 30 | * can be iterated over to return its members in definition order |
Ethan Furman | 7496486 | 2021-06-10 07:24:20 -0700 | [diff] [blame^] | 31 | * uses *call* syntax to return members by value |
| 32 | * uses *index* syntax to return members by name |
Ethan Furman | 542e1df | 2020-09-14 13:32:44 -0700 | [diff] [blame] | 33 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 34 | Enumerations are created either by using the :keyword:`class` syntax, or by |
| 35 | using function-call syntax:: |
| 36 | |
| 37 | >>> from enum import Enum |
| 38 | |
| 39 | >>> # class syntax |
| 40 | >>> class Color(Enum): |
| 41 | ... RED = 1 |
| 42 | ... GREEN = 2 |
| 43 | ... BLUE = 3 |
| 44 | |
| 45 | >>> # functional syntax |
| 46 | >>> Color = Enum('Color', ['RED', 'GREEN', 'BLUE']) |
| 47 | |
| 48 | Even though we can use the :keyword:`class` syntax to create Enums, Enums |
| 49 | are not normal Python classes. See |
| 50 | :ref:`How are Enums different? <enum-class-differences>` for more details. |
| 51 | |
| 52 | .. note:: Nomenclature |
| 53 | |
| 54 | - The class :class:`Color` is an *enumeration* (or *enum*) |
| 55 | - The attributes :attr:`Color.RED`, :attr:`Color.GREEN`, etc., are |
| 56 | *enumeration members* (or *enum members*) and are functionally constants. |
| 57 | - The enum members have *names* and *values* (the name of |
| 58 | :attr:`Color.RED` is ``RED``, the value of :attr:`Color.BLUE` is |
| 59 | ``3``, etc.) |
Ethan Furman | 542e1df | 2020-09-14 13:32:44 -0700 | [diff] [blame] | 60 | |
Ethan Furman | c72e638 | 2014-02-06 08:13:14 -0800 | [diff] [blame] | 61 | |
| 62 | Module Contents |
| 63 | --------------- |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 64 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 65 | :class:`EnumType` |
Ethan Furman | c72e638 | 2014-02-06 08:13:14 -0800 | [diff] [blame] | 66 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 67 | The ``type`` for Enum and its subclasses. |
Ethan Furman | c72e638 | 2014-02-06 08:13:14 -0800 | [diff] [blame] | 68 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 69 | :class:`Enum` |
Ethan Furman | c72e638 | 2014-02-06 08:13:14 -0800 | [diff] [blame] | 70 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 71 | Base class for creating enumerated constants. |
Ethan Furman | c72e638 | 2014-02-06 08:13:14 -0800 | [diff] [blame] | 72 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 73 | :class:`IntEnum` |
Ethan Furman | c72e638 | 2014-02-06 08:13:14 -0800 | [diff] [blame] | 74 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 75 | Base class for creating enumerated constants that are also |
| 76 | subclasses of :class:`int`. |
Ethan Furman | 0063ff4 | 2020-09-21 17:23:13 -0700 | [diff] [blame] | 77 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 78 | :class:`StrEnum` |
Ethan Furman | 0063ff4 | 2020-09-21 17:23:13 -0700 | [diff] [blame] | 79 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 80 | Base class for creating enumerated constants that are also |
| 81 | subclasses of :class:`str`. |
Ethan Furman | 65a5a47 | 2016-09-01 23:55:19 -0700 | [diff] [blame] | 82 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 83 | :class:`Flag` |
Ethan Furman | 65a5a47 | 2016-09-01 23:55:19 -0700 | [diff] [blame] | 84 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 85 | Base class for creating enumerated constants that can be combined using |
| 86 | the bitwise operations without losing their :class:`Flag` membership. |
Ethan Furman | 65a5a47 | 2016-09-01 23:55:19 -0700 | [diff] [blame] | 87 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 88 | :class:`IntFlag` |
Ethan Furman | 65a5a47 | 2016-09-01 23:55:19 -0700 | [diff] [blame] | 89 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 90 | Base class for creating enumerated constants that can be combined using |
| 91 | the bitwise operators without losing their :class:`IntFlag` membership. |
| 92 | :class:`IntFlag` members are also subclasses of :class:`int`. |
Ethan Furman | c72e638 | 2014-02-06 08:13:14 -0800 | [diff] [blame] | 93 | |
Ethan Furman | 7496486 | 2021-06-10 07:24:20 -0700 | [diff] [blame^] | 94 | :class:`EnumCheck` |
| 95 | |
| 96 | An enumeration with the values ``CONTINUOUS``, ``NAMED_FLAGS``, and |
| 97 | ``UNIQUE``, for use with :func:`verify` to ensure various constraints |
| 98 | are met by a given enumeration. |
| 99 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 100 | :class:`FlagBoundary` |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 101 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 102 | An enumeration with the values ``STRICT``, ``CONFORM``, ``EJECT``, and |
| 103 | ``KEEP`` which allows for more fine-grained control over how invalid values |
| 104 | are dealt with in an enumeration. |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 105 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 106 | :class:`auto` |
| 107 | |
| 108 | Instances are replaced with an appropriate value for Enum members. |
| 109 | :class:`StrEnum` defaults to the lower-cased version of the member name, |
| 110 | while other Enums default to 1 and increase from there. |
| 111 | |
| 112 | :func:`global_enum` |
| 113 | |
| 114 | :class:`Enum` class decorator to apply the appropriate global `__repr__`, |
| 115 | and export its members into the global name space. |
| 116 | |
Miss Islington (bot) | 377f3d4 | 2021-05-04 06:24:46 -0700 | [diff] [blame] | 117 | :func:`.property` |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 118 | |
| 119 | Allows :class:`Enum` members to have attributes without conflicting with |
| 120 | other members' names. |
| 121 | |
| 122 | :func:`unique` |
| 123 | |
| 124 | Enum class decorator that ensures only one name is bound to any one value. |
| 125 | |
Ethan Furman | 7496486 | 2021-06-10 07:24:20 -0700 | [diff] [blame^] | 126 | :func:`verify` |
| 127 | |
| 128 | Enum class decorator that checks user-selectable constraints on an |
| 129 | enumeration. |
| 130 | |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 131 | |
| 132 | .. versionadded:: 3.6 ``Flag``, ``IntFlag``, ``auto`` |
Ethan Furman | 7496486 | 2021-06-10 07:24:20 -0700 | [diff] [blame^] | 133 | .. versionadded:: 3.10 ``StrEnum``, ``EnumCheck``, ``FlagBoundary`` |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 134 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 135 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 136 | Data Types |
| 137 | ---------- |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 138 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 139 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 140 | .. class:: EnumType |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 141 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 142 | *EnumType* is the :term:`metaclass` for *enum* enumerations. It is possible |
| 143 | to subclass *EnumType* -- see :ref:`Subclassing EnumType <enumtype-examples>` |
| 144 | for details. |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 145 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 146 | .. method:: EnumType.__contains__(cls, member) |
Ethan Furman | 455bfde | 2013-09-08 23:48:34 -0700 | [diff] [blame] | 147 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 148 | Returns ``True`` if member belongs to the ``cls``:: |
| 149 | |
| 150 | >>> some_var = Color.RED |
| 151 | >>> some_var in Color |
| 152 | True |
| 153 | |
Ethan Furman | 6bd9288 | 2021-04-27 13:05:08 -0700 | [diff] [blame] | 154 | .. note:: |
| 155 | |
| 156 | In Python 3.12 it will be possible to check for member values and not |
| 157 | just members; until then, a ``TypeError`` will be raised if a |
| 158 | non-Enum-member is used in a containment check. |
| 159 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 160 | .. method:: EnumType.__dir__(cls) |
| 161 | |
| 162 | Returns ``['__class__', '__doc__', '__members__', '__module__']`` and the |
| 163 | names of the members in *cls*:: |
| 164 | |
| 165 | >>> dir(Color) |
| 166 | ['BLUE', 'GREEN', 'RED', '__class__', '__doc__', '__members__', '__module__'] |
| 167 | |
| 168 | .. method:: EnumType.__getattr__(cls, name) |
| 169 | |
| 170 | Returns the Enum member in *cls* matching *name*, or raises an :exc:`AttributeError`:: |
| 171 | |
| 172 | >>> Color.GREEN |
| 173 | Color.GREEN |
| 174 | |
| 175 | .. method:: EnumType.__getitem__(cls, name) |
| 176 | |
| 177 | Returns the Enum member in *cls* matching *name*, or raises an :exc:`KeyError`:: |
| 178 | |
| 179 | >>> Color['BLUE'] |
| 180 | Color.BLUE |
| 181 | |
| 182 | .. method:: EnumType.__iter__(cls) |
| 183 | |
| 184 | Returns each member in *cls* in definition order:: |
| 185 | |
| 186 | >>> list(Color) |
| 187 | [Color.RED, Color.GREEN, Color.BLUE] |
| 188 | |
| 189 | .. method:: EnumType.__len__(cls) |
| 190 | |
| 191 | Returns the number of member in *cls*:: |
| 192 | |
| 193 | >>> len(Color) |
| 194 | 3 |
| 195 | |
| 196 | .. method:: EnumType.__reversed__(cls) |
| 197 | |
| 198 | Returns each member in *cls* in reverse definition order:: |
| 199 | |
| 200 | >>> list(reversed(Color)) |
| 201 | [Color.BLUE, Color.GREEN, Color.RED] |
| 202 | |
| 203 | |
| 204 | .. class:: Enum |
| 205 | |
| 206 | *Enum* is the base class for all *enum* enumerations. |
| 207 | |
| 208 | .. attribute:: Enum.name |
| 209 | |
| 210 | The name used to define the ``Enum`` member:: |
| 211 | |
| 212 | >>> Color.BLUE.name |
| 213 | 'BLUE' |
| 214 | |
| 215 | .. attribute:: Enum.value |
| 216 | |
| 217 | The value given to the ``Enum`` member:: |
| 218 | |
| 219 | >>> Color.RED.value |
| 220 | 1 |
| 221 | |
| 222 | .. note:: Enum member values |
| 223 | |
| 224 | Member values can be anything: :class:`int`, :class:`str`, etc.. If |
| 225 | the exact value is unimportant you may use :class:`auto` instances and an |
| 226 | appropriate value will be chosen for you. Care must be taken if you mix |
| 227 | :class:`auto` with other values. |
| 228 | |
| 229 | .. attribute:: Enum._ignore_ |
| 230 | |
| 231 | ``_ignore_`` is only used during creation and is removed from the |
| 232 | enumeration once that is complete. |
| 233 | |
| 234 | ``_ignore_`` is a list of names that will not become members, and whose |
| 235 | names will also be removed from the completed enumeration. See |
| 236 | :ref:`TimePeriod <enum-time-period>` for an example. |
| 237 | |
| 238 | .. method:: Enum.__call__(cls, value, names=None, \*, module=None, qualname=None, type=None, start=1, boundary=None) |
| 239 | |
| 240 | This method is called in two different ways: |
| 241 | |
| 242 | * to look up an existing member: |
| 243 | |
| 244 | :cls: The enum class being called. |
| 245 | :value: The value to lookup. |
| 246 | |
| 247 | * to use the ``cls`` enum to create a new enum: |
| 248 | |
| 249 | :cls: The enum class being called. |
| 250 | :value: The name of the new Enum to create. |
| 251 | :names: The names/values of the members for the new Enum. |
| 252 | :module: The name of the module the new Enum is created in. |
| 253 | :qualname: The actual location in the module where this Enum can be found. |
| 254 | :type: A mix-in type for the new Enum. |
| 255 | :start: The first integer value for the Enum (used by :class:`auto`) |
| 256 | :boundary: How to handle out-of-range values from bit operations (:class:`Flag` only) |
| 257 | |
| 258 | .. method:: Enum.__dir__(self) |
| 259 | |
| 260 | Returns ``['__class__', '__doc__', '__module__', 'name', 'value']`` and |
| 261 | any public methods defined on *self.__class__*:: |
| 262 | |
| 263 | >>> from datetime import date |
| 264 | >>> class Weekday(Enum): |
| 265 | ... MONDAY = 1 |
| 266 | ... TUESDAY = 2 |
| 267 | ... WEDNESDAY = 3 |
| 268 | ... THURSDAY = 4 |
| 269 | ... FRIDAY = 5 |
| 270 | ... SATURDAY = 6 |
| 271 | ... SUNDAY = 7 |
| 272 | ... @classmethod |
| 273 | ... def today(cls): |
| 274 | ... print('today is %s' % cls(date.today.isoweekday).naem) |
| 275 | >>> dir(Weekday.SATURDAY) |
| 276 | ['__class__', '__doc__', '__module__', 'name', 'today', 'value'] |
| 277 | |
| 278 | .. method:: Enum._generate_next_value_(name, start, count, last_values) |
| 279 | |
| 280 | :name: The name of the member being defined (e.g. 'RED'). |
| 281 | :start: The start value for the Enum; the default is 1. |
| 282 | :count: The number of members currently defined, not including this one. |
| 283 | :last_values: A list of the previous values. |
| 284 | |
| 285 | A *staticmethod* that is used to determine the next value returned by |
| 286 | :class:`auto`:: |
| 287 | |
| 288 | >>> from enum import auto |
| 289 | >>> class PowersOfThree(Enum): |
| 290 | ... @staticmethod |
| 291 | ... def _generate_next_value_(name, start, count, last_values): |
| 292 | ... return (count + 1) * 3 |
| 293 | ... FIRST = auto() |
| 294 | ... SECOND = auto() |
| 295 | >>> PowersOfThree.SECOND.value |
| 296 | 6 |
| 297 | |
| 298 | .. method:: Enum._missing_(cls, value) |
| 299 | |
| 300 | A *classmethod* for looking up values not found in *cls*. By default it |
| 301 | does nothing, but can be overridden to implement custom search behavior:: |
| 302 | |
| 303 | >>> from enum import StrEnum |
| 304 | >>> class Build(StrEnum): |
| 305 | ... DEBUG = auto() |
| 306 | ... OPTIMIZED = auto() |
| 307 | ... @classmethod |
| 308 | ... def _missing_(cls, value): |
| 309 | ... value = value.lower() |
| 310 | ... for member in cls: |
| 311 | ... if member.value == value: |
| 312 | ... return member |
| 313 | ... return None |
| 314 | >>> Build.DEBUG.value |
| 315 | 'debug' |
| 316 | >>> Build('deBUG') |
| 317 | Build.DEBUG |
| 318 | |
| 319 | .. method:: Enum.__repr__(self) |
| 320 | |
| 321 | Returns the string used for *repr()* calls. By default, returns the |
| 322 | *Enum* name and the member name, but can be overridden:: |
| 323 | |
| 324 | >>> class OldStyle(Enum): |
| 325 | ... RETRO = auto() |
| 326 | ... OLD_SCHOOl = auto() |
| 327 | ... YESTERYEAR = auto() |
| 328 | ... def __repr__(self): |
| 329 | ... cls_name = self.__class__.__name__ |
| 330 | ... return f'<{cls_name}.{self.name}: {self.value}>' |
| 331 | >>> OldStyle.RETRO |
| 332 | <OldStyle.RETRO: 1> |
| 333 | |
| 334 | .. method:: Enum.__str__(self) |
| 335 | |
| 336 | Returns the string used for *str()* calls. By default, returns the |
| 337 | member name, but can be overridden:: |
| 338 | |
| 339 | >>> class OldStyle(Enum): |
| 340 | ... RETRO = auto() |
| 341 | ... OLD_SCHOOl = auto() |
| 342 | ... YESTERYEAR = auto() |
| 343 | ... def __str__(self): |
| 344 | ... cls_name = self.__class__.__name__ |
| 345 | ... return f'{cls_name}.{self.name}' |
| 346 | >>> OldStyle.RETRO |
| 347 | OldStyle.RETRO |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 348 | |
Ethan Furman | 9a1daf5 | 2013-09-27 22:58:06 -0700 | [diff] [blame] | 349 | .. note:: |
| 350 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 351 | Using :class:`auto` with :class:`Enum` results in integers of increasing value, |
| 352 | starting with ``1``. |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 353 | |
| 354 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 355 | .. class:: IntEnum |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 356 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 357 | *IntEnum* is the same as *Enum*, but its members are also integers and can be |
| 358 | used anywhere that an integer can be used. If any integer operation is performed |
| 359 | with an *IntEnum* member, the resulting value loses its enumeration status. |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 360 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 361 | >>> from enum import IntEnum |
| 362 | >>> class Numbers(IntEnum): |
| 363 | ... ONE = 1 |
| 364 | ... TWO = 2 |
| 365 | ... THREE = 3 |
| 366 | >>> Numbers.THREE |
| 367 | Numbers.THREE |
| 368 | >>> Numbers.ONE + Numbers.TWO |
| 369 | 3 |
| 370 | >>> Numbers.THREE + 5 |
| 371 | 8 |
| 372 | >>> Numbers.THREE == 3 |
| 373 | True |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 374 | |
Ethan Furman | 101e074 | 2013-09-15 12:34:36 -0700 | [diff] [blame] | 375 | .. note:: |
| 376 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 377 | Using :class:`auto` with :class:`IntEnum` results in integers of increasing value, |
| 378 | starting with ``1``. |
Ethan Furman | 101e074 | 2013-09-15 12:34:36 -0700 | [diff] [blame] | 379 | |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 380 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 381 | .. class:: StrEnum |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 382 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 383 | *StrEnum* is the same as *Enum*, but its members are also strings and can be used |
| 384 | in most of the same places that a string can be used. The result of any string |
| 385 | operation performed on or with a *StrEnum* member is not part of the enumeration. |
| 386 | |
| 387 | .. note:: There are places in the stdlib that check for an exact :class:`str` |
| 388 | instead of a :class:`str` subclass (i.e. ``type(unknown) == str`` |
| 389 | instead of ``isinstance(str, unknown)``), and in those locations you |
| 390 | will need to use ``str(StrEnum.member)``. |
| 391 | |
| 392 | |
| 393 | .. note:: |
| 394 | |
| 395 | Using :class:`auto` with :class:`StrEnum` results in values of the member name, |
| 396 | lower-cased. |
| 397 | |
| 398 | |
| 399 | .. class:: Flag |
| 400 | |
| 401 | *Flag* members support the bitwise operators ``&`` (*AND*), ``|`` (*OR*), |
| 402 | ``^`` (*XOR*), and ``~`` (*INVERT*); the results of those operators are members |
| 403 | of the enumeration. |
| 404 | |
| 405 | .. method:: __contains__(self, value) |
| 406 | |
| 407 | Returns *True* if value is in self:: |
| 408 | |
| 409 | >>> from enum import Flag, auto |
| 410 | >>> class Color(Flag): |
| 411 | ... RED = auto() |
| 412 | ... GREEN = auto() |
| 413 | ... BLUE = auto() |
| 414 | >>> purple = Color.RED | Color.BLUE |
| 415 | >>> white = Color.RED | Color.GREEN | Color.BLUE |
| 416 | >>> Color.GREEN in purple |
| 417 | False |
| 418 | >>> Color.GREEN in white |
| 419 | True |
| 420 | >>> purple in white |
| 421 | True |
| 422 | >>> white in purple |
| 423 | False |
| 424 | |
| 425 | .. method:: __iter__(self): |
| 426 | |
| 427 | Returns all contained members:: |
| 428 | |
| 429 | >>> list(Color.RED) |
| 430 | [Color.RED] |
| 431 | >>> list(purple) |
| 432 | [Color.RED, Color.BLUE] |
| 433 | |
| 434 | .. method:: __len__(self): |
| 435 | |
| 436 | Returns number of members in flag:: |
| 437 | |
| 438 | >>> len(Color.GREEN) |
| 439 | 1 |
| 440 | >>> len(white) |
| 441 | 3 |
| 442 | |
| 443 | .. method:: __bool__(self): |
| 444 | |
| 445 | Returns *True* if any members in flag, *False* otherwise:: |
| 446 | |
| 447 | >>> bool(Color.GREEN) |
| 448 | True |
| 449 | >>> bool(white) |
| 450 | True |
| 451 | >>> black = Color(0) |
| 452 | >>> bool(black) |
| 453 | False |
| 454 | |
| 455 | .. method:: __or__(self, other) |
| 456 | |
| 457 | Returns current flag binary or'ed with other:: |
| 458 | |
| 459 | >>> Color.RED | Color.GREEN |
| 460 | Color.RED|Color.GREEN |
| 461 | |
| 462 | .. method:: __and__(self, other) |
| 463 | |
| 464 | Returns current flag binary and'ed with other:: |
| 465 | |
| 466 | >>> purple & white |
| 467 | Color.RED|Color.BLUE |
| 468 | >>> purple & Color.GREEN |
| 469 | 0x0 |
| 470 | |
| 471 | .. method:: __xor__(self, other) |
| 472 | |
| 473 | Returns current flag binary xor'ed with other:: |
| 474 | |
| 475 | >>> purple ^ white |
| 476 | Color.GREEN |
| 477 | >>> purple ^ Color.GREEN |
| 478 | Color.RED|Color.GREEN|Color.BLUE |
| 479 | |
| 480 | .. method:: __invert__(self): |
| 481 | |
| 482 | Returns all the flags in *type(self)* that are not in self:: |
| 483 | |
| 484 | >>> ~white |
| 485 | 0x0 |
| 486 | >>> ~purple |
| 487 | Color.GREEN |
| 488 | >>> ~Color.RED |
| 489 | Color.GREEN|Color.BLUE |
| 490 | |
| 491 | .. note:: |
| 492 | |
| 493 | Using :class:`auto` with :class:`Flag` results in integers that are powers |
| 494 | of two, starting with ``1``. |
| 495 | |
| 496 | |
| 497 | .. class:: IntFlag |
| 498 | |
| 499 | *IntFlag* is the same as *Flag*, but its members are also integers and can be |
| 500 | used anywhere that an integer can be used. |
| 501 | |
| 502 | >>> from enum import IntFlag, auto |
| 503 | >>> class Color(IntFlag): |
| 504 | ... RED = auto() |
| 505 | ... GREEN = auto() |
| 506 | ... BLUE = auto() |
| 507 | >>> Color.RED & 2 |
| 508 | 0x0 |
| 509 | >>> Color.RED | 2 |
| 510 | Color.RED|Color.GREEN |
| 511 | |
| 512 | If any integer operation is performed with an *IntFlag* member, the result is |
| 513 | not an *IntFlag*:: |
| 514 | |
| 515 | >>> Color.RED + 2 |
| 516 | 3 |
| 517 | |
| 518 | If a *Flag* operation is performed with an *IntFlag* member and: |
| 519 | |
| 520 | * the result is a valid *IntFlag*: an *IntFlag* is returned |
| 521 | * the result is not a valid *IntFlag*: the result depends on the *FlagBoundary* setting |
| 522 | |
| 523 | .. note:: |
| 524 | |
| 525 | Using :class:`auto` with :class:`IntFlag` results in integers that are powers |
| 526 | of two, starting with ``1``. |
| 527 | |
Ethan Furman | 7496486 | 2021-06-10 07:24:20 -0700 | [diff] [blame^] | 528 | .. class:: EnumCheck |
| 529 | |
| 530 | *EnumCheck* contains the options used by the :func:`verify` decorator to ensure |
| 531 | various constraints; failed constraints result in a :exc:`TypeError`. |
| 532 | |
| 533 | .. attribute:: UNIQUE |
| 534 | |
| 535 | Ensure that each value has only one name:: |
| 536 | |
| 537 | >>> from enum import Enum, verify, UNIQUE |
| 538 | >>> @verify(UNIQUE) |
| 539 | ... class Color(Enum): |
| 540 | ... RED = 1 |
| 541 | ... GREEN = 2 |
| 542 | ... BLUE = 3 |
| 543 | ... CRIMSON = 1 |
| 544 | Traceback (most recent call last): |
| 545 | ... |
| 546 | ValueError: aliases found in <enum 'Color'>: CRIMSON -> RED |
| 547 | |
| 548 | |
| 549 | .. attribute:: CONTINUOUS |
| 550 | |
| 551 | Ensure that there are no missing values between the lowest-valued member |
| 552 | and the highest-valued member:: |
| 553 | |
| 554 | >>> from enum import Enum, verify, CONTINUOUS |
| 555 | >>> @verify(CONTINUOUS) |
| 556 | ... class Color(Enum): |
| 557 | ... RED = 1 |
| 558 | ... GREEN = 2 |
| 559 | ... BLUE = 5 |
| 560 | Traceback (most recent call last): |
| 561 | ... |
| 562 | ValueError: invalid enum 'Color': missing values 3, 4 |
| 563 | |
| 564 | .. attribute:: NAMED_FLAGS |
| 565 | |
| 566 | Ensure that any flag groups/masks contain only named flags -- useful when |
| 567 | values are specified instead of being generated by :func:`auto` |
| 568 | |
| 569 | >>> from enum import Flag, verify, NAMED_FLAGS |
| 570 | >>> @verify(NAMED_FLAGS) |
| 571 | ... class Color(Flag): |
| 572 | ... RED = 1 |
| 573 | ... GREEN = 2 |
| 574 | ... BLUE = 4 |
| 575 | ... WHITE = 15 |
| 576 | ... NEON = 31 |
| 577 | Traceback (most recent call last): |
| 578 | ... |
| 579 | ValueError: invalid Flag 'Color': 'WHITE' is missing a named flag for value 8; 'NEON' is missing named flags for values 8, 16 |
| 580 | |
| 581 | .. note:: |
| 582 | |
| 583 | CONTINUOUS and NAMED_FLAGS are designed to work with integer-valued members. |
| 584 | |
| 585 | .. versionadded:: 3.10 |
| 586 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 587 | .. class:: FlagBoundary |
| 588 | |
| 589 | *FlagBoundary* controls how out-of-range values are handled in *Flag* and its |
| 590 | subclasses. |
| 591 | |
| 592 | .. attribute:: STRICT |
| 593 | |
| 594 | Out-of-range values cause a :exc:`ValueError` to be raised. This is the |
| 595 | default for :class:`Flag`:: |
| 596 | |
Ethan Furman | 49aec1a | 2021-03-31 09:20:08 -0700 | [diff] [blame] | 597 | >>> from enum import Flag, STRICT |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 598 | >>> class StrictFlag(Flag, boundary=STRICT): |
| 599 | ... RED = auto() |
| 600 | ... GREEN = auto() |
| 601 | ... BLUE = auto() |
| 602 | >>> StrictFlag(2**2 + 2**4) |
| 603 | Traceback (most recent call last): |
| 604 | ... |
| 605 | ValueError: StrictFlag: invalid value: 20 |
| 606 | given 0b0 10100 |
| 607 | allowed 0b0 00111 |
| 608 | |
| 609 | .. attribute:: CONFORM |
| 610 | |
| 611 | Out-of-range values have invalid values removed, leaving a valid *Flag* |
| 612 | value:: |
| 613 | |
Ethan Furman | 49aec1a | 2021-03-31 09:20:08 -0700 | [diff] [blame] | 614 | >>> from enum import Flag, CONFORM |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 615 | >>> class ConformFlag(Flag, boundary=CONFORM): |
| 616 | ... RED = auto() |
| 617 | ... GREEN = auto() |
| 618 | ... BLUE = auto() |
| 619 | >>> ConformFlag(2**2 + 2**4) |
| 620 | ConformFlag.BLUE |
| 621 | |
| 622 | .. attribute:: EJECT |
| 623 | |
| 624 | Out-of-range values lose their *Flag* membership and revert to :class:`int`. |
| 625 | This is the default for :class:`IntFlag`:: |
| 626 | |
Ethan Furman | 49aec1a | 2021-03-31 09:20:08 -0700 | [diff] [blame] | 627 | >>> from enum import Flag, EJECT |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 628 | >>> class EjectFlag(Flag, boundary=EJECT): |
| 629 | ... RED = auto() |
| 630 | ... GREEN = auto() |
| 631 | ... BLUE = auto() |
| 632 | >>> EjectFlag(2**2 + 2**4) |
| 633 | 20 |
| 634 | |
| 635 | .. attribute:: KEEP |
| 636 | |
| 637 | Out-of-range values are kept, and the *Flag* membership is kept. This is |
| 638 | used for some stdlib flags: |
| 639 | |
Ethan Furman | 49aec1a | 2021-03-31 09:20:08 -0700 | [diff] [blame] | 640 | >>> from enum import Flag, KEEP |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 641 | >>> class KeepFlag(Flag, boundary=KEEP): |
| 642 | ... RED = auto() |
| 643 | ... GREEN = auto() |
| 644 | ... BLUE = auto() |
| 645 | >>> KeepFlag(2**2 + 2**4) |
| 646 | KeepFlag.BLUE|0x10 |
| 647 | |
Ethan Furman | 7496486 | 2021-06-10 07:24:20 -0700 | [diff] [blame^] | 648 | .. versionadded:: 3.10 |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 649 | |
| 650 | Utilites and Decorators |
| 651 | ----------------------- |
| 652 | |
| 653 | .. class:: auto |
| 654 | |
| 655 | *auto* can be used in place of a value. If used, the *Enum* machinery will |
| 656 | call an *Enum*'s :meth:`_generate_next_value_` to get an appropriate value. |
| 657 | For *Enum* and *IntEnum* that appropriate value will be the last value plus |
| 658 | one; for *Flag* and *IntFlag* it will be the first power-of-two greater |
| 659 | than the last value; for *StrEnum* it will be the lower-cased version of the |
| 660 | member's name. |
| 661 | |
| 662 | ``_generate_next_value_`` can be overridden to customize the values used by |
| 663 | *auto*. |
| 664 | |
| 665 | .. decorator:: global_enum |
| 666 | |
| 667 | A :keyword:`class` decorator specifically for enumerations. It replaces the |
| 668 | :meth:`__repr__` method with one that shows *module_name*.*member_name*. It |
Miss Islington (bot) | 37da1f0 | 2021-05-22 13:55:17 -0700 | [diff] [blame] | 669 | also injects the members, and their aliases, into the global namespace they |
| 670 | were defined in. |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 671 | |
| 672 | |
| 673 | .. decorator:: property |
| 674 | |
| 675 | A decorator similar to the built-in *property*, but specifically for |
| 676 | enumerations. It allows member attributes to have the same names as members |
| 677 | themselves. |
| 678 | |
| 679 | .. note:: the *property* and the member must be defined in separate classes; |
| 680 | for example, the *value* and *name* attributes are defined in the |
| 681 | *Enum* class, and *Enum* subclasses can define members with the |
| 682 | names ``value`` and ``name``. |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 683 | |
| 684 | .. decorator:: unique |
| 685 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 686 | A :keyword:`class` decorator specifically for enumerations. It searches an |
| 687 | enumeration's :attr:`__members__`, gathering any aliases it finds; if any are |
| 688 | found :exc:`ValueError` is raised with the details:: |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 689 | |
Ethan Furman | b775106 | 2021-03-30 21:17:26 -0700 | [diff] [blame] | 690 | >>> from enum import Enum, unique |
| 691 | >>> @unique |
| 692 | ... class Mistake(Enum): |
| 693 | ... ONE = 1 |
| 694 | ... TWO = 2 |
| 695 | ... THREE = 3 |
| 696 | ... FOUR = 3 |
| 697 | ... |
| 698 | Traceback (most recent call last): |
| 699 | ... |
| 700 | ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE |
Ethan Furman | 7496486 | 2021-06-10 07:24:20 -0700 | [diff] [blame^] | 701 | |
| 702 | .. decorator:: verify |
| 703 | |
| 704 | A :keyword:`class` decorator specifically for enumerations. Members from |
| 705 | :class:`EnumCheck` are used to specify which constraints should be checked |
| 706 | on the decorated enumeration. |
| 707 | |
| 708 | .. versionadded:: 3.10 |