]> granicus.if.org Git - python/commitdiff
#2502: add example how to do enum types with named tuples.
authorGeorg Brandl <georg@python.org>
Fri, 28 Mar 2008 12:58:26 +0000 (12:58 +0000)
committerGeorg Brandl <georg@python.org>
Fri, 28 Mar 2008 12:58:26 +0000 (12:58 +0000)
Doc/library/collections.rst

index f07ac2535b9733be2cbe88c87f45daa8911ce6fe..361da71430b739fa92fbb1af53347c94eeb9709d 100644 (file)
@@ -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.