The Gaudi Framework  master (9f3f8895)
Loading...
Searching...
No Matches
GaudiKernel.Configurable.Configurable Class Reference
Inheritance diagram for GaudiKernel.Configurable.Configurable:
Collaboration diagram for GaudiKernel.Configurable.Configurable:

Classes

class  DefaultName

Public Member Functions

 __new__ (cls, *args, **kwargs)
 __init__ (self, name=DefaultName)
 __getstate__ (self)
 __getnewargs__ (self)
 __setstate__ (self, dict)
 __len__ (self)
 __iter__ (self)
 __deepcopy__ (self, memo)
 __iadd__ (self, configs, descr=None)
 __getattr__ (self, attr)
 __setattr__ (self, name, value)
 __delattr__ (self, attr)
 __bool__ (self)
 remove (self, items)
 removeAll (self)
 copyChild (self, child)
 setParent (self, parentName)
 getParent (self)
 hasParent (self, parent)
 copyChildAndSetParent (self, cfg, parent)
 getChildren (self)
 getTools (self)
 children (self)
 getAllChildren (self)
 getSequence (self)
 setup (self)
 getProperties (self)
 getPropertiesWithDescription (self)
 getValuedProperties (self)
 properties (self)
 getDefaultProperties (cls)
 getDefaultProperty (cls, name)
 getProp (self, name)
 setProp (self, name, value)
 isPropertySet (self, name)
 getType (cls)
 getName (self)
 name (self)
 getJobOptName (self)
 isPublic (self)
 jobOptName (self)
 getFullName (self)
 getFullJobOptName (self)
 getPrintTitle (self)
 getTitleName (self)
 setDefaults (cls, handle)
 clone (self, name=None, **kwargs)
 splitName (self)
 addTool (self, tool, name=None)
 __repr__ (self)
 __str__ (self, indent=0, headerLastIndentUnit=indentUnit)
 isApplicable (self)
Public Member Functions inherited from GaudiKernel.ConfigurableMeta.ConfigurableMeta
 __new__ (self, name, bases, dct)
 __call__ (cls, *args, **kwargs)

Public Attributes

 configurables

Static Public Attributes

 propertyNoValue
str indentUnit = "| "
int printHeaderWidth = 100
int printHeaderPre = 5
dict allConfigurables = {}
dict configurableServices = {}

Protected Member Functions

 _isInSetDefaults (self)

Static Protected Member Functions

 _printHeader (indentStr, title)
 _printFooter (indentStr, title)

Protected Attributes

 _name = self.__class__.DefaultedName
bool _inSetDefaults = False
bool _initok = True
bool _setupok = False
bool _unpickling = False
 _properties

Static Protected Attributes

bool _configurationLocked = False

Private Member Functions

 __setupServices (self)
 __setupDlls (self)
 __setupDefaults (self)

Private Attributes

 __name__
 __bases__
list __children = []
dict __tools = {}
 __class__

Static Private Attributes

tuple __slots__

Detailed Description

Base class for Gaudi components that implement the IProperty interface.
Provides most of the boilerplate code, but the actual useful classes
are its derived ConfigurableAlgorithm, ConfigurableService, and
ConfigurableAlgTool.

Definition at line 154 of file Configurable.py.

Constructor & Destructor Documentation

◆ __init__()

GaudiKernel.Configurable.Configurable.__init__ ( self,
name = DefaultName )

Definition at line 343 of file Configurable.py.

343 def __init__(self, name=DefaultName):
344 # check class readiness, all required overloads should be there now
345 klass = self.__class__
346
347 # this is an abstract class
348 if klass == Configurable:
349 raise TypeError(f"{Configurable} is an ABC and can not be instantiated")
350
351 # the following methods require overloading
352 # NOT YET meths = { 'getServices' : 1, # retrieve list of services to configure
353 meths = {
354 "getDlls": 1, # provide list of Dlls to load
355 "getGaudiType": 1, # return string describing component class
356 "getHandle": 1,
357 } # provide access to C++ side component instance
358 # 'getType' : 1 } # return the type of the actual C++ component
359
360 for meth, nArgs in meths.items():
361 try:
362 f = getattr(klass, meth)
363 except AttributeError:
364 raise NotImplementedError(f"{meth} is missing in class {klass}")
365
366 # in addition, verify the number of arguments w/o defaults
367 nargcount = f.__code__.co_argcount
368 fdefaults = f.__defaults__
369 ndefaults = fdefaults and len(fdefaults) or 0
370 if not nargcount - ndefaults <= nArgs <= nargcount:
371 raise TypeError(f"{klass}.{meth} requires exactly {nArgs} arguments")
372
373 # for using this Configurable as a (Gaudi) sequence
374 self.__children = []
375 self.__tools = {}
376
377 # know who we are
378 if name == Configurable.DefaultName:
379 if hasattr(self.__class__, "DefaultedName"):
380 self._name = self.__class__.DefaultedName
381 else:
382 self._name = self.getType()
383 else:
384 self._name = name
385
386 # set to True when collecting defaults, False otherwise
387 self._inSetDefaults = False
388
389 # for later, in case __init__ itself is overridden
390 self._initok = True
391
392 # for debugging purposes (temporary)
393 self._setupok = False
394
395 # used to prevent spurious deprecation warnings when unpickling
396 self._unpickling = False
397

Member Function Documentation

◆ __bool__()

GaudiKernel.Configurable.Configurable.__bool__ ( self)

Definition at line 544 of file Configurable.py.

544 def __bool__(self):
545 return True
546

◆ __deepcopy__()

GaudiKernel.Configurable.Configurable.__deepcopy__ ( self,
memo )

Definition at line 439 of file Configurable.py.

439 def __deepcopy__(self, memo):
440 newconf = object.__new__(self.__class__)
441 self.__class__.__init__(newconf, self.getName())
442
443 for proxy in self._properties.values():
444 try:
445 proxy.__set__(newconf, proxy.__get__(self))
446 except AttributeError:
447 pass # means property was not set for self
448
449 for c in self.__children:
450 newconf += c # processes proper copy semantics
451
452 return newconf
453

◆ __delattr__()

GaudiKernel.Configurable.Configurable.__delattr__ ( self,
attr )

Definition at line 519 of file Configurable.py.

519 def __delattr__(self, attr):
520 # remove as property, otherwise try as child
521 try:
522 # remove history etc., then reset to default (in case set before)
523 prop = self._properties[attr]
524 prop.__delete__(self)
525 prop.__set__(self, prop.default)
526 return # reaches here? was property: done now
527 except KeyError:
528 pass
529 # otherwise, remove the private tool
530 if attr in self.__tools:
531 del self.__tools[attr]
532
533 # otherwise, remove child, if one is so named
534 for c in self.__children:
535 if c.getName() == attr:
536 self.__children.remove(c)
537
538 # potentially, there are left over caches (certain user derived classes)
539 try:
540 del self.__dict__[attr]
541 except (AttributeError, KeyError):
542 pass
543

◆ __getattr__()

GaudiKernel.Configurable.Configurable.__getattr__ ( self,
attr )

Definition at line 490 of file Configurable.py.

490 def __getattr__(self, attr): # until ToolProperties exist ...
491 if attr in self.__tools:
492 return self.__tools[attr]
493
494 if attr in self._properties:
495 if isinstance(
496 self._properties[attr].__get__(self),
497 (DataHandle, DataHandleVector),
498 ):
499 return self._properties[attr].__get__(self)
500
501 for c in self.__children:
502 if c.getName() == attr:
503 return c
504
505 raise AttributeError(f"'{self.__class__}' object has no attribute '{attr}'")
506

◆ __getnewargs__()

GaudiKernel.Configurable.Configurable.__getnewargs__ ( self)

Definition at line 412 of file Configurable.py.

412 def __getnewargs__(self):
413 return (self._name,)
414

◆ __getstate__()

GaudiKernel.Configurable.Configurable.__getstate__ ( self)

Definition at line 399 of file Configurable.py.

399 def __getstate__(self):
400 dict = {}
401 for name, proxy in self._properties.items():
402 try:
403 dict[name] = proxy.__get__(self)
404 except AttributeError:
405 pass
406
407 dict["_Configurable__children"] = self.__children
408 dict["_Configurable__tools"] = self.__tools
409 dict["_name"] = self._name
410 return dict
411

◆ __iadd__()

GaudiKernel.Configurable.Configurable.__iadd__ ( self,
configs,
descr = None )

Definition at line 455 of file Configurable.py.

455 def __iadd__(self, configs, descr=None):
456 if not isinstance(configs, (list, tuple)):
457 configs = (configs,)
458
459 joname = self.getJobOptName()
460
461 for cfg in configs:
462 # prevent type mismatches
463 if not isinstance(cfg, Configurable):
464 raise TypeError(f"'{cfg}' is not a Configurable")
465
466 cc = self.copyChildAndSetParent(cfg, joname)
467
468 # filters dupes; usually "ok" (backdoor should catch them)
469 ccjo = cc.getJobOptName()
470 for c in self.__children:
471 if c.getJobOptName() == ccjo:
472 log.error(
473 "attempt to add a duplicate ... dupe ignored%s",
474 error_explanation,
475 )
476 break
477 else:
478 self.__children.append(cc)
479
480 try:
481 if descr: # support for tool properties
482 descr.__set__(self, cc)
483 else:
484 setattr(self, cc.getName(), cc)
485 except AttributeError:
486 pass # to allow free addition of tools/subalgorithms
487
488 return self
489

◆ __iter__()

GaudiKernel.Configurable.Configurable.__iter__ ( self)

Definition at line 435 of file Configurable.py.

435 def __iter__(self):
436 return iter(self.__children)
437

◆ __len__()

GaudiKernel.Configurable.Configurable.__len__ ( self)

Definition at line 432 of file Configurable.py.

432 def __len__(self):
433 return len(self.__children)
434

◆ __new__()

GaudiKernel.Configurable.Configurable.__new__ ( cls,
* args,
** kwargs )
To Gaudi, any object with the same type/name is the same object. Hence,
this is mimicked in the configuration: instantiating a new Configurable
of a type with the same name will return the same instance.

Definition at line 185 of file Configurable.py.

185 def __new__(cls, *args, **kwargs):
186 """To Gaudi, any object with the same type/name is the same object. Hence,
187 this is mimicked in the configuration: instantiating a new Configurable
188 of a type with the same name will return the same instance."""
189
190 global log
191 func_code = cls.__init__.__code__
192 func_defaults = cls.__init__.__defaults__
193 # try to get the name of the Configurable (having a name is compulsory)
194 if "name" in kwargs:
195 # simple keyword (by far the easiest)
196 name = kwargs["name"]
197 elif "name" in func_code.co_varnames:
198 # either positional in args, or default
199 index = list(func_code.co_varnames).index("name")
200 try:
201 # var names index is offset by one as __init__ is to be called with self
202 name = args[index - 1]
203 except IndexError:
204 # retrieve default value, then
205 name = func_defaults[index - (len(args) + 1)]
206 else:
207 # positional index is assumed (will work most of the time)
208 try:
209 name = args[1] # '0' is for self
210 except (IndexError, TypeError):
211 raise TypeError(
212 f'no "name" argument while instantiating "{cls.__name__}"'
213 )
214
215 argname = name
216 if name == Configurable.DefaultName:
217 if hasattr(cls, "DefaultedName"):
218 name = cls.DefaultedName
219 else:
220 name = cls.getType()
221 elif not name or not isinstance(name, str):
222 # unnamed, highly specialized user code, etc. ... unacceptable
223 raise TypeError(
224 f"could not retrieve name from {cls.__name__}.__init__ arguments"
225 )
226
227 # Handle the case of global tools to prepend ToolSvc in the name.
228 # This is needed for compatibility with old JobOptions files being read
229 if issubclass(cls, ConfigurableAlgTool) and "." not in name:
230 name = "ToolSvc." + name
231
232 # close backdoor access to otherwise private subalgs/tools
233 # PM if 0 <= name.find( '.' ):
234 # PM # temp protection for old style types
235 # PM from OldStyleConfig import GenericConfigurable
236 # PM if not issubclass( cls, GenericConfigurable ): # except raised for new types only
237 # PM raise NameError( '"%s": backdoor access to private configurables not allowed' % name )
238
239 # ordinary recycle case
240 if name in cls.configurables:
241 conf = cls.configurables[name]
242 if name != argname: # special case: user derived <-> real ... make same
243 cls.configurables[conf.getType()] = conf
244 # ---PM: Initialize additional properties
245 for n, v in kwargs.items():
246 if n != "name": # it should not be confused with a normal property
247 setattr(conf, n, v)
248 if (
249 not cls._configurationLocked
250 and "_enabled" not in kwargs
251 and isinstance(conf, ConfigurableUser)
252 ):
253 # Ensure that the ConfigurableUser gets enabled if nothing is
254 # specified in the constructor.
255 setattr(conf, "_enabled", True)
256 return conf
257
258 # a couple of special cases (note that these cases don't mix)
259 spos = name.find("/")
260 ti_name = None
261 if spos < 0:
262 ti_name = f"{name}/{name}"
263 if ti_name in cls.configurables:
264 # support for old-style name as type/name lookup where name==type
265 return cls.configurables[ti_name]
266
267 i_name = None
268 if spos > 0:
269 i_name = name[:spos]
270 if i_name == name[spos + 1 :] and i_name in cls.configurables:
271 # this is the opposite of the above special case
272 return cls.configurables[i_name]
273
274 # the following is purely for debugging support and should realistically bomb
275 conf = (
276 cls.allConfigurables.get(name, None)
277 or (spos < 0 and cls.allConfigurables.get(ti_name, None))
278 or (
279 spos > 0
280 and i_name == name[spos + 1 :]
281 and cls.allConfigurables.get(i_name, None)
282 )
283 )
284 if conf: # wrong type used?
285 if conf.__class__ is ConfigurableGeneric:
286 # If the instance found is ConfigurableGeneric then
287 # we create a new one with the proper type and fill with
288 # the contents of the generic one
289 newconf = object.__new__(cls)
290 cls.__init__(newconf, *args, **kwargs)
291 # initialize with the properties of generic configurable
292 # (we map the names of the properties to lowercase versions because
293 # old options are not case sensitive)
294 names = {}
295 for n in newconf.__slots__:
296 names[n.lower()] = n
297 for n in conf._properties:
298 if names[n.lower()] != n:
299 log.warning(
300 f"Option '{n}' was used for {name}, but the correct spelling is '{names[n.lower()]}'"
301 )
302 setattr(newconf, names[n.lower()], getattr(conf, n))
303 for n, v in kwargs.items():
304 setattr(newconf, n, v)
305 cls.configurables[name] = newconf
306 cls.allConfigurables[name] = newconf
307 return newconf
308 else:
309 # will be an actual error in the future (now only report as such)
310 log.error(
311 'attempt to redefine type of "%s" (was: %s, new: %s)%s',
312 name,
313 conf.__class__.__name__,
314 cls.__name__,
315 error_explanation,
316 )
317 # in the future:
318 # return None # will bomb on use (or go unharmed on non-use)
319 # for now, allow use through allConfigurables lookup
320 # ---PM: Initialize additional properties
321 for n, v in kwargs.items():
322 setattr(conf, n, v)
323 return conf
324
325 # still here: create a new instance and initialize it
326 conf = object.__new__(cls)
327 cls.__init__(conf, *args, **kwargs)
328
329 # update normal, per-class cache
330 cls.configurables[name] = conf
331
332 for base in cls.__bases__:
333 if base.__name__ == "ConfigurableService":
334 cls.configurableServices[name] = conf
335
336 # update generics super-cache, if needed
337 cls.allConfigurables[name] = conf
338 # -->PM#if hasattr( cls, 'getType' ) and name.find('/') < 0:
339 # -->PM# cls.allConfigurables[ cls.getType() + '/' + name ] = conf
340
341 return conf
342

◆ __repr__()

GaudiKernel.Configurable.Configurable.__repr__ ( self)

Definition at line 964 of file Configurable.py.

964 def __repr__(self):
965 return f"{self.__class__.__name__}({self.name()!r})"
966

◆ __setattr__()

GaudiKernel.Configurable.Configurable.__setattr__ ( self,
name,
value )

Definition at line 507 of file Configurable.py.

507 def __setattr__(self, name, value):
508 if self._configurationLocked:
509 raise RuntimeError(
510 f"{self.name()}: Configuration cannot be modified after the ApplicationMgr has been started."
511 )
512 try:
513 super().__setattr__(name, value)
514 except AttributeError:
515 raise AttributeError(
516 f"Configurable '{self.__class__.__name__}' does not have property '{name}'."
517 )
518

◆ __setstate__()

GaudiKernel.Configurable.Configurable.__setstate__ ( self,
dict )

Definition at line 415 of file Configurable.py.

415 def __setstate__(self, dict):
416 self._initok = True
417 from contextlib import contextmanager
418
419 @contextmanager
420 def unpickling():
421 try:
422 self._unpickling = True
423 yield
424 finally:
425 self._unpickling = False
426
427 with unpickling():
428 for n, v in dict.items():
429 setattr(self, n, v)
430

◆ __setupDefaults()

GaudiKernel.Configurable.Configurable.__setupDefaults ( self)
private

Definition at line 937 of file Configurable.py.

937 def __setupDefaults(self):
938 # set handle defaults flags to inform __setattr__ that it is being
939 # called during setDefaults of the concrete Configurable
940 self._inSetDefaults = True
941 self.setDefaults(self)
942 self._inSetDefaults = False
943

◆ __setupDlls()

GaudiKernel.Configurable.Configurable.__setupDlls ( self)
private

Definition at line 924 of file Configurable.py.

924 def __setupDlls(self):
925 dlls = self.getDlls()
926 if not dlls:
927 dlls = []
928 elif isinstance(dlls, types.StringType):
929 dlls = [dlls]
930
931 from __main__ import theApp
932
933 dlls = filter(lambda d: d not in theApp.Dlls, dlls)
934 if dlls:
935 theApp.Dlls += dlls
936

◆ __setupServices()

GaudiKernel.Configurable.Configurable.__setupServices ( self)
private

Definition at line 906 of file Configurable.py.

906 def __setupServices(self):
907 # svcs = self.getServices()
908 # if not svcs:
909 svcs = []
910 # elif type(svcs) == types.StringType:
911 # svcs = [ svcs ]
912
913 import __main__
914
915 for svc in svcs:
916 handle = __main__.Service(svc) # noqa: F841 (used in eval below)
917 # services should be configurables as well, but aren't for now
918 # handle.setup()
919
920 # allow Configurable to make some changes
921 if hasattr(self, "configure" + svc):
922 eval("self.configure" + svc + "( handle )")
923

◆ __str__()

GaudiKernel.Configurable.Configurable.__str__ ( self,
indent = 0,
headerLastIndentUnit = indentUnit )

Definition at line 967 of file Configurable.py.

967 def __str__(self, indent=0, headerLastIndentUnit=indentUnit):
968 global log # to print some info depending on output level
969
970 def _sorted_repr_set(value):
971 """Helper to print sorted set representation"""
972 return "{" + repr(sorted(value))[1:-1] + "}" if value else "set()"
973
974 indentStr = indent * Configurable.indentUnit
975 # print header
976 title = self.getPrintTitle()
977 # print line to easily see start-of-configurable
978 if indent > 0:
979 headerIndent = (indent - 1) * Configurable.indentUnit + headerLastIndentUnit
980 else:
981 headerIndent = ""
982 rep = Configurable._printHeader(headerIndent, title)
983 rep += os.linesep
984 # print own properties
985 props = self.getProperties()
986 defs = self.getDefaultProperties()
987 if not props:
988 rep += f"{indentStr}|-<no properties>{os.linesep}"
989 else:
990 # get property name with
991 nameWidth = 0
992 for p in props.keys():
993 nameWidth = max(nameWidth, len(p))
994 for p, v in props.items():
995 # start with indent and property name
996 prefix = f"{indentStr}|-{p:<{nameWidth}}"
997 # add memory address for debugging (not for defaults)
998 if log.isEnabledFor(logging.DEBUG):
999 if v != Configurable.propertyNoValue:
1000 address = f" @{id(v):#018x}"
1001 else:
1002 address = 20 * " "
1003 prefix += address
1004 # add value and default
1005 default = defs.get(p)
1006 if v == Configurable.propertyNoValue:
1007 # show default value as value, and no extra 'default'
1008 strVal = repr(default)
1009 strDef = None
1010 else:
1011 # convert configurable to handle
1012 if hasattr(v, "getGaudiHandle"):
1013 vv = v.getGaudiHandle()
1014 else:
1015 vv = v
1016 if isinstance(vv, (GaudiHandle, GaudiHandleArray, DataHandle)):
1017 strVal = repr(vv)
1018 # the default may not be a GaudiHandle (?)
1019 if hasattr(default, "toStringProperty"):
1020 strDef = repr(default.toStringProperty())
1021 else:
1022 strDef = repr(default)
1023 if strDef == repr(vv.toStringProperty()):
1024 strDef = None
1025 elif isinstance(vv, set):
1026 strVal = _sorted_repr_set(vv)
1027 strDef = _sorted_repr_set(default)
1028 else:
1029 strVal = repr(vv)
1030 strDef = repr(default)
1031 # add the value
1032 line = prefix + " = " + strVal
1033 # add default if present
1034 if strDef is not None:
1035 # put default on new line if too big
1036 if len(line) + len(strDef) > Configurable.printHeaderWidth:
1037 line += (
1038 os.linesep
1039 + indentStr
1040 + "| "
1041 + (len(prefix) - len(indentStr) - 3) * " "
1042 )
1043 line += f" (default: {strDef})"
1044 # add the line to the total string
1045 rep += line + os.linesep
1046 # print out full private configurables
1047 # if isinstance(v,Configurable) and not v.isPublic():
1048
1053
1054 # print configurables + their properties, or loop over sequence
1055 # for cfg in self.__children:
1056 for cfg in self.getAllChildren():
1057 rep += cfg.__str__(indent + 1, "|=") + os.linesep
1058
1059 # print line to easily see end-of-configurable. Note: No linesep!
1060 rep += Configurable._printFooter(indentStr, title)
1061 return rep
1062

◆ _isInSetDefaults()

GaudiKernel.Configurable.Configurable._isInSetDefaults ( self)
protected

Definition at line 903 of file Configurable.py.

903 def _isInSetDefaults(self):
904 return self._inSetDefaults
905

◆ _printFooter()

GaudiKernel.Configurable.Configurable._printFooter ( indentStr,
title )
staticprotected

Definition at line 954 of file Configurable.py.

954 def _printFooter(indentStr, title):
955 preLen = Configurable.printHeaderPre
956 postLen = (
957 Configurable.printHeaderWidth - preLen - 12 - len(title)
958 ) # - len(indentStr)
959 postLen = max(preLen, postLen)
960 return indentStr + "\\{} (End of {}) {}".format(
961 preLen * "-", title, postLen * "-"
962 )
963
GAUDI_API std::string format(const char *,...)
MsgStream format utility "a la sprintf(...)".
Definition MsgStream.cpp:93

◆ _printHeader()

GaudiKernel.Configurable.Configurable._printHeader ( indentStr,
title )
staticprotected

Definition at line 945 of file Configurable.py.

945 def _printHeader(indentStr, title):
946 preLen = Configurable.printHeaderPre
947 postLen = (
948 Configurable.printHeaderWidth - preLen - 3 - len(title)
949 ) # - len(indentStr)
950 postLen = max(preLen, postLen)
951 return indentStr + "/{} {} {}".format(preLen * "*", title, postLen * "*")
952

◆ addTool()

GaudiKernel.Configurable.Configurable.addTool ( self,
tool,
name = None )

Definition at line 880 of file Configurable.py.

880 def addTool(self, tool, name=None):
881 if isclass(tool) and issubclass(tool, ConfigurableAlgTool):
882 if name is None:
883 name = tool.__name__
884 priv_tool = tool(self.getName() + "." + name)
885 elif isinstance(tool, ConfigurableAlgTool):
886 if name is None:
887 name = tool.splitName()[1]
888 priv_tool = tool.clone(self.getName() + "." + name)
889 else:
890 if isclass(tool):
891 classname = tool.__name__
892 else:
893 classname = type(tool).__name__
894 raise TypeError(
895 f"addTool requires AlgTool configurable. Got {classname} type"
896 )
897 self.__tools[name] = priv_tool
898 if name in self.__slots__:
899 # this is to avoid that the property hides the tool
900 setattr(self, name, self.__tools[name])
901 return self.__tools[name]
902

◆ children()

GaudiKernel.Configurable.Configurable.children ( self)

Definition at line 595 of file Configurable.py.

595 def children(self):
596 log.error("children() is deprecated, use getChildren() instead for consistency")
597 log.error(
598 "getChildren() returns a copy; to add a child, use 'parent += child'%s",
599 error_explanation,
600 )
601 return self.__children # by ref, for compatibility
602

◆ clone()

GaudiKernel.Configurable.Configurable.clone ( self,
name = None,
** kwargs )

Definition at line 833 of file Configurable.py.

833 def clone(self, name=None, **kwargs):
834 if not name:
835 if hasattr(self, "DefaultedName"):
836 name = self.DefaultedName
837 else:
838 name = self.getType()
839
840 newconf = Configurable.__new__(self.__class__, name)
841 self.__class__.__init__(newconf, name)
842
843 for proxy in self._properties.values():
844 try:
845 value = proxy.__get__(self)
846 if isinstance(value, (str, list, dict, tuple, set)):
847 # clone the values of the properties for basic types
848 value = type(value)(value)
849 proxy.__set__(newconf, value)
850 except AttributeError:
851 pass
852
853 for c in self.__children:
854 newconf += c # processes proper copy semantics
855
856 for n, t in self.__tools.items():
857 newconf.addTool(t, n)
858
859 for name, value in kwargs.items():
860 setattr(newconf, name, value)
861
862 return newconf
863

◆ copyChild()

GaudiKernel.Configurable.Configurable.copyChild ( self,
child )

Reimplemented in GaudiKernel.Configurable.ConfigurableService.

Definition at line 557 of file Configurable.py.

557 def copyChild(self, child):
558 return copy.deepcopy(child)
559

◆ copyChildAndSetParent()

GaudiKernel.Configurable.Configurable.copyChildAndSetParent ( self,
cfg,
parent )

Definition at line 569 of file Configurable.py.

569 def copyChildAndSetParent(self, cfg, parent):
570 cc = self.copyChild(cfg)
571
572 if hasattr(cc, "setParent") and parent:
573 try:
574 cc.setParent(parent)
575 except RuntimeError as e:
576 # temporary backdoor resolution for compatibility
577 log.error(str(e) + "%s", error_explanation)
578 ccbd = cc.configurables[cc.getJobOptName()]
579
580 # merge properties, new over pre-existing
581 for proxy in self._properties.values():
582 if cc in proxy.history:
583 proxy.__set__(ccbd, proxy.__get__(cc))
584
585 # consolidate
586 cc = ccbd
587 return cc
588

◆ getAllChildren()

GaudiKernel.Configurable.Configurable.getAllChildren ( self)
Get all (private) configurable children, both explicit ones (added with +=)
and the ones in the private GaudiHandle properties

Definition at line 603 of file Configurable.py.

603 def getAllChildren(self):
604 """Get all (private) configurable children, both explicit ones (added with +=)
605 and the ones in the private GaudiHandle properties"""
606 childs = []
607 # add private configurable properties (also inside handles)
608 for proxy in self._properties.values():
609 try:
610 c = proxy.__get__(self)
611 except AttributeError:
612 pass
613 else:
614 if isinstance(c, Configurable) and not c.isPublic():
615 childs.append(c)
616 elif isinstance(c, GaudiHandle):
617 try:
618 conf = c.configurable
619 except AttributeError:
620 pass
621 else:
622 if not conf.isPublic():
623 childs.append(conf)
624 elif isinstance(c, GaudiHandleArray):
625 # only setup private arrays
626 if not c.isPublic():
627 for ci in c:
628 if isinstance(ci, Configurable):
629 childs.append(ci)
630 else:
631 try:
632 conf = ci.configurable
633 except AttributeError:
634 pass
635 else:
636 childs.append(conf)
637
638 # add explicit children
639 childs += self.__children
640 return childs
641

◆ getChildren()

GaudiKernel.Configurable.Configurable.getChildren ( self)

Definition at line 589 of file Configurable.py.

589 def getChildren(self):
590 return self.__children[:] # read only
591

◆ getDefaultProperties()

GaudiKernel.Configurable.Configurable.getDefaultProperties ( cls)

Definition at line 732 of file Configurable.py.

732 def getDefaultProperties(cls):
733 # user provided defaults
734 c = _DefaultPropertiesCollectorHelper()
735 cls.setDefaults(c)
736
737 # defaults from C++
738 for k, v in cls._properties.items():
739 if k not in c.__dict__ and hasattr(v, "default"):
740 c.__dict__[k] = v.default
741
742 return c.__dict__
743

◆ getDefaultProperty()

GaudiKernel.Configurable.Configurable.getDefaultProperty ( cls,
name )

Definition at line 745 of file Configurable.py.

745 def getDefaultProperty(cls, name):
746 # user provided defaults
747 c = _DefaultPropertiesCollectorHelper()
748 cls.setDefaults(c)
749
750 if name in c.__dict__:
751 return c.__dict__[name]
752
753 # defaults from C++
754 try:
755 v = cls._properties[name]
756 if hasattr(v, "default"):
757 return v.default
758 except KeyError:
759 pass
760
761 return None
762

◆ getFullJobOptName()

GaudiKernel.Configurable.Configurable.getFullJobOptName ( self)

Definition at line 818 of file Configurable.py.

818 def getFullJobOptName(self):
819 return f"{self.getType()}/{self.getJobOptName() or self.getName()}"
820

◆ getFullName()

GaudiKernel.Configurable.Configurable.getFullName ( self)

Reimplemented in GaudiKernel.Configurable.ConfigurableAlgTool.

Definition at line 815 of file Configurable.py.

815 def getFullName(self):
816 return str(self.getType() + "/" + self.getName())
817

◆ getJobOptName()

GaudiKernel.Configurable.Configurable.getJobOptName ( self)

Reimplemented in GaudiKernel.Configurable.ConfigurableAlgorithm, GaudiKernel.Configurable.ConfigurableAlgTool, GaudiKernel.Configurable.ConfigurableAuditor, and GaudiKernel.Configurable.ConfigurableGeneric.

Definition at line 801 of file Configurable.py.

801 def getJobOptName(self): # full hierachical name
802 return self.getName()
803

◆ getName()

GaudiKernel.Configurable.Configurable.getName ( self)

Definition at line 795 of file Configurable.py.

795 def getName(self):
796 return self._name
797

◆ getParent()

GaudiKernel.Configurable.Configurable.getParent ( self)

Reimplemented in GaudiKernel.Configurable.ConfigurableAlgTool.

Definition at line 563 of file Configurable.py.

563 def getParent(self):
564 return ""
565

◆ getPrintTitle()

GaudiKernel.Configurable.Configurable.getPrintTitle ( self)

Reimplemented in GaudiKernel.Configurable.ConfigurableAlgTool.

Definition at line 821 of file Configurable.py.

821 def getPrintTitle(self):
822 return self.getGaudiType() + " " + self.getTitleName()
823

◆ getProp()

GaudiKernel.Configurable.Configurable.getProp ( self,
name )
Returns the value of the given property.

Definition at line 763 of file Configurable.py.

763 def getProp(self, name):
764 """Returns the value of the given property."""
765 if hasattr(self, name):
766 return getattr(self, name)
767 else:
768 return self.getDefaultProperties()[name]
769

◆ getProperties()

GaudiKernel.Configurable.Configurable.getProperties ( self)

Definition at line 681 of file Configurable.py.

681 def getProperties(self):
682 props = {}
683 for name, proxy in self._properties.items():
684 try:
685 props[name] = proxy.__get__(self)
686 except AttributeError:
687 props[name] = Configurable.propertyNoValue
688
689 return props
690

◆ getPropertiesWithDescription()

GaudiKernel.Configurable.Configurable.getPropertiesWithDescription ( self)
Get all properties with their description string as { name : (value, desc) }.

Definition at line 691 of file Configurable.py.

691 def getPropertiesWithDescription(self):
692 """Get all properties with their description string as { name : (value, desc) }."""
693 props = {}
694 for name, proxy in self._properties.items():
695 try:
696 props[name] = (proxy.__get__(self), proxy.__doc__)
697 except AttributeError:
698 props[name] = (Configurable.propertyNoValue, proxy.__doc__)
699 return props
700

◆ getSequence()

GaudiKernel.Configurable.Configurable.getSequence ( self)

Definition at line 642 of file Configurable.py.

642 def getSequence(self):
643 elems = []
644 for c in self.__children:
645 elems.append(c.getFullName())
646 return elems
647

◆ getTitleName()

GaudiKernel.Configurable.Configurable.getTitleName ( self)

Definition at line 824 of file Configurable.py.

824 def getTitleName(self):
825 if log.isEnabledFor(logging.DEBUG):
826 return self.getFullJobOptName()
827 else:
828 return self.getFullName()
829

◆ getTools()

GaudiKernel.Configurable.Configurable.getTools ( self)

Definition at line 592 of file Configurable.py.

592 def getTools(self):
593 return self.__tools.values() # read only
594

◆ getType()

GaudiKernel.Configurable.Configurable.getType ( cls)

Definition at line 792 of file Configurable.py.

792 def getType(cls):
793 return cls.__name__
794

◆ getValuedProperties()

GaudiKernel.Configurable.Configurable.getValuedProperties ( self)

Definition at line 701 of file Configurable.py.

701 def getValuedProperties(self):
702 props = {}
703 for name, proxy in self._properties.items():
704 if self.isPropertySet(name):
705 value = proxy.__get__(self)
706 if hasattr(value, "getFullName"):
707 value = value.getFullName()
708 elif isinstance(value, (list, set, tuple)):
709 new_value = []
710 for i in value:
711 if hasattr(i, "getFullName"):
712 new_value.append(i.getFullName())
713 else:
714 new_value.append(i)
715 value = type(value)(new_value)
716 elif isinstance(value, dict):
717 new_value = {}
718 for i in value:
719 if hasattr(value[i], "getFullName"):
720 new_value[i] = value[i].getFullName()
721 else:
722 new_value[i] = value[i]
723 value = new_value
724 props[name] = value
725
726 return props
727

◆ hasParent()

GaudiKernel.Configurable.Configurable.hasParent ( self,
parent )

Reimplemented in GaudiKernel.Configurable.ConfigurableAlgTool.

Definition at line 566 of file Configurable.py.

566 def hasParent(self, parent):
567 return False
568

◆ isApplicable()

GaudiKernel.Configurable.Configurable.isApplicable ( self)
Return True is the instance can be "applied".
Always False for plain Configurable instances
(i.e. not ConfigurableUser).

Reimplemented in GaudiKernel.Configurable.ConfigurableUser.

Definition at line 1063 of file Configurable.py.

1063 def isApplicable(self):
1064 """
1065 Return True is the instance can be "applied".
1066 Always False for plain Configurable instances
1067 (i.e. not ConfigurableUser).
1068 """
1069 return False
1070
1071
1072# classes for generic Gaudi component ===========
1073
1074

◆ isPropertySet()

GaudiKernel.Configurable.Configurable.isPropertySet ( self,
name )
Tell if the property 'name' has been set or not.

Because of a problem with list and dictionary properties, in those cases
if the value is equal to the default, the property is considered as not
set.

Definition at line 774 of file Configurable.py.

774 def isPropertySet(self, name):
775 """Tell if the property 'name' has been set or not.
776
777 Because of a problem with list and dictionary properties, in those cases
778 if the value is equal to the default, the property is considered as not
779 set.
780 """
781 if not hasattr(self, name):
782 return False
783 default = self.getDefaultProperty(name)
784 if isinstance(
785 default,
786 (list, dict, set, DataHandle, DataHandleVector, GaudiHandleArray),
787 ):
788 value = getattr(self, name)
789 return value != default
790 return True
791

◆ isPublic()

GaudiKernel.Configurable.Configurable.isPublic ( self)

Reimplemented in GaudiKernel.Configurable.ConfigurableAlgTool.

Definition at line 804 of file Configurable.py.

804 def isPublic(self):
805 return True
806

◆ jobOptName()

GaudiKernel.Configurable.Configurable.jobOptName ( self)

Definition at line 808 of file Configurable.py.

808 def jobOptName(self):
809 log.error(
810 "jobOptName() is deprecated, use getJobOptName() instead for consistency%s",
811 error_explanation,
812 )
813 return self.getJobOptName() # compatibility
814

◆ name()

GaudiKernel.Configurable.Configurable.name ( self)

Definition at line 798 of file Configurable.py.

798 def name(self):
799 return self.getName()
800

◆ properties()

GaudiKernel.Configurable.Configurable.properties ( self)

Definition at line 728 of file Configurable.py.

728 def properties(self):
729 return self.getProperties() # compatibility
730

◆ remove()

GaudiKernel.Configurable.Configurable.remove ( self,
items )

Definition at line 547 of file Configurable.py.

547 def remove(self, items):
548 if not isinstance(items, (list, tuple)):
549 items = [items]
550
551 self.__children = [e for e in self.__children if e not in items]
552

◆ removeAll()

GaudiKernel.Configurable.Configurable.removeAll ( self)

Definition at line 553 of file Configurable.py.

553 def removeAll(self):
554 self.remove(self.__children)
555

◆ setDefaults()

GaudiKernel.Configurable.Configurable.setDefaults ( cls,
handle )

Definition at line 830 of file Configurable.py.

830 def setDefaults(cls, handle):
831 pass
832

◆ setParent()

GaudiKernel.Configurable.Configurable.setParent ( self,
parentName )

Reimplemented in GaudiKernel.Configurable.ConfigurableAlgTool.

Definition at line 560 of file Configurable.py.

560 def setParent(self, parentName):
561 pass
562

◆ setProp()

GaudiKernel.Configurable.Configurable.setProp ( self,
name,
value )
Set the value of a given property

Definition at line 770 of file Configurable.py.

770 def setProp(self, name, value):
771 """Set the value of a given property"""
772 return setattr(self, name, value)
773

◆ setup()

GaudiKernel.Configurable.Configurable.setup ( self)

Definition at line 648 of file Configurable.py.

648 def setup(self):
649 # make sure base class init has been called
650 if not hasattr(self, "_initok") or not self._initok:
651 # could check more, but this is the only explanation
652 raise TypeError(
653 f"Configurable.__init__ not called in {self.__class__.__name__} override"
654 )
655
656 # log.debug("calling setup() on " + self.getFullJobOptName())
657
658 # setup self: this collects all values on the python side
659 self.__setupServices()
660 self.__setupDlls()
661 self.__setupDefaults()
662
663 # setup children
664 for c in self.getAllChildren():
665 c.setup()
666
667 # now get handle to work with for moving properties into the catalogue
668 handle = self.getHandle()
669 if not handle:
670 log.debug("no handle for %s: not transporting properties", self._name)
671 return # allowed, done early
672
673 # pass final set of properties on to handle on the C++ side or JobOptSvc
674 for name in self._properties.keys():
675 if hasattr(self, name): # means property has python-side value/default
676 setattr(handle, name, getattr(self, name))
677
678 # for debugging purposes
679 self._setupok = True
680

◆ splitName()

GaudiKernel.Configurable.Configurable.splitName ( self)

Definition at line 864 of file Configurable.py.

864 def splitName(self):
865 fullname = self.getName()
866 dot = fullname.find(".")
867 if dot != -1:
868 parentname = fullname[:dot]
869 longname = fullname[dot + 1 :]
870 else:
871 parentname = ""
872 longname = fullname
873 dot = longname.find(".")
874 if dot != -1:
875 name = longname[:dot]
876 else:
877 name = longname
878 return parentname, name, longname
879

Member Data Documentation

◆ __bases__

GaudiKernel.Configurable.Configurable.__bases__
private

Definition at line 332 of file Configurable.py.

◆ __children

GaudiKernel.Configurable.Configurable.__children = []
private

Definition at line 374 of file Configurable.py.

◆ __class__

GaudiKernel.Configurable.Configurable.__class__
private

Definition at line 379 of file Configurable.py.

◆ __name__

GaudiKernel.Configurable.Configurable.__name__
private

Definition at line 314 of file Configurable.py.

◆ __slots__

tuple GaudiKernel.Configurable.Configurable.__slots__
staticprivate
Initial value:
= (
"__children", # controlled components, e.g. private AlgTools
"__tools", # private AlgTools (#PM-->)
"_name", # the (unqualified) component name
"_inSetDefaults", # currently setting default values
"_initok", # used to enforce base class init
"_setupok", # for debugging purposes (temporary)
"_unpickling", # flag for actions done during unpickling
)

Definition at line 169 of file Configurable.py.

◆ __tools

dict GaudiKernel.Configurable.Configurable.__tools = {}
private

Definition at line 375 of file Configurable.py.

◆ _configurationLocked

bool GaudiKernel.Configurable.Configurable._configurationLocked = False
staticprotected

Definition at line 183 of file Configurable.py.

◆ _initok

bool GaudiKernel.Configurable.Configurable._initok = True
protected

Definition at line 390 of file Configurable.py.

◆ _inSetDefaults

bool GaudiKernel.Configurable.Configurable._inSetDefaults = False
protected

Definition at line 387 of file Configurable.py.

◆ _name

GaudiKernel.Configurable.Configurable._name = self.__class__.DefaultedName
protected

Definition at line 380 of file Configurable.py.

◆ _properties

GaudiKernel.Configurable.Configurable._properties
protected

Definition at line 494 of file Configurable.py.

◆ _setupok

bool GaudiKernel.Configurable.Configurable._setupok = False
protected

Definition at line 393 of file Configurable.py.

◆ _unpickling

bool GaudiKernel.Configurable.Configurable._unpickling = False
protected

Definition at line 396 of file Configurable.py.

◆ allConfigurables

dict GaudiKernel.Configurable.Configurable.allConfigurables = {}
static

Definition at line 179 of file Configurable.py.

◆ configurables

GaudiKernel.Configurable.Configurable.configurables

Definition at line 240 of file Configurable.py.

◆ configurableServices

dict GaudiKernel.Configurable.Configurable.configurableServices = {}
static

Definition at line 180 of file Configurable.py.

◆ indentUnit

str GaudiKernel.Configurable.Configurable.indentUnit = "| "
static

Definition at line 165 of file Configurable.py.

◆ printHeaderPre

int GaudiKernel.Configurable.Configurable.printHeaderPre = 5
static

Definition at line 167 of file Configurable.py.

◆ printHeaderWidth

int GaudiKernel.Configurable.Configurable.printHeaderWidth = 100
static

Definition at line 166 of file Configurable.py.

◆ propertyNoValue

GaudiKernel.Configurable.Configurable.propertyNoValue
static

Definition at line 164 of file Configurable.py.


The documentation for this class was generated from the following file: