CMS 3D CMS Logo

Enumerate.py

Go to the documentation of this file.
00001 #! /usr/bin/env python
00002 
00003 ##  Note: Please do not use or modify any data or functions with a
00004 ##  leading underscore.  If you "mess" with the internal structure,
00005 ##  the classes may not function as intended.
00006 
00007 class Enumerate (object):
00008     """Similar to C++'s 'enum', but with a few extra toys.  Takes a
00009     string with spaces in between the different 'enum' names (keys).
00010     If 'asInt' is true, then values will be integers (useful for array
00011     indicies).  Once created, the enum values can not be changed."""
00012 
00013     def __init__(self, names, prefix = '', asInt = False, intOffset = 0):
00014         biggest = smallest = ""
00015         self._keys = []
00016         self._valueDict = {}
00017         for count, name in enumerate (names.split()) :
00018             # make sure we don't already have this key
00019             if self.isValidKey (name):
00020                 raise RuntimeError, \
00021                       "You can not duplicate Enum Names '%s'" % name
00022             # set the value using the base class
00023             key = "%s_%s" % (prefix, name)
00024             if asInt:
00025                 key = count + intOffset
00026             object.__setattr__ (self, name, key)
00027             self._valueDict[key] = name
00028             self._keys.append (name)
00029 
00030 
00031     def isValidValue (self, value):
00032         """ Returns true if this value is a valid enum value"""
00033         return self._valueDict.has_key (value)
00034 
00035 
00036     def isValidKey (self, key):
00037         """ Returns true if this value is a valid enum key"""
00038         return self.__dict__.has_key (key)
00039 
00040 
00041     def valueToKey (self, value):
00042         """ Returns the key (if it exists) for a given enum value"""
00043         return self._valueDict.get (value, None)
00044 
00045 
00046     def keys (self):
00047         """ Returns copy of valid keys """
00048         # since this is a list, return a copy of it instead of the
00049         # list itself
00050         return self._keys [:]
00051 
00052 
00053     def __setattr__ (self, name, value):
00054         """Lets me set internal values, but throws an error if any of
00055         the enum values are changed"""
00056         if not name.startswith ("_"):
00057             # Once it's set, you can't change the values
00058             raise RuntimeError, "You can not modify Enum values."
00059         else:
00060             object.__setattr__ (self, name, value)
00061 
00062 
00063     def __call__ (self, key):
00064         return self.__dict__.get (key, None)
00065 

Generated on Tue Jun 9 17:36:32 2009 for CMSSW by  doxygen 1.5.4