diff options
Diffstat (limited to 'devdocs/python~3.12/howto%2Fenum.html')
| -rw-r--r-- | devdocs/python~3.12/howto%2Fenum.html | 641 |
1 files changed, 641 insertions, 0 deletions
diff --git a/devdocs/python~3.12/howto%2Fenum.html b/devdocs/python~3.12/howto%2Fenum.html new file mode 100644 index 00000000..0abc0df6 --- /dev/null +++ b/devdocs/python~3.12/howto%2Fenum.html @@ -0,0 +1,641 @@ + <h1>Enum HOWTO</h1> <p id="enum-basic-tutorial">An <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> is a set of symbolic names bound to unique values. They are similar to global variables, but they offer a more useful <a class="reference internal" href="../library/functions#repr" title="repr"><code>repr()</code></a>, grouping, type-safety, and a few other features.</p> <p>They are most useful when you have a variable that can take one of a limited selection of values. For example, the days of the week:</p> <pre data-language="python">>>> from enum import Enum +>>> class Weekday(Enum): +... MONDAY = 1 +... TUESDAY = 2 +... WEDNESDAY = 3 +... THURSDAY = 4 +... FRIDAY = 5 +... SATURDAY = 6 +... SUNDAY = 7 +</pre> <p>Or perhaps the RGB primary colors:</p> <pre data-language="python">>>> from enum import Enum +>>> class Color(Enum): +... RED = 1 +... GREEN = 2 +... BLUE = 3 +</pre> <p>As you can see, creating an <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> is as simple as writing a class that inherits from <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> itself.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Case of Enum Members</p> <p>Because Enums are used to represent constants, and to help avoid issues with name clashes between mixin-class methods/attributes and enum names, we strongly recommend using UPPER_CASE names for members, and will be using that style in our examples.</p> </div> <p>Depending on the nature of the enum a member’s value may or may not be important, but either way that value can be used to get the corresponding member:</p> <pre data-language="python">>>> Weekday(3) +<Weekday.WEDNESDAY: 3> +</pre> <p>As you can see, the <code>repr()</code> of a member shows the enum name, the member name, and the value. The <code>str()</code> of a member shows only the enum name and member name:</p> <pre data-language="python">>>> print(Weekday.THURSDAY) +Weekday.THURSDAY +</pre> <p>The <em>type</em> of an enumeration member is the enum it belongs to:</p> <pre data-language="python">>>> type(Weekday.MONDAY) +<enum 'Weekday'> +>>> isinstance(Weekday.FRIDAY, Weekday) +True +</pre> <p>Enum members have an attribute that contains just their <code>name</code>:</p> <pre data-language="python">>>> print(Weekday.TUESDAY.name) +TUESDAY +</pre> <p>Likewise, they have an attribute for their <code>value</code>:</p> <pre data-language="python">>>> Weekday.WEDNESDAY.value +3 +</pre> <p>Unlike many languages that treat enumerations solely as name/value pairs, Python Enums can have behavior added. For example, <a class="reference internal" href="../library/datetime#datetime.date" title="datetime.date"><code>datetime.date</code></a> has two methods for returning the weekday: <code>weekday()</code> and <code>isoweekday()</code>. The difference is that one of them counts from 0-6 and the other from 1-7. Rather than keep track of that ourselves we can add a method to the <code>Weekday</code> enum to extract the day from the <code>date</code> instance and return the matching enum member:</p> <pre data-language="python">@classmethod +def from_date(cls, date): + return cls(date.isoweekday()) +</pre> <p>The complete <code>Weekday</code> enum now looks like this:</p> <pre data-language="python">>>> class Weekday(Enum): +... MONDAY = 1 +... TUESDAY = 2 +... WEDNESDAY = 3 +... THURSDAY = 4 +... FRIDAY = 5 +... SATURDAY = 6 +... SUNDAY = 7 +... # +... @classmethod +... def from_date(cls, date): +... return cls(date.isoweekday()) +</pre> <p>Now we can find out what today is! Observe:</p> <pre data-language="python">>>> from datetime import date +>>> Weekday.from_date(date.today()) +<Weekday.TUESDAY: 2> +</pre> <p>Of course, if you’re reading this on some other day, you’ll see that day instead.</p> <p>This <code>Weekday</code> enum is great if our variable only needs one day, but what if we need several? Maybe we’re writing a function to plot chores during a week, and don’t want to use a <a class="reference internal" href="../library/stdtypes#list" title="list"><code>list</code></a> – we could use a different type of <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a>:</p> <pre data-language="python">>>> from enum import Flag +>>> class Weekday(Flag): +... MONDAY = 1 +... TUESDAY = 2 +... WEDNESDAY = 4 +... THURSDAY = 8 +... FRIDAY = 16 +... SATURDAY = 32 +... SUNDAY = 64 +</pre> <p>We’ve changed two things: we’re inherited from <a class="reference internal" href="../library/enum#enum.Flag" title="enum.Flag"><code>Flag</code></a>, and the values are all powers of 2.</p> <p>Just like the original <code>Weekday</code> enum above, we can have a single selection:</p> <pre data-language="python">>>> first_week_day = Weekday.MONDAY +>>> first_week_day +<Weekday.MONDAY: 1> +</pre> <p>But <a class="reference internal" href="../library/enum#enum.Flag" title="enum.Flag"><code>Flag</code></a> also allows us to combine several members into a single variable:</p> <pre data-language="python">>>> weekend = Weekday.SATURDAY | Weekday.SUNDAY +>>> weekend +<Weekday.SATURDAY|SUNDAY: 96> +</pre> <p>You can even iterate over a <a class="reference internal" href="../library/enum#enum.Flag" title="enum.Flag"><code>Flag</code></a> variable:</p> <pre data-language="python">>>> for day in weekend: +... print(day) +Weekday.SATURDAY +Weekday.SUNDAY +</pre> <p>Okay, let’s get some chores set up:</p> <pre data-language="python">>>> chores_for_ethan = { +... 'feed the cat': Weekday.MONDAY | Weekday.WEDNESDAY | Weekday.FRIDAY, +... 'do the dishes': Weekday.TUESDAY | Weekday.THURSDAY, +... 'answer SO questions': Weekday.SATURDAY, +... } +</pre> <p>And a function to display the chores for a given day:</p> <pre data-language="python">>>> def show_chores(chores, day): +... for chore, days in chores.items(): +... if day in days: +... print(chore) +... +>>> show_chores(chores_for_ethan, Weekday.SATURDAY) +answer SO questions +</pre> <p>In cases where the actual values of the members do not matter, you can save yourself some work and use <a class="reference internal" href="../library/enum#enum.auto" title="enum.auto"><code>auto()</code></a> for the values:</p> <pre data-language="python">>>> from enum import auto +>>> class Weekday(Flag): +... MONDAY = auto() +... TUESDAY = auto() +... WEDNESDAY = auto() +... THURSDAY = auto() +... FRIDAY = auto() +... SATURDAY = auto() +... SUNDAY = auto() +... WEEKEND = SATURDAY | SUNDAY +</pre> <section id="programmatic-access-to-enumeration-members-and-their-attributes"> <span id="enum-advanced-tutorial"></span><h2>Programmatic access to enumeration members and their attributes</h2> <p>Sometimes it’s useful to access members in enumerations programmatically (i.e. situations where <code>Color.RED</code> won’t do because the exact color is not known at program-writing time). <code>Enum</code> allows such access:</p> <pre data-language="python">>>> Color(1) +<Color.RED: 1> +>>> Color(3) +<Color.BLUE: 3> +</pre> <p>If you want to access enum members by <em>name</em>, use item access:</p> <pre data-language="python">>>> Color['RED'] +<Color.RED: 1> +>>> Color['GREEN'] +<Color.GREEN: 2> +</pre> <p>If you have an enum member and need its <code>name</code> or <code>value</code>:</p> <pre data-language="python">>>> member = Color.RED +>>> member.name +'RED' +>>> member.value +1 +</pre> </section> <section id="duplicating-enum-members-and-values"> <h2>Duplicating enum members and values</h2> <p>Having two enum members with the same name is invalid:</p> <pre data-language="python">>>> class Shape(Enum): +... SQUARE = 2 +... SQUARE = 3 +... +Traceback (most recent call last): +... +TypeError: 'SQUARE' already defined as 2 +</pre> <p>However, an enum member can have other names associated with it. Given two entries <code>A</code> and <code>B</code> with the same value (and <code>A</code> defined first), <code>B</code> is an alias for the member <code>A</code>. By-value lookup of the value of <code>A</code> will return the member <code>A</code>. By-name lookup of <code>A</code> will return the member <code>A</code>. By-name lookup of <code>B</code> will also return the member <code>A</code>:</p> <pre data-language="python">>>> class Shape(Enum): +... SQUARE = 2 +... DIAMOND = 1 +... CIRCLE = 3 +... ALIAS_FOR_SQUARE = 2 +... +>>> Shape.SQUARE +<Shape.SQUARE: 2> +>>> Shape.ALIAS_FOR_SQUARE +<Shape.SQUARE: 2> +>>> Shape(2) +<Shape.SQUARE: 2> +</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Attempting to create a member with the same name as an already defined attribute (another member, a method, etc.) or attempting to create an attribute with the same name as a member is not allowed.</p> </div> </section> <section id="ensuring-unique-enumeration-values"> <h2>Ensuring unique enumeration values</h2> <p>By default, enumerations allow multiple names as aliases for the same value. When this behavior isn’t desired, you can use the <a class="reference internal" href="../library/enum#enum.unique" title="enum.unique"><code>unique()</code></a> decorator:</p> <pre data-language="python">>>> from enum import Enum, unique +>>> @unique +... class Mistake(Enum): +... ONE = 1 +... TWO = 2 +... THREE = 3 +... FOUR = 3 +... +Traceback (most recent call last): +... +ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE +</pre> </section> <section id="using-automatic-values"> <h2>Using automatic values</h2> <p>If the exact value is unimportant you can use <a class="reference internal" href="../library/enum#enum.auto" title="enum.auto"><code>auto</code></a>:</p> <pre data-language="python">>>> from enum import Enum, auto +>>> class Color(Enum): +... RED = auto() +... BLUE = auto() +... GREEN = auto() +... +>>> [member.value for member in Color] +[1, 2, 3] +</pre> <p>The values are chosen by <code>_generate_next_value_()</code>, which can be overridden:</p> <pre data-language="python">>>> class AutoName(Enum): +... @staticmethod +... def _generate_next_value_(name, start, count, last_values): +... return name +... +>>> class Ordinal(AutoName): +... NORTH = auto() +... SOUTH = auto() +... EAST = auto() +... WEST = auto() +... +>>> [member.value for member in Ordinal] +['NORTH', 'SOUTH', 'EAST', 'WEST'] +</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <code>_generate_next_value_()</code> method must be defined before any members.</p> </div> </section> <section id="iteration"> <h2>Iteration</h2> <p>Iterating over the members of an enum does not provide the aliases:</p> <pre data-language="python">>>> list(Shape) +[<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>] +>>> list(Weekday) +[<Weekday.MONDAY: 1>, <Weekday.TUESDAY: 2>, <Weekday.WEDNESDAY: 4>, <Weekday.THURSDAY: 8>, <Weekday.FRIDAY: 16>, <Weekday.SATURDAY: 32>, <Weekday.SUNDAY: 64>] +</pre> <p>Note that the aliases <code>Shape.ALIAS_FOR_SQUARE</code> and <code>Weekday.WEEKEND</code> aren’t shown.</p> <p>The special attribute <code>__members__</code> is a read-only ordered mapping of names to members. It includes all names defined in the enumeration, including the aliases:</p> <pre data-language="python">>>> for name, member in Shape.__members__.items(): +... name, member +... +('SQUARE', <Shape.SQUARE: 2>) +('DIAMOND', <Shape.DIAMOND: 1>) +('CIRCLE', <Shape.CIRCLE: 3>) +('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>) +</pre> <p>The <code>__members__</code> attribute can be used for detailed programmatic access to the enumeration members. For example, finding all the aliases:</p> <pre data-language="python">>>> [name for name, member in Shape.__members__.items() if member.name != name] +['ALIAS_FOR_SQUARE'] +</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Aliases for flags include values with multiple flags set, such as <code>3</code>, and no flags set, i.e. <code>0</code>.</p> </div> </section> <section id="comparisons"> <h2>Comparisons</h2> <p>Enumeration members are compared by identity:</p> <pre data-language="python">>>> Color.RED is Color.RED +True +>>> Color.RED is Color.BLUE +False +>>> Color.RED is not Color.BLUE +True +</pre> <p>Ordered comparisons between enumeration values are <em>not</em> supported. Enum members are not integers (but see <a class="reference internal" href="#intenum">IntEnum</a> below):</p> <pre data-language="python">>>> Color.RED < Color.BLUE +Traceback (most recent call last): + File "<stdin>", line 1, in <module> +TypeError: '<' not supported between instances of 'Color' and 'Color' +</pre> <p>Equality comparisons are defined though:</p> <pre data-language="python">>>> Color.BLUE == Color.RED +False +>>> Color.BLUE != Color.RED +True +>>> Color.BLUE == Color.BLUE +True +</pre> <p>Comparisons against non-enumeration values will always compare not equal (again, <a class="reference internal" href="../library/enum#enum.IntEnum" title="enum.IntEnum"><code>IntEnum</code></a> was explicitly designed to behave differently, see below):</p> <pre data-language="python">>>> Color.BLUE == 2 +False +</pre> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>It is possible to reload modules – if a reloaded module contains enums, they will be recreated, and the new members may not compare identical/equal to the original members.</p> </div> </section> <section id="allowed-members-and-attributes-of-enumerations"> <h2>Allowed members and attributes of enumerations</h2> <p>Most of the examples above use integers for enumeration values. Using integers is short and handy (and provided by default by the <a class="reference internal" href="#functional-api">Functional API</a>), but not strictly enforced. In the vast majority of use-cases, one doesn’t care what the actual value of an enumeration is. But if the value <em>is</em> important, enumerations can have arbitrary values.</p> <p>Enumerations are Python classes, and can have methods and special methods as usual. If we have this enumeration:</p> <pre data-language="python">>>> class Mood(Enum): +... FUNKY = 1 +... HAPPY = 3 +... +... def describe(self): +... # self is the member here +... return self.name, self.value +... +... def __str__(self): +... return 'my custom str! {0}'.format(self.value) +... +... @classmethod +... def favorite_mood(cls): +... # cls here is the enumeration +... return cls.HAPPY +... +</pre> <p>Then:</p> <pre data-language="python">>>> Mood.favorite_mood() +<Mood.HAPPY: 3> +>>> Mood.HAPPY.describe() +('HAPPY', 3) +>>> str(Mood.FUNKY) +'my custom str! 1' +</pre> <p>The rules for what is allowed are as follows: names that start and end with a single underscore are reserved by enum and cannot be used; all other attributes defined within an enumeration will become members of this enumeration, with the exception of special methods (<code>__str__()</code>, <code>__add__()</code>, etc.), descriptors (methods are also descriptors), and variable names listed in <code>_ignore_</code>.</p> <p>Note: if your enumeration defines <code>__new__()</code> and/or <code>__init__()</code>, any value(s) given to the enum member will be passed into those methods. See <a class="reference internal" href="#planet">Planet</a> for an example.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <code>__new__()</code> method, if defined, is used during creation of the Enum members; it is then replaced by Enum’s <code>__new__()</code> which is used after class creation for lookup of existing members. See <a class="reference internal" href="#new-vs-init"><span class="std std-ref">When to use __new__() vs. __init__()</span></a> for more details.</p> </div> </section> <section id="restricted-enum-subclassing"> <h2>Restricted Enum subclassing</h2> <p>A new <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> class must have one base enum class, up to one concrete data type, and as many <a class="reference internal" href="../library/functions#object" title="object"><code>object</code></a>-based mixin classes as needed. The order of these base classes is:</p> <pre data-language="python">class EnumName([mix-in, ...,] [data-type,] base-enum): + pass +</pre> <p>Also, subclassing an enumeration is allowed only if the enumeration does not define any members. So this is forbidden:</p> <pre data-language="python">>>> class MoreColor(Color): +... PINK = 17 +... +Traceback (most recent call last): +... +TypeError: <enum 'MoreColor'> cannot extend <enum 'Color'> +</pre> <p>But this is allowed:</p> <pre data-language="python">>>> class Foo(Enum): +... def some_behavior(self): +... pass +... +>>> class Bar(Foo): +... HAPPY = 1 +... SAD = 2 +... +</pre> <p>Allowing subclassing of enums that define members would lead to a violation of some important invariants of types and instances. On the other hand, it makes sense to allow sharing some common behavior between a group of enumerations. (See <a class="reference internal" href="#orderedenum">OrderedEnum</a> for an example.)</p> </section> <section id="dataclass-support"> <span id="enum-dataclass-support"></span><h2>Dataclass support</h2> <p>When inheriting from a <a class="reference internal" href="../library/dataclasses#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass</code></a>, the <a class="reference internal" href="../library/enum#enum.Enum.__repr__" title="enum.Enum.__repr__"><code>__repr__()</code></a> omits the inherited class’ name. For example:</p> <pre data-language="python">>>> from dataclasses import dataclass, field +>>> @dataclass +... class CreatureDataMixin: +... size: str +... legs: int +... tail: bool = field(repr=False, default=True) +... +>>> class Creature(CreatureDataMixin, Enum): +... BEETLE = 'small', 6 +... DOG = 'medium', 4 +... +>>> Creature.DOG +<Creature.DOG: size='medium', legs=4> +</pre> <p>Use the <code>dataclass()</code> argument <code>repr=False</code> to use the standard <a class="reference internal" href="../library/functions#repr" title="repr"><code>repr()</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Only the dataclass fields are shown in the value area, not the dataclass’ name.</p> </div> </section> <section id="pickling"> <h2>Pickling</h2> <p>Enumerations can be pickled and unpickled:</p> <pre data-language="python">>>> from test.test_enum import Fruit +>>> from pickle import dumps, loads +>>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO)) +True +</pre> <p>The usual restrictions for pickling apply: picklable enums must be defined in the top level of a module, since unpickling requires them to be importable from that module.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>With pickle protocol version 4 it is possible to easily pickle enums nested in other classes.</p> </div> <p>It is possible to modify how enum members are pickled/unpickled by defining <code>__reduce_ex__()</code> in the enumeration class. The default method is by-value, but enums with complicated values may want to use by-name:</p> <pre data-language="python">>>> import enum +>>> class MyEnum(enum.Enum): +... __reduce_ex__ = enum.pickle_by_enum_name +</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Using by-name for flags is not recommended, as unnamed aliases will not unpickle.</p> </div> </section> <section id="functional-api"> <h2>Functional API</h2> <p>The <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> class is callable, providing the following functional API:</p> <pre data-language="python">>>> Animal = Enum('Animal', 'ANT BEE CAT DOG') +>>> Animal +<enum 'Animal'> +>>> Animal.ANT +<Animal.ANT: 1> +>>> list(Animal) +[<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>] +</pre> <p>The semantics of this API resemble <a class="reference internal" href="../library/collections#collections.namedtuple" title="collections.namedtuple"><code>namedtuple</code></a>. The first argument of the call to <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> is the name of the enumeration.</p> <p>The second argument is the <em>source</em> of enumeration member names. It can be a whitespace-separated string of names, a sequence of names, a sequence of 2-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to values. The last two options enable assigning arbitrary values to enumerations; the others auto-assign increasing integers starting with 1 (use the <code>start</code> parameter to specify a different starting value). A new class derived from <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> is returned. In other words, the above assignment to <code>Animal</code> is equivalent to:</p> <pre data-language="python">>>> class Animal(Enum): +... ANT = 1 +... BEE = 2 +... CAT = 3 +... DOG = 4 +... +</pre> <p>The reason for defaulting to <code>1</code> as the starting number and not <code>0</code> is that <code>0</code> is <code>False</code> in a boolean sense, but by default enum members all evaluate to <code>True</code>.</p> <p>Pickling enums created with the functional API can be tricky as frame stack implementation details are used to try and figure out which module the enumeration is being created in (e.g. it will fail if you use a utility function in a separate module, and also may not work on IronPython or Jython). The solution is to specify the module name explicitly as follows:</p> <pre data-language="python">>>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__) +</pre> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>If <code>module</code> is not supplied, and Enum cannot determine what it is, the new Enum members will not be unpicklable; to keep errors closer to the source, pickling will be disabled.</p> </div> <p>The new pickle protocol 4 also, in some circumstances, relies on <a class="reference internal" href="../library/stdtypes#definition.__qualname__" title="definition.__qualname__"><code>__qualname__</code></a> being set to the location where pickle will be able to find the class. For example, if the class was made available in class SomeData in the global scope:</p> <pre data-language="python">>>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal') +</pre> <p>The complete signature is:</p> <pre data-language="python">Enum( + value='NewEnumName', + names=<...>, + *, + module='...', + qualname='...', + type=<mixed-in class>, + start=1, + ) +</pre> <ul> <li> +<em>value</em>: What the new enum class will record as its name.</li> <li> +<p><em>names</em>: The enum members. This can be a whitespace- or comma-separated string (values will start at 1 unless otherwise specified):</p> <pre data-language="python">'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE' +</pre> <p>or an iterator of names:</p> <pre data-language="python">['RED', 'GREEN', 'BLUE'] +</pre> <p>or an iterator of (name, value) pairs:</p> <pre data-language="python">[('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)] +</pre> <p>or a mapping:</p> <pre data-language="python">{'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42} +</pre> </li> <li> +<em>module</em>: name of module where new enum class can be found.</li> <li> +<em>qualname</em>: where in module new enum class can be found.</li> <li> +<em>type</em>: type to mix in to new enum class.</li> <li> +<em>start</em>: number to start counting at if only names are passed in.</li> </ul> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The <em>start</em> parameter was added.</p> </div> </section> <section id="derived-enumerations"> <h2>Derived Enumerations</h2> <section id="intenum"> <h3>IntEnum</h3> <p>The first variation of <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> that is provided is also a subclass of <a class="reference internal" href="../library/functions#int" title="int"><code>int</code></a>. Members of an <a class="reference internal" href="../library/enum#enum.IntEnum" title="enum.IntEnum"><code>IntEnum</code></a> can be compared to integers; by extension, integer enumerations of different types can also be compared to each other:</p> <pre data-language="python">>>> from enum import IntEnum +>>> class Shape(IntEnum): +... CIRCLE = 1 +... SQUARE = 2 +... +>>> class Request(IntEnum): +... POST = 1 +... GET = 2 +... +>>> Shape == 1 +False +>>> Shape.CIRCLE == 1 +True +>>> Shape.CIRCLE == Request.POST +True +</pre> <p>However, they still can’t be compared to standard <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> enumerations:</p> <pre data-language="python">>>> class Shape(IntEnum): +... CIRCLE = 1 +... SQUARE = 2 +... +>>> class Color(Enum): +... RED = 1 +... GREEN = 2 +... +>>> Shape.CIRCLE == Color.RED +False +</pre> <p><a class="reference internal" href="../library/enum#enum.IntEnum" title="enum.IntEnum"><code>IntEnum</code></a> values behave like integers in other ways you’d expect:</p> <pre data-language="python">>>> int(Shape.CIRCLE) +1 +>>> ['a', 'b', 'c'][Shape.CIRCLE] +'b' +>>> [i for i in range(Shape.SQUARE)] +[0, 1] +</pre> </section> <section id="strenum"> <h3>StrEnum</h3> <p>The second variation of <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> that is provided is also a subclass of <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str</code></a>. Members of a <a class="reference internal" href="../library/enum#enum.StrEnum" title="enum.StrEnum"><code>StrEnum</code></a> can be compared to strings; by extension, string enumerations of different types can also be compared to each other.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </section> <section id="intflag"> <h3>IntFlag</h3> <p>The next variation of <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> provided, <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a>, is also based on <a class="reference internal" href="../library/functions#int" title="int"><code>int</code></a>. The difference being <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a> members can be combined using the bitwise operators (&, |, ^, ~) and the result is still an <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a> member, if possible. Like <a class="reference internal" href="../library/enum#enum.IntEnum" title="enum.IntEnum"><code>IntEnum</code></a>, <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a> members are also integers and can be used wherever an <a class="reference internal" href="../library/functions#int" title="int"><code>int</code></a> is used.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Any operation on an <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a> member besides the bit-wise operations will lose the <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a> membership.</p> <p>Bit-wise operations that result in invalid <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a> values will lose the <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a> membership. See <a class="reference internal" href="../library/enum#enum.FlagBoundary" title="enum.FlagBoundary"><code>FlagBoundary</code></a> for details.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11.</span></p> </div> <p>Sample <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a> class:</p> <pre data-language="python">>>> from enum import IntFlag +>>> class Perm(IntFlag): +... R = 4 +... W = 2 +... X = 1 +... +>>> Perm.R | Perm.W +<Perm.R|W: 6> +>>> Perm.R + Perm.W +6 +>>> RW = Perm.R | Perm.W +>>> Perm.R in RW +True +</pre> <p>It is also possible to name the combinations:</p> <pre data-language="python">>>> class Perm(IntFlag): +... R = 4 +... W = 2 +... X = 1 +... RWX = 7 +... +>>> Perm.RWX +<Perm.RWX: 7> +>>> ~Perm.RWX +<Perm: 0> +>>> Perm(7) +<Perm.RWX: 7> +</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Named combinations are considered aliases. Aliases do not show up during iteration, but can be returned from by-value lookups.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11.</span></p> </div> <p>Another important difference between <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a> and <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> is that if no flags are set (the value is 0), its boolean evaluation is <a class="reference internal" href="../library/constants#False" title="False"><code>False</code></a>:</p> <pre data-language="python">>>> Perm.R & Perm.X +<Perm: 0> +>>> bool(Perm.R & Perm.X) +False +</pre> <p>Because <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a> members are also subclasses of <a class="reference internal" href="../library/functions#int" title="int"><code>int</code></a> they can be combined with them (but may lose <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a> membership:</p> <pre data-language="python">>>> Perm.X | 4 +<Perm.R|X: 5> + +>>> Perm.X + 8 +9 +</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The negation operator, <code>~</code>, always returns an <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a> member with a positive value:</p> <pre data-language="python">>>> (~Perm.X).value == (Perm.R|Perm.W).value == 6 +True +</pre> </div> <p><a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a> members can also be iterated over:</p> <pre data-language="python">>>> list(RW) +[<Perm.R: 4>, <Perm.W: 2>] +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </section> <section id="flag"> <h3>Flag</h3> <p>The last variation is <a class="reference internal" href="../library/enum#enum.Flag" title="enum.Flag"><code>Flag</code></a>. Like <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a>, <a class="reference internal" href="../library/enum#enum.Flag" title="enum.Flag"><code>Flag</code></a> members can be combined using the bitwise operators (&, |, ^, ~). Unlike <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a>, they cannot be combined with, nor compared against, any other <a class="reference internal" href="../library/enum#enum.Flag" title="enum.Flag"><code>Flag</code></a> enumeration, nor <a class="reference internal" href="../library/functions#int" title="int"><code>int</code></a>. While it is possible to specify the values directly it is recommended to use <a class="reference internal" href="../library/enum#enum.auto" title="enum.auto"><code>auto</code></a> as the value and let <a class="reference internal" href="../library/enum#enum.Flag" title="enum.Flag"><code>Flag</code></a> select an appropriate value.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> <p>Like <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a>, if a combination of <a class="reference internal" href="../library/enum#enum.Flag" title="enum.Flag"><code>Flag</code></a> members results in no flags being set, the boolean evaluation is <a class="reference internal" href="../library/constants#False" title="False"><code>False</code></a>:</p> <pre data-language="python">>>> from enum import Flag, auto +>>> class Color(Flag): +... RED = auto() +... BLUE = auto() +... GREEN = auto() +... +>>> Color.RED & Color.GREEN +<Color: 0> +>>> bool(Color.RED & Color.GREEN) +False +</pre> <p>Individual flags should have values that are powers of two (1, 2, 4, 8, …), while combinations of flags will not:</p> <pre data-language="python">>>> class Color(Flag): +... RED = auto() +... BLUE = auto() +... GREEN = auto() +... WHITE = RED | BLUE | GREEN +... +>>> Color.WHITE +<Color.WHITE: 7> +</pre> <p>Giving a name to the “no flags set” condition does not change its boolean value:</p> <pre data-language="python">>>> class Color(Flag): +... BLACK = 0 +... RED = auto() +... BLUE = auto() +... GREEN = auto() +... +>>> Color.BLACK +<Color.BLACK: 0> +>>> bool(Color.BLACK) +False +</pre> <p><a class="reference internal" href="../library/enum#enum.Flag" title="enum.Flag"><code>Flag</code></a> members can also be iterated over:</p> <pre data-language="python">>>> purple = Color.RED | Color.BLUE +>>> list(purple) +[<Color.RED: 1>, <Color.BLUE: 2>] +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>For the majority of new code, <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> and <a class="reference internal" href="../library/enum#enum.Flag" title="enum.Flag"><code>Flag</code></a> are strongly recommended, since <a class="reference internal" href="../library/enum#enum.IntEnum" title="enum.IntEnum"><code>IntEnum</code></a> and <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a> break some semantic promises of an enumeration (by being comparable to integers, and thus by transitivity to other unrelated enumerations). <a class="reference internal" href="../library/enum#enum.IntEnum" title="enum.IntEnum"><code>IntEnum</code></a> and <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a> should be used only in cases where <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> and <a class="reference internal" href="../library/enum#enum.Flag" title="enum.Flag"><code>Flag</code></a> will not do; for example, when integer constants are replaced with enumerations, or for interoperability with other systems.</p> </div> </section> <section id="others"> <h3>Others</h3> <p>While <a class="reference internal" href="../library/enum#enum.IntEnum" title="enum.IntEnum"><code>IntEnum</code></a> is part of the <a class="reference internal" href="../library/enum#module-enum" title="enum: Implementation of an enumeration class."><code>enum</code></a> module, it would be very simple to implement independently:</p> <pre data-language="python">class IntEnum(int, Enum): + pass +</pre> <p>This demonstrates how similar derived enumerations can be defined; for example a <code>FloatEnum</code> that mixes in <a class="reference internal" href="../library/functions#float" title="float"><code>float</code></a> instead of <a class="reference internal" href="../library/functions#int" title="int"><code>int</code></a>.</p> <p>Some rules:</p> <ol class="arabic simple"> <li>When subclassing <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a>, mix-in types must appear before <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> itself in the sequence of bases, as in the <a class="reference internal" href="../library/enum#enum.IntEnum" title="enum.IntEnum"><code>IntEnum</code></a> example above.</li> <li>Mix-in types must be subclassable. For example, <a class="reference internal" href="../library/functions#bool" title="bool"><code>bool</code></a> and <a class="reference internal" href="../library/stdtypes#range" title="range"><code>range</code></a> are not subclassable and will throw an error during Enum creation if used as the mix-in type.</li> <li>While <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> can have members of any type, once you mix in an additional type, all the members must have values of that type, e.g. <a class="reference internal" href="../library/functions#int" title="int"><code>int</code></a> above. This restriction does not apply to mix-ins which only add methods and don’t specify another type.</li> <li>When another data type is mixed in, the <code>value</code> attribute is <em>not the same</em> as the enum member itself, although it is equivalent and will compare equal.</li> <li>A <code>data type</code> is a mixin that defines <code>__new__()</code>, or a <a class="reference internal" href="../library/dataclasses#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass</code></a> +</li> <li>%-style formatting: <code>%s</code> and <code>%r</code> call the <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> class’s <code>__str__()</code> and <code>__repr__()</code> respectively; other codes (such as <code>%i</code> or <code>%h</code> for IntEnum) treat the enum member as its mixed-in type.</li> <li> +<a class="reference internal" href="../reference/lexical_analysis#f-strings"><span class="std std-ref">Formatted string literals</span></a>, <a class="reference internal" href="../library/stdtypes#str.format" title="str.format"><code>str.format()</code></a>, and <a class="reference internal" href="../library/functions#format" title="format"><code>format()</code></a> will use the enum’s <code>__str__()</code> method.</li> </ol> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Because <a class="reference internal" href="../library/enum#enum.IntEnum" title="enum.IntEnum"><code>IntEnum</code></a>, <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a>, and <a class="reference internal" href="../library/enum#enum.StrEnum" title="enum.StrEnum"><code>StrEnum</code></a> are designed to be drop-in replacements for existing constants, their <code>__str__()</code> method has been reset to their data types’ <code>__str__()</code> method.</p> </div> </section> </section> <section id="when-to-use-new-vs-init"> <span id="new-vs-init"></span><h2>When to use <code>__new__()</code> vs. <code>__init__()</code> +</h2> <p><code>__new__()</code> must be used whenever you want to customize the actual value of the <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> member. Any other modifications may go in either <code>__new__()</code> or <code>__init__()</code>, with <code>__init__()</code> being preferred.</p> <p>For example, if you want to pass several items to the constructor, but only want one of them to be the value:</p> <pre data-language="python">>>> class Coordinate(bytes, Enum): +... """ +... Coordinate with binary codes that can be indexed by the int code. +... """ +... def __new__(cls, value, label, unit): +... obj = bytes.__new__(cls, [value]) +... obj._value_ = value +... obj.label = label +... obj.unit = unit +... return obj +... PX = (0, 'P.X', 'km') +... PY = (1, 'P.Y', 'km') +... VX = (2, 'V.X', 'km/s') +... VY = (3, 'V.Y', 'km/s') +... + +>>> print(Coordinate['PY']) +Coordinate.PY + +>>> print(Coordinate(3)) +Coordinate.VY +</pre> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p><em>Do not</em> call <code>super().__new__()</code>, as the lookup-only <code>__new__</code> is the one that is found; instead, use the data type directly.</p> </div> <section id="finer-points"> <h3>Finer Points</h3> <section id="supported-dunder-names"> <h4>Supported <code>__dunder__</code> names</h4> <p><code>__members__</code> is a read-only ordered mapping of <code>member_name</code>:<code>member</code> items. It is only available on the class.</p> <p><code>__new__()</code>, if specified, must create and return the enum members; it is also a very good idea to set the member’s <code>_value_</code> appropriately. Once all the members are created it is no longer used.</p> </section> <section id="supported-sunder-names"> <h4>Supported <code>_sunder_</code> names</h4> <ul class="simple"> <li> +<code>_name_</code> – name of the member</li> <li> +<code>_value_</code> – value of the member; can be set / modified in <code>__new__</code> +</li> <li> +<code>_missing_</code> – a lookup function used when a value is not found; may be overridden</li> <li> +<code>_ignore_</code> – a list of names, either as a <a class="reference internal" href="../library/stdtypes#list" title="list"><code>list</code></a> or a <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str</code></a>, that will not be transformed into members, and will be removed from the final class</li> <li> +<code>_order_</code> – used in Python 2/3 code to ensure member order is consistent (class attribute, removed during class creation)</li> <li> +<code>_generate_next_value_</code> – used by the <a class="reference internal" href="#functional-api">Functional API</a> and by <a class="reference internal" href="../library/enum#enum.auto" title="enum.auto"><code>auto</code></a> to get an appropriate value for an enum member; may be overridden</li> </ul> <div class="admonition note"> <p class="admonition-title">Note</p> <p>For standard <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> classes the next value chosen is the last value seen incremented by one.</p> <p>For <a class="reference internal" href="../library/enum#enum.Flag" title="enum.Flag"><code>Flag</code></a> classes the next value chosen will be the next highest power-of-two, regardless of the last value seen.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6: </span><code>_missing_</code>, <code>_order_</code>, <code>_generate_next_value_</code></p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7: </span><code>_ignore_</code></p> </div> <p>To help keep Python 2 / Python 3 code in sync an <code>_order_</code> attribute can be provided. It will be checked against the actual order of the enumeration and raise an error if the two do not match:</p> <pre data-language="python">>>> class Color(Enum): +... _order_ = 'RED GREEN BLUE' +... RED = 1 +... BLUE = 3 +... GREEN = 2 +... +Traceback (most recent call last): +... +TypeError: member order does not match _order_: + ['RED', 'BLUE', 'GREEN'] + ['RED', 'GREEN', 'BLUE'] +</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>In Python 2 code the <code>_order_</code> attribute is necessary as definition order is lost before it can be recorded.</p> </div> </section> <section id="private-names"> <h4>_Private__names</h4> <p><a class="reference internal" href="../reference/expressions#private-name-mangling"><span class="std std-ref">Private names</span></a> are not converted to enum members, but remain normal attributes.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11.</span></p> </div> </section> <section id="enum-member-type"> <h4> +<code>Enum</code> member type</h4> <p>Enum members are instances of their enum class, and are normally accessed as <code>EnumClass.member</code>. In certain situations, such as writing custom enum behavior, being able to access one member directly from another is useful, and is supported; however, in order to avoid name clashes between member names and attributes/methods from mixed-in classes, upper-case names are strongly recommended.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5.</span></p> </div> </section> <section id="creating-members-that-are-mixed-with-other-data-types"> <h4>Creating members that are mixed with other data types</h4> <p>When subclassing other data types, such as <a class="reference internal" href="../library/functions#int" title="int"><code>int</code></a> or <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str</code></a>, with an <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a>, all values after the <code>=</code> are passed to that data type’s constructor. For example:</p> <pre data-language="python">>>> class MyEnum(IntEnum): # help(int) -> int(x, base=10) -> integer +... example = '11', 16 # so x='11' and base=16 +... +>>> MyEnum.example.value # and hex(11) is... +17 +</pre> </section> <section id="boolean-value-of-enum-classes-and-members"> <h4>Boolean value of <code>Enum</code> classes and members</h4> <p>Enum classes that are mixed with non-<a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> types (such as <a class="reference internal" href="../library/functions#int" title="int"><code>int</code></a>, <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str</code></a>, etc.) are evaluated according to the mixed-in type’s rules; otherwise, all members evaluate as <a class="reference internal" href="../library/constants#True" title="True"><code>True</code></a>. To make your own enum’s boolean evaluation depend on the member’s value add the following to your class:</p> <pre data-language="python">def __bool__(self): + return bool(self.value) +</pre> <p>Plain <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> classes always evaluate as <a class="reference internal" href="../library/constants#True" title="True"><code>True</code></a>.</p> </section> <section id="enum-classes-with-methods"> <h4> +<code>Enum</code> classes with methods</h4> <p>If you give your enum subclass extra methods, like the <a class="reference internal" href="#planet">Planet</a> class below, those methods will show up in a <a class="reference internal" href="../library/functions#dir" title="dir"><code>dir()</code></a> of the member, but not of the class:</p> <pre data-language="python">>>> dir(Planet) +['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__'] +>>> dir(Planet.EARTH) +['__class__', '__doc__', '__module__', 'mass', 'name', 'radius', 'surface_gravity', 'value'] +</pre> </section> <section id="combining-members-of-flag"> <h4>Combining members of <code>Flag</code> +</h4> <p>Iterating over a combination of <a class="reference internal" href="../library/enum#enum.Flag" title="enum.Flag"><code>Flag</code></a> members will only return the members that are comprised of a single bit:</p> <pre data-language="python">>>> class Color(Flag): +... RED = auto() +... GREEN = auto() +... BLUE = auto() +... MAGENTA = RED | BLUE +... YELLOW = RED | GREEN +... CYAN = GREEN | BLUE +... +>>> Color(3) # named combination +<Color.YELLOW: 3> +>>> Color(7) # not named combination +<Color.RED|GREEN|BLUE: 7> +</pre> </section> <section id="flag-and-intflag-minutia"> <h4> +<code>Flag</code> and <code>IntFlag</code> minutia</h4> <p>Using the following snippet for our examples:</p> <pre data-language="python">>>> class Color(IntFlag): +... BLACK = 0 +... RED = 1 +... GREEN = 2 +... BLUE = 4 +... PURPLE = RED | BLUE +... WHITE = RED | GREEN | BLUE +... +</pre> <p>the following are true:</p> <ul> <li>single-bit flags are canonical</li> <li>multi-bit and zero-bit flags are aliases</li> <li> +<p>only canonical flags are returned during iteration:</p> <pre data-language="python">>>> list(Color.WHITE) +[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 4>] +</pre> </li> <li> +<p>negating a flag or flag set returns a new flag/flag set with the corresponding positive integer value:</p> <pre data-language="python">>>> Color.BLUE +<Color.BLUE: 4> + +>>> ~Color.BLUE +<Color.RED|GREEN: 3> +</pre> </li> <li> +<p>names of pseudo-flags are constructed from their members’ names:</p> <pre data-language="python">>>> (Color.RED | Color.GREEN).name +'RED|GREEN' +</pre> </li> <li> +<p>multi-bit flags, aka aliases, can be returned from operations:</p> <pre data-language="python">>>> Color.RED | Color.BLUE +<Color.PURPLE: 5> + +>>> Color(7) # or Color(-1) +<Color.WHITE: 7> + +>>> Color(0) +<Color.BLACK: 0> +</pre> </li> <li> +<p>membership / containment checking: zero-valued flags are always considered to be contained:</p> <pre data-language="python">>>> Color.BLACK in Color.WHITE +True +</pre> <p>otherwise, only if all bits of one flag are in the other flag will True be returned:</p> <pre data-language="python">>>> Color.PURPLE in Color.WHITE +True + +>>> Color.GREEN in Color.PURPLE +False +</pre> </li> </ul> <p>There is a new boundary mechanism that controls how out-of-range / invalid bits are handled: <code>STRICT</code>, <code>CONFORM</code>, <code>EJECT</code>, and <code>KEEP</code>:</p> <ul class="simple"> <li>STRICT –> raises an exception when presented with invalid values</li> <li>CONFORM –> discards any invalid bits</li> <li>EJECT –> lose Flag status and become a normal int with the given value</li> <li> +<p>KEEP –> keep the extra bits</p> <ul> <li>keeps Flag status and extra bits</li> <li>extra bits do not show up in iteration</li> <li>extra bits do show up in repr() and str()</li> </ul> </li> </ul> <p>The default for Flag is <code>STRICT</code>, the default for <code>IntFlag</code> is <code>EJECT</code>, and the default for <code>_convert_</code> is <code>KEEP</code> (see <code>ssl.Options</code> for an example of when <code>KEEP</code> is needed).</p> </section> </section> </section> <section id="how-are-enums-and-flags-different"> <span id="enum-class-differences"></span><h2>How are Enums and Flags different?</h2> <p>Enums have a custom metaclass that affects many aspects of both derived <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> classes and their instances (members).</p> <section id="enum-classes"> <h3>Enum Classes</h3> <p>The <a class="reference internal" href="../library/enum#enum.EnumType" title="enum.EnumType"><code>EnumType</code></a> metaclass is responsible for providing the <code>__contains__()</code>, <code>__dir__()</code>, <code>__iter__()</code> and other methods that allow one to do things with an <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> class that fail on a typical class, such as <code>list(Color)</code> or <code>some_enum_var in Color</code>. <a class="reference internal" href="../library/enum#enum.EnumType" title="enum.EnumType"><code>EnumType</code></a> is responsible for ensuring that various other methods on the final <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> class are correct (such as <code>__new__()</code>, <code>__getnewargs__()</code>, <code>__str__()</code> and <code>__repr__()</code>).</p> </section> <section id="flag-classes"> <h3>Flag Classes</h3> <p>Flags have an expanded view of aliasing: to be canonical, the value of a flag needs to be a power-of-two value, and not a duplicate name. So, in addition to the <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> definition of alias, a flag with no value (a.k.a. <code>0</code>) or with more than one power-of-two value (e.g. <code>3</code>) is considered an alias.</p> </section> <section id="enum-members-aka-instances"> <h3>Enum Members (aka instances)</h3> <p>The most interesting thing about enum members is that they are singletons. <a class="reference internal" href="../library/enum#enum.EnumType" title="enum.EnumType"><code>EnumType</code></a> creates them all while it is creating the enum class itself, and then puts a custom <code>__new__()</code> in place to ensure that no new ones are ever instantiated by returning only the existing member instances.</p> </section> <section id="flag-members"> <h3>Flag Members</h3> <p>Flag members can be iterated over just like the <a class="reference internal" href="../library/enum#enum.Flag" title="enum.Flag"><code>Flag</code></a> class, and only the canonical members will be returned. For example:</p> <pre data-language="python">>>> list(Color) +[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 4>] +</pre> <p>(Note that <code>BLACK</code>, <code>PURPLE</code>, and <code>WHITE</code> do not show up.)</p> <p>Inverting a flag member returns the corresponding positive value, rather than a negative value — for example:</p> <pre data-language="python">>>> ~Color.RED +<Color.GREEN|BLUE: 6> +</pre> <p>Flag members have a length corresponding to the number of power-of-two values they contain. For example:</p> <pre data-language="python">>>> len(Color.PURPLE) +2 +</pre> </section> </section> <section id="enum-cookbook"> <span id="id1"></span><h2>Enum Cookbook</h2> <p>While <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a>, <a class="reference internal" href="../library/enum#enum.IntEnum" title="enum.IntEnum"><code>IntEnum</code></a>, <a class="reference internal" href="../library/enum#enum.StrEnum" title="enum.StrEnum"><code>StrEnum</code></a>, <a class="reference internal" href="../library/enum#enum.Flag" title="enum.Flag"><code>Flag</code></a>, and <a class="reference internal" href="../library/enum#enum.IntFlag" title="enum.IntFlag"><code>IntFlag</code></a> are expected to cover the majority of use-cases, they cannot cover them all. Here are recipes for some different types of enumerations that can be used directly, or as examples for creating one’s own.</p> <section id="omitting-values"> <h3>Omitting values</h3> <p>In many use-cases, one doesn’t care what the actual value of an enumeration is. There are several ways to define this type of simple enumeration:</p> <ul class="simple"> <li>use instances of <a class="reference internal" href="../library/enum#enum.auto" title="enum.auto"><code>auto</code></a> for the value</li> <li>use instances of <a class="reference internal" href="../library/functions#object" title="object"><code>object</code></a> as the value</li> <li>use a descriptive string as the value</li> <li>use a tuple as the value and a custom <code>__new__()</code> to replace the tuple with an <a class="reference internal" href="../library/functions#int" title="int"><code>int</code></a> value</li> </ul> <p>Using any of these methods signifies to the user that these values are not important, and also enables one to add, remove, or reorder members without having to renumber the remaining members.</p> <section id="using-auto"> <h4>Using <a class="reference internal" href="../library/enum#enum.auto" title="enum.auto"><code>auto</code></a> +</h4> <p>Using <a class="reference internal" href="../library/enum#enum.auto" title="enum.auto"><code>auto</code></a> would look like:</p> <pre data-language="python">>>> class Color(Enum): +... RED = auto() +... BLUE = auto() +... GREEN = auto() +... +>>> Color.GREEN +<Color.GREEN: 3> +</pre> </section> <section id="using-object"> <h4>Using <a class="reference internal" href="../library/functions#object" title="object"><code>object</code></a> +</h4> <p>Using <a class="reference internal" href="../library/functions#object" title="object"><code>object</code></a> would look like:</p> <pre data-language="python">>>> class Color(Enum): +... RED = object() +... GREEN = object() +... BLUE = object() +... +>>> Color.GREEN +<Color.GREEN: <object object at 0x...>> +</pre> <p>This is also a good example of why you might want to write your own <code>__repr__()</code>:</p> <pre data-language="python">>>> class Color(Enum): +... RED = object() +... GREEN = object() +... BLUE = object() +... def __repr__(self): +... return "<%s.%s>" % (self.__class__.__name__, self._name_) +... +>>> Color.GREEN +<Color.GREEN> +</pre> </section> <section id="using-a-descriptive-string"> <h4>Using a descriptive string</h4> <p>Using a string as the value would look like:</p> <pre data-language="python">>>> class Color(Enum): +... RED = 'stop' +... GREEN = 'go' +... BLUE = 'too fast!' +... +>>> Color.GREEN +<Color.GREEN: 'go'> +</pre> </section> <section id="using-a-custom-new"> <h4>Using a custom <code>__new__()</code> +</h4> <p>Using an auto-numbering <code>__new__()</code> would look like:</p> <pre data-language="python">>>> class AutoNumber(Enum): +... def __new__(cls): +... value = len(cls.__members__) + 1 +... obj = object.__new__(cls) +... obj._value_ = value +... return obj +... +>>> class Color(AutoNumber): +... RED = () +... GREEN = () +... BLUE = () +... +>>> Color.GREEN +<Color.GREEN: 2> +</pre> <p>To make a more general purpose <code>AutoNumber</code>, add <code>*args</code> to the signature:</p> <pre data-language="python">>>> class AutoNumber(Enum): +... def __new__(cls, *args): # this is the only change from above +... value = len(cls.__members__) + 1 +... obj = object.__new__(cls) +... obj._value_ = value +... return obj +... +</pre> <p>Then when you inherit from <code>AutoNumber</code> you can write your own <code>__init__</code> to handle any extra arguments:</p> <pre data-language="python">>>> class Swatch(AutoNumber): +... def __init__(self, pantone='unknown'): +... self.pantone = pantone +... AUBURN = '3497' +... SEA_GREEN = '1246' +... BLEACHED_CORAL = () # New color, no Pantone code yet! +... +>>> Swatch.SEA_GREEN +<Swatch.SEA_GREEN: 2> +>>> Swatch.SEA_GREEN.pantone +'1246' +>>> Swatch.BLEACHED_CORAL.pantone +'unknown' +</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <code>__new__()</code> method, if defined, is used during creation of the Enum members; it is then replaced by Enum’s <code>__new__()</code> which is used after class creation for lookup of existing members.</p> </div> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p><em>Do not</em> call <code>super().__new__()</code>, as the lookup-only <code>__new__</code> is the one that is found; instead, use the data type directly – e.g.:</p> <pre data-language="python">obj = int.__new__(cls, value) +</pre> </div> </section> </section> <section id="orderedenum"> <h3>OrderedEnum</h3> <p>An ordered enumeration that is not based on <a class="reference internal" href="../library/enum#enum.IntEnum" title="enum.IntEnum"><code>IntEnum</code></a> and so maintains the normal <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> invariants (such as not being comparable to other enumerations):</p> <pre data-language="python">>>> class OrderedEnum(Enum): +... def __ge__(self, other): +... if self.__class__ is other.__class__: +... return self.value >= other.value +... return NotImplemented +... def __gt__(self, other): +... if self.__class__ is other.__class__: +... return self.value > other.value +... return NotImplemented +... def __le__(self, other): +... if self.__class__ is other.__class__: +... return self.value <= other.value +... return NotImplemented +... def __lt__(self, other): +... if self.__class__ is other.__class__: +... return self.value < other.value +... return NotImplemented +... +>>> class Grade(OrderedEnum): +... A = 5 +... B = 4 +... C = 3 +... D = 2 +... F = 1 +... +>>> Grade.C < Grade.A +True +</pre> </section> <section id="duplicatefreeenum"> <h3>DuplicateFreeEnum</h3> <p>Raises an error if a duplicate member value is found instead of creating an alias:</p> <pre data-language="python">>>> class DuplicateFreeEnum(Enum): +... def __init__(self, *args): +... cls = self.__class__ +... if any(self.value == e.value for e in cls): +... a = self.name +... e = cls(self.value).name +... raise ValueError( +... "aliases not allowed in DuplicateFreeEnum: %r --> %r" +... % (a, e)) +... +>>> class Color(DuplicateFreeEnum): +... RED = 1 +... GREEN = 2 +... BLUE = 3 +... GRENE = 2 +... +Traceback (most recent call last): + ... +ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN' +</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>This is a useful example for subclassing Enum to add or change other behaviors as well as disallowing aliases. If the only desired change is disallowing aliases, the <a class="reference internal" href="../library/enum#enum.unique" title="enum.unique"><code>unique()</code></a> decorator can be used instead.</p> </div> </section> <section id="planet"> <h3>Planet</h3> <p>If <code>__new__()</code> or <code>__init__()</code> is defined, the value of the enum member will be passed to those methods:</p> <pre data-language="python">>>> class Planet(Enum): +... MERCURY = (3.303e+23, 2.4397e6) +... VENUS = (4.869e+24, 6.0518e6) +... EARTH = (5.976e+24, 6.37814e6) +... MARS = (6.421e+23, 3.3972e6) +... JUPITER = (1.9e+27, 7.1492e7) +... SATURN = (5.688e+26, 6.0268e7) +... URANUS = (8.686e+25, 2.5559e7) +... NEPTUNE = (1.024e+26, 2.4746e7) +... def __init__(self, mass, radius): +... self.mass = mass # in kilograms +... self.radius = radius # in meters +... @property +... def surface_gravity(self): +... # universal gravitational constant (m3 kg-1 s-2) +... G = 6.67300E-11 +... return G * self.mass / (self.radius * self.radius) +... +>>> Planet.EARTH.value +(5.976e+24, 6378140.0) +>>> Planet.EARTH.surface_gravity +9.802652743337129 +</pre> </section> <section id="timeperiod"> <span id="enum-time-period"></span><h3>TimePeriod</h3> <p>An example to show the <code>_ignore_</code> attribute in use:</p> <pre data-language="python">>>> from datetime import timedelta +>>> class Period(timedelta, Enum): +... "different lengths of time" +... _ignore_ = 'Period i' +... Period = vars() +... for i in range(367): +... Period['day_%d' % i] = i +... +>>> list(Period)[:2] +[<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>] +>>> list(Period)[-2:] +[<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>] +</pre> </section> </section> <section id="subclassing-enumtype"> <span id="enumtype-examples"></span><h2>Subclassing EnumType</h2> <p>While most enum needs can be met by customizing <a class="reference internal" href="../library/enum#enum.Enum" title="enum.Enum"><code>Enum</code></a> subclasses, either with class decorators or custom functions, <a class="reference internal" href="../library/enum#enum.EnumType" title="enum.EnumType"><code>EnumType</code></a> can be subclassed to provide a different Enum experience.</p> </section> <div class="_attribution"> + <p class="_attribution-p"> + © 2001–2023 Python Software Foundation<br>Licensed under the PSF License.<br> + <a href="https://docs.python.org/3.12/howto/enum.html" class="_attribution-link">https://docs.python.org/3.12/howto/enum.html</a> + </p> +</div> |
