CMS 3D CMS Logo

Enumerate.py
Go to the documentation of this file.
1 #! /usr/bin/env python
2 
3 ## Note: Please do not use or modify any data or functions with a
4 ## leading underscore. If you "mess" with the internal structure,
5 ## the classes may not function as intended.
6 
7 class Enumerate (object):
8  """Similar to C++'s 'enum', but with a few extra toys. Takes a
9  string with spaces in between the different 'enum' names (keys).
10  If 'asInt' is true, then values will be integers (useful for array
11  indicies). Once created, the enum values can not be changed."""
12 
13  def __init__(self, names, prefix = '', asInt = False, intOffset = 0):
14  biggest = smallest = ""
15  self._keys = []
16  self._valueDict = {}
17  for count, name in enumerate (names.split()) :
18  # make sure we don't already have this key
19  if self.isValidKey (name):
20  raise RuntimeError("You can not duplicate Enum Names '%s'" % name)
21  # set the value using the base class
22  key = "%s_%s" % (prefix, name)
23  if asInt:
24  key = count + intOffset
25  object.__setattr__ (self, name, key)
26  self._valueDict[key] = name
27  self._keys.append (name)
28 
29 
30  def isValidValue (self, value):
31  """ Returns true if this value is a valid enum value"""
32  return value in self._valueDict
33 
34 
35  def isValidKey (self, key):
36  """ Returns true if this value is a valid enum key"""
37  return key in self.__dict__
38 
39 
40  def valueToKey (self, value):
41  """ Returns the key (if it exists) for a given enum value"""
42  return self._valueDict.get (value, None)
43 
44 
45  def keys (self):
46  """ Returns copy of valid keys """
47  # since this is a list, return a copy of it instead of the
48  # list itself
49  return self._keys [:]
50 
51 
52  def __setattr__ (self, name, value):
53  """Lets me set internal values, but throws an error if any of
54  the enum values are changed"""
55  if not name.startswith ("_"):
56  # Once it's set, you can't change the values
57  raise RuntimeError("You can not modify Enum values.")
58  else:
59  object.__setattr__ (self, name, value)
60 
61 
62  def __call__ (self, key):
63  return self.__dict__.get (key, None)
64 
def valueToKey(self, value)
Definition: Enumerate.py:40
Note: Please do not use or modify any data or functions with a leading underscore.
Definition: Enumerate.py:7
def isValidValue(self, value)
Definition: Enumerate.py:30
def __init__(self, names, prefix='', asInt=False, intOffset=0)
Definition: Enumerate.py:13
def __setattr__(self, name, value)
Definition: Enumerate.py:52
def keys(self)
Definition: Enumerate.py:45
def __call__(self, key)
Definition: Enumerate.py:62
def isValidKey(self, key)
Definition: Enumerate.py:35