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