traitlets icon indicating copy to clipboard operation
traitlets copied to clipboard

Override default config of children in the hierarchy

Open maxnoe opened this issue 4 years ago • 1 comments

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?

maxnoe avatar Nov 16 '21 16:11 maxnoe

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)

azjps avatar Dec 09 '21 23:12 azjps

Closing as stale, feel free to re-open.

azjps avatar Jan 30 '23 09:01 azjps