Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-04-06 12:13:13

0001 #! /usr/bin/env python3
0002 
0003 ##  Note: Please do not use or modify any data or functions with a
0004 ##  leading underscore.  If you "mess" with the internal structure,
0005 ##  the classes may not function as intended.
0006 
0007 class Enumerate (object):
0008     """Similar to C++'s 'enum', but with a few extra toys.  Takes a
0009     string with spaces in between the different 'enum' names (keys).
0010     If 'asInt' is true, then values will be integers (useful for array
0011     indicies).  Once created, the enum values can not be changed."""
0012 
0013     def __init__(self, names, prefix = '', asInt = False, intOffset = 0):
0014         biggest = smallest = ""
0015         self._keys = []
0016         self._valueDict = {}
0017         for count, name in enumerate (names.split()) :
0018             # make sure we don't already have this key
0019             if self.isValidKey (name):
0020                 raise RuntimeError("You can not duplicate Enum Names '%s'" % name)
0021             # set the value using the base class
0022             key = "%s_%s" % (prefix, name)
0023             if asInt:
0024                 key = count + intOffset
0025             object.__setattr__ (self, name, key)
0026             self._valueDict[key] = name
0027             self._keys.append (name)
0028 
0029 
0030     def isValidValue (self, value):
0031         """ Returns true if this value is a valid enum value"""
0032         return value in self._valueDict
0033 
0034 
0035     def isValidKey (self, key):
0036         """ Returns true if this value is a valid enum key"""
0037         return key in self.__dict__
0038 
0039 
0040     def valueToKey (self, value):
0041         """ Returns the key (if it exists) for a given enum value"""
0042         return self._valueDict.get (value, None)
0043 
0044 
0045     def keys (self):
0046         """ Returns copy of valid keys """
0047         # since this is a list, return a copy of it instead of the
0048         # list itself
0049         return self._keys [:]
0050 
0051 
0052     def __setattr__ (self, name, value):
0053         """Lets me set internal values, but throws an error if any of
0054         the enum values are changed"""
0055         if not name.startswith ("_"):
0056             # Once it's set, you can't change the values
0057             raise RuntimeError("You can not modify Enum values.")
0058         else:
0059             object.__setattr__ (self, name, value)
0060 
0061 
0062     def __call__ (self, key):
0063         return self.__dict__.get (key, None)
0064