CMS 3D CMS Logo

Enumerate.py
Go to the documentation of this file.
1 #! /usr/bin/env python3
2 
3 
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 
resolutioncreator_cfi.object
object
Definition: resolutioncreator_cfi.py:4
Enumerate.Enumerate.__call__
def __call__(self, key)
Definition: Enumerate.py:62
Enumerate.Enumerate.isValidKey
def isValidKey(self, key)
Definition: Enumerate.py:35
Enumerate.Enumerate._valueDict
_valueDict
Definition: Enumerate.py:16
Enumerate.Enumerate.valueToKey
def valueToKey(self, value)
Definition: Enumerate.py:40
Enumerate.Enumerate.isValidValue
def isValidValue(self, value)
Definition: Enumerate.py:30
Enumerate.Enumerate
Note: Please do not use or modify any data or functions with a leading underscore.
Definition: Enumerate.py:7
Enumerate.Enumerate._keys
_keys
Definition: Enumerate.py:15
Enumerate.Enumerate.__setattr__
def __setattr__(self, name, value)
Definition: Enumerate.py:52
Enumerate.Enumerate.__init__
def __init__(self, names, prefix='', asInt=False, intOffset=0)
Definition: Enumerate.py:13
Enumerate.Enumerate.keys
def keys(self)
Definition: Enumerate.py:45