Make it clear that iteration order is undefined for Enums but defined for
IntEnums.
This commit is contained in:
parent
50fe21c75b
commit
8ea4fd96b4
25
pep-0435.txt
25
pep-0435.txt
|
@ -147,18 +147,37 @@ The str and repr of the enumeration class also provides useful information::
|
|||
>>> print(repr(Colors))
|
||||
<Colors {red: 1, green: 2, blue: 3}>
|
||||
|
||||
The ``Enum`` class supports iteration. Iteration is defined as the
|
||||
sorted order of the item values::
|
||||
The ``Enum`` class supports iteration. Iteration order is undefined::
|
||||
|
||||
>>> from operator import attrgetter
|
||||
>>> by_value = attrgetter('value')
|
||||
>>> class FiveColors(Enum):
|
||||
... pink = 4
|
||||
... cyan = 5
|
||||
... green = 2
|
||||
... blue = 3
|
||||
... red = 1
|
||||
>>> [v.name for v in FiveColors]
|
||||
>>> [v.name for v in sorted(FiveColors, by_value)]
|
||||
['red', 'green', 'blue', 'pink', 'cyan']
|
||||
|
||||
Iteration order over ``IntEnum`` enumerations are guaranteed to be
|
||||
sorted by value.
|
||||
|
||||
>>> class Toppings(IntEnum):
|
||||
... anchovies = 4
|
||||
... black_olives = 8
|
||||
... cheese = 2
|
||||
... dried_tomatoes = 16
|
||||
... eggplant = 1
|
||||
|
||||
>>> for value in Toppings:
|
||||
... print(value.name, '=', value.value)
|
||||
eggplant = 1
|
||||
cheese = 2
|
||||
anchovies = 4
|
||||
black_olives = 8
|
||||
dried_tomatoes = 16
|
||||
|
||||
Enumeration values are hashable, so they can be used in dictionaries and sets::
|
||||
|
||||
>>> apples = {}
|
||||
|
|
Loading…
Reference in New Issue