traitlets
traitlets copied to clipboard
Override default config of children in the hierarchy
Consider a configurable that has a child configurable:
from traitlets.config import Configurable, Config
from traitlets import Int
class Child(Configurable):
value = Int(default_value=1).tag(config=True)
class Parent(Configurable):
classes = [Child]
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.child = Child(parent=self)
print(Child().value)
print(Parent().child.value)
Is it possible to have Parent override the default value for Child.value? So that e.g. Parent().child.value is 3 but Child().value is still 1?
I think there's a couple of ways you could try to work around it, for example (1) using the @default decorator to dynamically check in Child if it has self.parent set (probably a bit of an anti-pattern, but could use some kind of dependency injection here)
@default("value")
def _default_value(self):
if self.parent:
return self.parent.get_default_value()
else:
return self.__class__.value.default_value
or (2) by explicitly constructing Child with the new default, and then calling .update_config():
self.child = Child(value=3)
self.child.parent = self
self.child.update_config(self.config)
Closing as stale, feel free to re-open.