CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
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, \
21  "You can not duplicate Enum Names '%s'" % name
22  # set the value using the base class
23  key = "%s_%s" % (prefix, name)
24  if asInt:
25  key = count + intOffset
26  object.__setattr__ (self, name, key)
27  self._valueDict[key] = name
28  self._keys.append (name)
29 
30 
31  def isValidValue (self, value):
32  """ Returns true if this value is a valid enum value"""
33  return self._valueDict.has_key (value)
34 
35 
36  def isValidKey (self, key):
37  """ Returns true if this value is a valid enum key"""
38  return self.__dict__.has_key (key)
39 
40 
41  def valueToKey (self, value):
42  """ Returns the key (if it exists) for a given enum value"""
43  return self._valueDict.get (value, None)
44 
45 
46  def keys (self):
47  """ Returns copy of valid keys """
48  # since this is a list, return a copy of it instead of the
49  # list itself
50  return self._keys [:]
51 
52 
53  def __setattr__ (self, name, value):
54  """Lets me set internal values, but throws an error if any of
55  the enum values are changed"""
56  if not name.startswith ("_"):
57  # Once it's set, you can't change the values
58  raise RuntimeError, "You can not modify Enum values."
59  else:
60  object.__setattr__ (self, name, value)
61 
62 
63  def __call__ (self, key):
64  return self.__dict__.get (key, None)
65 
Note: Please do not use or modify any data or functions with a leading underscore.
Definition: Enumerate.py:7
list object
Definition: dbtoconf.py:77