Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Simulating Enumerations in Python

Credit: Will Ware

Problem

You want to define an enumeration in the spirit of C’s enum type.

Solution

Python’s introspection facilities let you add a version of enum, even though Python, as a language, does not support this construct:

import types, string, pprint, exceptions

class EnumException(exceptions.Exception):
    pass

class Enumeration:
    def _ _init_ _(self, name, enumList, valuesAreUnique=1):
        self._ _doc_ _ = name
        lookup = { }
        reverseLookup = { }
        i = 0
        uniqueNames = {}
        uniqueValues = {}
        for x in enumList:
            if type(x) == types.TupleType:
                x, i = x
            if type(x) != types.StringType:
                raise EnumException, "enum name is not a string: " + x
            if type(i) != types.IntType:
                raise EnumException, "enum value is not an integer: " + i
            if uniqueNames.has_key(x):
                raise EnumException, "enum name is not unique: " + x
            if valuesAreUnique and uniqueValues.has_key(i):
                raise EnumException, "enum value is not unique for " + x
            uniqueNames[x] = 1
            uniqueValues[i] = 1
            lookup[x] = i
            reverseLookup[i] = x
            i = i + 1
        self.lookup = lookup
        self.reverseLookup = reverseLookup
    def _ _getattr_ _(self, attr):
        try: return self.lookup[attr]
        except KeyError: raise AttributeError
    def whatis(self, value):
        return self.reverseLookup[value]

Discussion

In C, enum lets you declare several constants, typically with unique values (although you can also explicitly arrange for a value to be duplicated under two different names), without necessarily specifying the actual values (except when you want it to). ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata