[Python-checkins] peps: Make it clear that iteration order is undefined for Enums but defined for
barry.warsaw
python-checkins at python.org
Fri Apr 12 17:11:08 CEST 2013
http://hg.python.org/peps/rev/57f9a04d5994
changeset: 4851:57f9a04d5994
user: Barry Warsaw <barry at python.org>
date: Fri Apr 12 10:53:42 2013 -0400
summary:
Make it clear that iteration order is undefined for Enums but defined for
IntEnums.
files:
pep-0435.txt | 25 ++++++++++++++++++++++---
1 files changed, 22 insertions(+), 3 deletions(-)
diff --git a/pep-0435.txt b/pep-0435.txt
--- a/pep-0435.txt
+++ b/pep-0435.txt
@@ -147,18 +147,37 @@
>>> 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 = {}
--
Repository URL: http://hg.python.org/peps
More information about the Python-checkins
mailing list