The Gaudi Framework  master (1304469f)
Loading...
Searching...
No Matches
__init__.py
Go to the documentation of this file.
12from GaudiConfig2._db import ConfigurablesDB
13
14Configurables = ConfigurablesDB(__name__ + ".Configurables")
15del ConfigurablesDB # no need to use this class after this point
16
17import re
18
19from GaudiConfig2._configurables import ( # noqa: F401
20 Configurable,
21 Property,
22 all_options,
23 useGlobalInstances,
24)
25
26# Regular expression to check if any of the options is a Python callable,
27# in the form of a string like `package.sub_package.module:callable` or
28# `path/to/file.py:callable`
29CALLABLE_FORMAT = re.compile(
30 r"^(?:(?P<module>[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)|(?P<path>[^\0]+\.py)):(?P<callable>[a-zA-Z_][a-zA-Z0-9_]*)$"
31)
32
33
34def _makeConfigDict(iterable):
35 try: # pragma no cover
36 from collections.abc import Mapping
37 except ImportError: # pragma no cover
38 from collections import Mapping
39
40 if iterable is None:
41 return {}
42 if not isinstance(iterable, Mapping):
43 return {c.name: c for c in iterable}
44 return iterable
45
46
47def mergeConfigs(*configs):
48 """
49 Merge configuration dictionaries ({'name': Configurable('name'), ...}) or
50 lists ([Configurable('name'), ...]) into one configuration dictionary.
51
52 **warning** the configurable instances passed are not cloned during the
53 merging, so the arguments to this function cannot be used afterwards
54 """
55 result = {}
56 for config in configs:
57 config = _makeConfigDict(config)
58 for name in config:
59 if name in result:
60 result[name].merge(config[name])
61 else:
62 result[name] = config[name]
63 return result
64
65
66def invokeConfig(func, *args, **kwargs):
67 from importlib import import_module
68
69 if not callable(func):
70 if isinstance(func, str):
71 m = CALLABLE_FORMAT.match(func)
72 if m and m.group("module"):
73 func = getattr(import_module(m.group("module")), m.group("callable"))
74 elif m and m.group("path"):
75 globals = {"__file__": m.group("path")}
76 exec(
77 compile(
78 open(m.group("path"), "rb").read(), m.group("path"), "exec"
79 ),
80 globals,
81 )
82 func = globals[m.group("callable")]
83 else:
84 raise ValueError("invalid callable id %r" % func)
85 else:
86 raise TypeError("expected either a callable or a string as first argument")
87 return _makeConfigDict(func(*args, **kwargs))
int merge(const char *target, const char *source, bool fixup=false, bool dbg=true)
Definition merge.C:417
invokeConfig(func, *args, **kwargs)
Definition __init__.py:66
mergeConfigs(*configs)
Definition __init__.py:47
_makeConfigDict(iterable)
Definition __init__.py:34