The Gaudi Framework  v29r0 (ff2e7097)
ConfigurableMeta.py
Go to the documentation of this file.
1 # File: AthenaCommon/python/ConfigurableMeta.py
2 # Author: Wim Lavrijsen (WLavrijsen@lbl.gov)
3 
4 import GaudiKernel.PropertyProxy as PropertyProxy
5 
6 
7 # data
8 __version__ = '1.0.1'
9 __author__ = 'Wim Lavrijsen (WLavrijsen@lbl.gov)'
10 
11 __all__ = ['ConfigurableMeta']
12 
13 # this metaclass installs PropertyProxy descriptors for Gaudi properties
14 
15 
17  """The setting of Gaudi component properties needs to be deferred and
18  history of who set what where needs to be collected. This is done
19  by using PropertyProxy descriptors rather than the default ones."""
20 
21  def __new__(self, name, bases, dct):
22  # enfore use of classmethod for getType() and setDefaults()
23  if 'getType' in dct and not isinstance(dct['getType'], classmethod):
24  dct['getType'] = classmethod(dct['getType'])
25 
26  if 'setDefaults' in dct and not isinstance(dct['setDefaults'], classmethod):
27  dct['setDefaults'] = classmethod(dct['setDefaults'])
28 
29  # collect what are properties (basically, any public name; C++ variables
30  # shouldn't start with an '_' because of portability constraints, hence
31  # it is safe to assume that any such vars are python private ones)
32  newclass = type.__new__(self, name, bases, dct)
33 
34  # cache references of instances by name for duplicate removal
35  newclass.configurables = {}
36 
37  # loop over slots, which are all assumed to be properties, create proxies, defaults
38  properties = {}
39  slots = dct.get('__slots__')
40  if slots:
41  props = [x for x in slots if x[0] != '_']
42  propDict = dct.get('_propertyDocDct')
43  for prop in props:
44  docString = propDict and propDict.get(prop)
45  if type(slots) == dict:
46  default = slots[prop]
47  else:
48  default = None
49  proxy = PropertyProxy.PropertyProxyFactory(
50  getattr(newclass, prop), docString, default)
51 
52  properties[prop] = proxy
53  setattr(newclass, prop, proxy)
54 
55  # complete set of properties includes those from base classes
56  for base in bases:
57  try:
58  bprops = base._properties.copy()
59  bprops.update(properties)
60  properties = bprops
61  except AttributeError:
62  pass
63 
64  newclass._properties = properties
65 
66  return newclass
67 
68  def __call__(cls, *args, **kwargs):
69  """To Gaudi, any object with the same type/name is the same object. Hence,
70  this is mimicked in the configuration: instantiating a new Configurable
71  of a type with the same name will return the same instance."""
72 
73  # Get the instance: `singleton' logic needs to be in __new__, not here,
74  # for compatibililty with pickling.)
75  cfg = cls.__new__(cls, *args, **kwargs)
76 
77  # Initialize the object, if not done already.
78  if not hasattr(cfg, '_initok') or not cfg._initok:
79  cls.__init__(cfg, *args, **kwargs)
80 
81  return cfg