The Gaudi Framework  v33r0 (d5ea422b)
_configurables.py
Go to the documentation of this file.
1 
12 from __future__ import absolute_import
13 
14 import sys
15 
16 _GLOBAL_INSTANCES = False
17 
18 
19 def useGlobalInstances(enable):
20  '''
21  Enable or disable the global instances database.
22 
23  By default global instances are enabled.
24  '''
25  global _GLOBAL_INSTANCES
26  if enable == _GLOBAL_INSTANCES:
27  return
28  if not enable:
29  assert not Configurable.instances, \
30  'Configurable instances DB not empty, cannot be disabled'
31  _GLOBAL_INSTANCES = enable
32 
33 
34 class Property(object):
35  '''
36  Descriptor class to implement validation of Configurable properties.
37  '''
38 
39  def __init__(self, cpp_type, default, doc='undocumented', semantics=None):
40  from .semantics import getSemanticsFor
41  self.semantics = getSemanticsFor(semantics or cpp_type)
42  self.default = default
43  self.__doc__ = doc
44 
45  @property
46  def cpp_type(self):
47  return self.semantics.cpp_type
48 
49  @property
50  def name(self):
51  return self.semantics.name
52 
53  def __get__(self, instance, owner):
54  if (self.name not in instance._properties
55  and hasattr(self.semantics, 'default')):
56  instance._properties[self.name] = self.semantics.default(
57  self.default)
58  return self.semantics.load(
59  instance._properties.get(self.name, self.default))
60 
61  def __set__(self, instance, value):
62  instance._properties[self.name] = self.semantics.store(value)
63 
64  def __delete__(self, instance):
65  del instance._properties[self.name]
66 
67  def __set_name__(self, owner, name):
68  self.semantics.name = name
69 
70  def __is_set__(self, instance, owner):
71  try:
72  value = instance._properties[self.name]
73  return self.semantics.is_set(value)
74  except KeyError:
75  return False
76 
77  def __opt_value__(self, instance, owner):
78  return self.semantics.opt_value(
79  instance._properties.get(self.name, self.default))
80 
81  def __merge__(self, instance, owner, value):
82  '''
83  Return "merge" (according to the semantic) of the value
84  in this property and the incoming value.
85  '''
86  if not self.__is_set__(instance, owner):
87  return value
88  return self.semantics.merge(self.__get__(instance, owner), value)
89 
90 
92  '''
93  Metaclass for Configurables.
94  '''
95 
96  def __new__(cls, name, bases, namespace, **kwds):
97  props = {
98  key: namespace[key]
99  for key in namespace if isinstance(namespace[key], Property)
100  }
101  if props:
102  doc = namespace.get('__doc__', '').rstrip()
103  doc += '\n\nProperties\n----------\n'
104  doc += '\n'.join([
105  '- {name}: {p.cpp_type} ({p.default!r})\n {p.__doc__}\n'.
106  format(name=n, p=props[n]) for n in props
107  ])
108  namespace['__doc__'] = doc
109  if sys.version_info < (3, 6): # pragma no cover
110  for n in props:
111  namespace[n].__set_name__(None, n)
112  namespace['_descriptors'] = props
113  slots = set(namespace.get('__slots__', []))
114  slots.update(['_properties', '_name'])
115  namespace['__slots__'] = tuple(slots)
116  result = type.__new__(cls, name, bases, namespace)
117  return result
118 
119 
120 def opt_repr(value):
121  '''
122  String representation of the value, such that it can be consumed be the
123  Gaudi option parsers.
124  '''
125  if hasattr(value, '__opt_repr__'):
126  return value.__opt_repr__()
127  return repr(value)
128 
129 
130 if sys.version_info >= (3, ): # pragma no cover
131  exec ('class ConfigMetaHelper(metaclass=ConfigurableMeta):\n pass')
132 else: # pragma no cover
133 
134  class ConfigMetaHelper(object):
135  __metaclass__ = ConfigurableMeta
136 
137 
139  '''
140  Base class for all configurable instances.
141  '''
142  instances = {}
143 
144  def __init__(self, name=None, **kwargs):
145  self._name = None
146  self._properties = {}
147  if 'parent' in kwargs:
148  parent = kwargs.pop('parent')
149  if isinstance(parent,
150  basestring if sys.version_info[0] == 2 else str):
151  parent = self.instances[parent]
152  if not name:
153  raise TypeError('name is needed when a parent is specified')
154  name = '{}.{}'.format(parent.name, name)
155  if name:
156  self.name = name
157  elif not _GLOBAL_INSTANCES:
158  self.name = self.__cpp_type__
159  for key, value in kwargs.items():
160  setattr(self, key, value)
161 
162  @classmethod
163  def getInstance(cls, name):
164  return cls.instances.get(name) or cls(name)
165 
166  @property
167  def name(self):
168  if not self._name:
169  raise AttributeError('{!r} instance was not named yet'.format(
170  type(self).__name__))
171  return self._name
172 
173  @name.setter
174  def name(self, value):
175  if value == self._name:
176  return # it's already the name of the instance, nothing to do
177  if not isinstance(value, basestring
178  if sys.version_info[0] == 2 else str) or not value:
179  raise TypeError('expected string, got {} instead'.format(
180  type(value).__name__))
181  if _GLOBAL_INSTANCES:
182  if value in self.instances:
183  raise ValueError('name {!r} already used'.format(value))
184  if self._name in self.instances:
185  del self.instances[self._name]
186  self._name = value
187  self.instances[value] = self
188  else:
189  self._name = value
190 
191  @name.deleter
192  def name(self):
193  if _GLOBAL_INSTANCES:
194  # check if it was set
195  del self.instances[self.name]
196  self._name = None
197  else:
198  raise TypeError('name attribute cannot be deleted')
199 
200  def __repr__(self):
201  args = []
202  try:
203  args.append(repr(self.name))
204  except AttributeError:
205  pass # no name
206  args.extend(
207  '{}={!r}'.format(*item) for item in self._properties.items())
208  return '{}({})'.format(type(self).__name__, ', '.join(args))
209 
210  def __getstate__(self):
211  state = {'properties': self._properties}
212  try:
213  state['name'] = self.name
214  except AttributeError:
215  pass # no name
216  return state
217 
218  def __setstate__(self, state):
219  self.__init__(state.get('name'), **state['properties'])
220 
221  def __opt_value__(self):
222  if self.__cpp_type__ == self.name:
223  return self.__cpp_type__
224  return '{}/{}'.format(self.__cpp_type__, self.name)
225 
226  def __opt_properties__(self, explicit_defaults=False):
227  name = self.name
228  out = {}
229  for p in self._descriptors.values():
230  if explicit_defaults or p.__is_set__(self, type(self)):
231  out['.'.join([name, p.name])] = opt_repr(
232  p.__opt_value__(self, type(self)))
233  return out
234 
235  def is_property_set(self, propname):
236  return self._descriptors[propname].__is_set__(self, type(self))
237 
238  def merge(self, other):
239  '''
240  Merge the properties of the other instance into the current one.
241 
242  The two instances have to be of the same type, have the same name
243  (or both unnamed) and the settings must be mergable (according to
244  their semantics).
245  '''
246  if type(self) is not type(other):
247  raise TypeError(
248  'cannot merge instance of {} into an instance of {}'.format(
249  type(other).__name__,
250  type(self).__name__))
251  if hasattr(self, 'name') != hasattr(other, 'name'):
252  raise ValueError(
253  'cannot merge a named configurable with an unnamed one')
254  if hasattr(self, 'name') and (self.name != other.name):
255  raise ValueError(
256  'cannot merge configurables with different names ({} and {})'.
257  format(self.name, other.name))
258 
259  for name in other._descriptors:
260  if not other.is_property_set(name):
261  continue
262  try:
263  setattr(
264  self, name, self._descriptors[name].__merge__(
265  self, type(self), getattr(other, name)))
266  except ValueError as err:
267  raise ValueError(
268  'conflicting settings for property {} of {}: {}'.format(
269  name, self.name
270  if hasattr(self, 'name') else type(self).__name__,
271  str(err)))
272 
273  return self
274 
275 
276 def makeConfigurableClass(name, **namespace):
277  '''
278  Create a Configurable specialization.
279  '''
280  properties = namespace.pop('properties', {})
281  namespace.update(
282  {pname: Property(*pargs)
283  for pname, pargs in properties.items()})
284 
285  return type(name, (Configurable, ), namespace)
286 
287 
288 def all_options(explicit_defaults=False):
289  '''
290  Return a dictionary with all explicitly set options, or with also the
291  defaults if explicit_defaults is set to True.
292  '''
293  opts = {}
294  for c in Configurable.instances.values():
295  opts.update(c.__opt_properties__(explicit_defaults))
296  return opts
def __opt_properties__(self, explicit_defaults=False)
GAUDI_API std::string format(const char *,...)
MsgStream format utility "a la sprintf(...)".
Definition: MsgStream.cpp:119
def __is_set__(self, instance, owner)
def __new__(cls, name, bases, namespace, **kwds)
def getSemanticsFor(cpp_type, name=None)
Definition: semantics.py:409
int merge(const char *target, const char *source, bool fixup=false, bool dbg=true)
Definition: merge.C:430
def __set__(self, instance, value)
auto get(const Handle &handle, const Algo &, const EventContext &) -> decltype(details::deref(handle.get()))
def __init__(self, name=None, **kwargs)
def __init__(self, cpp_type, default, doc='undocumented', semantics=None)
def all_options(explicit_defaults=False)
def __merge__(self, instance, owner, value)
def __set_name__(self, owner, name)
def __opt_value__(self, instance, owner)
def __get__(self, instance, owner)
def makeConfigurableClass(name, **namespace)