Describe in detail access to enum values with [] and getattr
This commit is contained in:
parent
455e1fcc45
commit
d3c26c354d
26
pep-0435.txt
26
pep-0435.txt
|
@ -159,7 +159,7 @@ The ``Enum`` class supports iteration. Iteration order is undefined::
|
||||||
>>> [v.name for v in sorted(FiveColors, by_value)]
|
>>> [v.name for v in sorted(FiveColors, by_value)]
|
||||||
['red', 'green', 'blue', 'pink', 'cyan']
|
['red', 'green', 'blue', 'pink', 'cyan']
|
||||||
|
|
||||||
Iteration order over ``IntEnum`` enumerations are guaranteed to be
|
Iteration order over `IntEnum`_ enumerations are guaranteed to be
|
||||||
sorted by value.
|
sorted by value.
|
||||||
|
|
||||||
>>> class Toppings(IntEnum):
|
>>> class Toppings(IntEnum):
|
||||||
|
@ -185,10 +185,32 @@ Enumeration values are hashable, so they can be used in dictionaries and sets::
|
||||||
>>> apples
|
>>> apples
|
||||||
{<EnumValue: Colors.green [value=2]>: 'granny smith', <EnumValue: Colors.red [value=1]>: 'red delicious'}
|
{<EnumValue: Colors.green [value=2]>: 'granny smith', <EnumValue: Colors.red [value=1]>: 'red delicious'}
|
||||||
|
|
||||||
To programmatically access enumeration values, use ``getattr``::
|
Programmatic access to enum values
|
||||||
|
----------------------------------
|
||||||
|
|
||||||
|
Sometimes it's useful to access values in enumerations programmatically (i.e.
|
||||||
|
situations where ``Colors.red`` won't do because the exact color is not known
|
||||||
|
at program-writing time). ``Enum`` allows such access by value::
|
||||||
|
|
||||||
|
>>> Colors[1]
|
||||||
|
<EnumValue: Colors.red [value=1]>
|
||||||
|
>>> Colors[2]
|
||||||
|
<EnumValue: Colors.green [value=2]>
|
||||||
|
|
||||||
|
For consistency, an ``EnumValue`` can be used in the same access pattern::
|
||||||
|
|
||||||
|
>>> Colors[Colors.red]
|
||||||
|
<EnumValue: Colors.red [value=1]>
|
||||||
|
>>> Colors[Colors.green]
|
||||||
|
<EnumValue: Colors.green [value=2]>
|
||||||
|
|
||||||
|
If you want to access enum values by *name*, ``Enum`` works as expected with
|
||||||
|
``getattr``::
|
||||||
|
|
||||||
>>> getattr(Colors, 'red')
|
>>> getattr(Colors, 'red')
|
||||||
<EnumValue: Colors.red [value=1]>
|
<EnumValue: Colors.red [value=1]>
|
||||||
|
>>> getattr(Colors, 'green')
|
||||||
|
<EnumValue: Colors.green [value=2]>
|
||||||
|
|
||||||
Comparisons
|
Comparisons
|
||||||
-----------
|
-----------
|
||||||
|
|
Loading…
Reference in New Issue