25 from .config
import Config, Field, _joinNamePath, _typeStr, FieldValidationError
26 from .comparison
import compareConfigs, getComparisonName
27 from .callStack
import getCallStack, getStackFrame
31 def __initValue(self, at, label):
33 if field.default is an instance of ConfigClass, custom construct 34 _value with the correct values from default. 35 otherwise call ConfigClass constructor 37 name = _joinNamePath(self._config._name, self._field.name)
39 storage = self._field.default._storage
42 value = self._ConfigClass(__name=name, __at=at, __label=label, **storage)
43 object.__setattr__(self,
"_value", value)
45 def __init__(self, config, field, at=None, label="default"):
46 object.__setattr__(self,
"_config", config)
47 object.__setattr__(self,
"_field", field)
48 object.__setattr__(self,
"__doc__", config)
49 object.__setattr__(self,
"_target", field.target)
50 object.__setattr__(self,
"_ConfigClass", field.ConfigClass)
51 object.__setattr__(self,
"_value",
None)
55 at += [self._field.source]
58 history = config._history.setdefault(field.name, [])
59 history.append((
"Targeted and initialized from defaults", at, label))
62 Read-only access to the targeted configurable 64 target = property(
lambda x: x._target)
66 Read-only access to the ConfigClass 68 ConfigClass = property(
lambda x: x._ConfigClass)
71 Read-only access to the ConfigClass instance 73 value = property(
lambda x: x._value)
77 Call the confirurable. 78 With argument config=self.value along with any positional and kw args 83 Target a new configurable and ConfigClass 85 def retarget(self, target, ConfigClass=None, at=None, label="retarget"):
86 if self._config._frozen:
90 ConfigClass = self._field.validateTarget(target, ConfigClass)
91 except BaseException
as e:
96 object.__setattr__(self,
"_target", target)
98 object.__setattr__(self,
"_ConfigClass", ConfigClass)
101 history = self._config._history.setdefault(self._field.name, [])
102 msg =
"retarget(target=%s, ConfigClass=%s)" % (_typeStr(target), _typeStr(ConfigClass))
103 history.append((msg, at, label))
106 return getattr(self._value, name)
110 Pretend to be an isntance of ConfigClass. 111 Attributes defined by ConfigurableInstance will shadow those defined in ConfigClass 113 if self._config._frozen:
116 if name
in self.__dict__:
118 object.__setattr__(self, name, value)
122 self._value.
__setattr__(name, value, at=at, label=label)
126 Pretend to be an isntance of ConfigClass. 127 Attributes defiend by ConfigurableInstance will shadow those defined in ConfigClass 129 if self._config._frozen:
134 object.__delattr__(self, name)
135 except AttributeError:
143 A variant of a ConfigField which has a known configurable target 145 Behaves just like a ConfigField except that it can be 'retargeted' to point 146 at a different configurable. Further you can 'apply' to construct a fully 147 configured configurable. 153 if ConfigClass
is None:
155 ConfigClass = target.ConfigClass
157 raise AttributeError(
"'target' must define attribute 'ConfigClass'")
158 if not issubclass(ConfigClass, Config):
159 raise TypeError(
"'ConfigClass' is of incorrect type %s." 160 "'ConfigClass' must be a subclass of Config" % _typeStr(ConfigClass))
161 if not hasattr(target,
'__call__'):
162 raise ValueError(
"'target' must be callable")
163 if not hasattr(target,
'__module__')
or not hasattr(target,
'__name__'):
164 raise ValueError(
"'target' must be statically defined" 165 "(must have '__module__' and '__name__' attributes)")
168 def __init__(self, doc, target, ConfigClass=None, default=None, check=None):
170 @param target is the configurable target. Must be callable, and the first 171 parameter will be the value of this field 172 @param ConfigClass is the class of Config object expected by the target. 173 If not provided by target.ConfigClass it must be provided explicitly in this argument 178 default = ConfigClass
179 if default != ConfigClass
and type(default) != ConfigClass:
180 raise TypeError(
"'default' is of incorrect type %s. Expected %s" %
181 (_typeStr(default), _typeStr(ConfigClass)))
184 self.
_setup(doc=doc, dtype=ConfigurableInstance, default=default,
185 check=check, optional=
False, source=source)
189 def __getOrMake(self, instance, at=None, label="default"):
190 value = instance._storage.get(self.name,
None)
195 instance._storage[self.name] = value
198 def __get__(self, instance, owner=None, at=None, label="default"):
199 if instance
is None or not isinstance(instance, Config):
202 return self.
__getOrMake(instance, at=at, label=label)
204 def __set__(self, instance, value, at=None, label="assignment"):
211 if isinstance(value, ConfigurableInstance):
212 oldValue.retarget(value.target, value.ConfigClass, at, label)
213 oldValue.update(__at=at, __label=label, **value._storage)
214 elif type(value) == oldValue._ConfigClass:
215 oldValue.update(__at=at, __label=label, **value._storage)
216 elif value == oldValue.ConfigClass:
217 value = oldValue.ConfigClass()
218 oldValue.update(__at=at, __label=label, **value._storage)
220 msg =
"Value %s is of incorrect type %s. Expected %s" % \
221 (value, _typeStr(value), _typeStr(oldValue.ConfigClass))
225 fullname = _joinNamePath(instance._name, self.name)
227 value._rename(fullname)
229 def save(self, outfile, instance):
230 fullname = _joinNamePath(instance._name, self.name)
232 target = value.target
237 ConfigClass = value.ConfigClass
238 for module
in set([target.__module__, ConfigClass.__module__]):
239 outfile.write(
u"import {}\n".
format(module))
240 outfile.write(
u"{}.retarget(target={}, ConfigClass={})\n\n".
format(fullname,
242 _typeStr(ConfigClass)))
252 return value.toDict()
258 if self.
check is not None and not self.
check(value):
259 msg =
"%s is not a valid value" % str(value)
263 """Customize deep-copying, because we always want a reference to the original typemap. 265 WARNING: this must be overridden by subclasses if they change the constructor signature! 268 default=copy.deepcopy(self.
default))
270 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
271 """Helper function for Config.compare; used to compare two fields for equality. 273 @param[in] instance1 LHS Config instance to compare. 274 @param[in] instance2 RHS Config instance to compare. 275 @param[in] shortcut If True, return as soon as an inequality is found. 276 @param[in] rtol Relative tolerance for floating point comparisons. 277 @param[in] atol Absolute tolerance for floating point comparisons. 278 @param[in] output If not None, a callable that takes a string, used (possibly repeatedly) 279 to report inequalities. 281 Floating point comparisons are performed by numpy.allclose; refer to that for details. 283 c1 = getattr(instance1, self.name)._value
284 c2 = getattr(instance2, self.name)._value
286 _joinNamePath(instance1._name, self.name),
287 _joinNamePath(instance2._name, self.name)
289 return compareConfigs(name, c1, c2, shortcut=shortcut, rtol=rtol, atol=atol, output=output)
def save(self, outfile, instance)
def __setattr__(self, name, value, at=None, label="assignment")
def freeze(self, instance)
def compareConfigs(name, c1, c2, shortcut=True, rtol=1E-8, atol=1E-8, output=None)
def __init__(self, doc, target, ConfigClass=None, default=None, check=None)
def __initValue(self, at, label)
def __get__(self, instance, owner=None, at=None, label="default")
def _setup(self, doc, dtype, default, check, optional, source)
def validateTarget(self, target, ConfigClass)
def getStackFrame(relative=0)
def toDict(self, instance)
def validate(self, instance)
def format(config, name=None, writeSourceLine=True, prefix="", verbose=False)
def retarget(self, target, ConfigClass=None, at=None, label="retarget")
def __deepcopy__(self, memo)
def rename(self, instance)
def __init__(self, config, field, at=None, label="default")
def __getOrMake(self, instance, at=None, label="default")
def __delattr__(self, name, at=None, label="delete")
def apply(self, args, kw)
def __get__(self, instance, owner=None, at=None, label="default")
def __set__(self, instance, value, at=None, label="assignment")
def getComparisonName(name1, name2)
def __getattr__(self, name)