[Python-checkins] peps: Describe in detail access to enum values with [] and getattr
eli.bendersky
python-checkins at python.org
Sat Apr 13 04:55:17 CEST 2013
http://hg.python.org/peps/rev/fd006d852c3f
changeset: 4853:fd006d852c3f
user: Eli Bendersky <eliben at gmail.com>
date: Fri Apr 12 19:54:37 2013 -0700
summary:
Describe in detail access to enum values with [] and getattr
files:
pep-0435.txt | 26 ++++++++++++++++++++++++--
1 files changed, 24 insertions(+), 2 deletions(-)
diff --git a/pep-0435.txt b/pep-0435.txt
--- a/pep-0435.txt
+++ b/pep-0435.txt
@@ -159,7 +159,7 @@
>>> [v.name for v in sorted(FiveColors, by_value)]
['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.
>>> class Toppings(IntEnum):
@@ -185,10 +185,32 @@
>>> apples
{<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')
<EnumValue: Colors.red [value=1]>
+ >>> getattr(Colors, 'green')
+ <EnumValue: Colors.green [value=2]>
Comparisons
-----------
--
Repository URL: http://hg.python.org/peps
More information about the Python-checkins
mailing list