summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGeorg Brandl <georg@python.org>2008-03-28 12:58:26 +0000
committerGeorg Brandl <georg@python.org>2008-03-28 12:58:26 +0000
commitd289ea6df96e9e24e17914070fd5c2594e44413e (patch)
tree305923730679b3524f1ae04cad5424a940abfdf3
parent489343e948516c5a010eb55b154a99c5b3a7004c (diff)
downloadcpython-git-d289ea6df96e9e24e17914070fd5c2594e44413e.tar.gz
#2502: add example how to do enum types with named tuples.
-rw-r--r--Doc/library/collections.rst10
1 files changed, 10 insertions, 0 deletions
diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst
index f07ac2535b..361da71430 100644
--- a/Doc/library/collections.rst
+++ b/Doc/library/collections.rst
@@ -567,6 +567,16 @@ by the :mod:`csv` or :mod:`sqlite3` modules::
for emp in map(EmployeeRecord._make, cursor.fetchall()):
print emp.name, emp.title
+Named tuples can also be used to generate enumerated constants:
+
+.. testcode::
+
+ def enum(*names):
+ return namedtuple('Enum', ' '.join(names))(*range(len(names)))
+
+ Status = enum('open', 'pending', 'closed')
+ assert (0, 1, 2) == (Status.open, Status.pending, Status.closed)
+
In addition to the methods inherited from tuples, named tuples support
three additional methods and one attribute. To prevent conflicts with
field names, the method and attribute names start with an underscore.