0

Dear ipywidgets gurus,

I want to set up a link between the attribute of some python object and the value of some ipywidget:

import ipywidgets as ipyw

w = ipyw.IntSlider(42)

class Foo(object):
    def __init__(self, i=0):
        self.i = i  # not a traitlet, just an integer
foo = Foo(w.value)

two_way_link((w, 'value'), (foo, 'i'))  # mimics ipyw.link()

foo.i = 5  # will move the slider of w
w.value = 8  # update foo.i

I thought of two_way_link instantiating a wrapper traitlet around foo.i and then use ipyw.link with this wrapper and w.value. Maybe someone can suggest and alternative method?

jmborr
  • 1,215
  • 2
  • 13
  • 23

1 Answers1

1

Normal python attributes (Foo.i, here) do not give any signals/events out of the box, so there is not any existing way to do this. A one way link from the traitlet to the attribute is possible by observing the traitlet, and having the handler set the attribute (ipywidget.dlink might already support this, not sure). Having something that goes the other way, you might have some luck with a __setattr__ method on Foo (https://docs.python.org/2/reference/datamodel.html#object.setattr).

Vidar
  • 1,777
  • 1
  • 11
  • 15
  • yes, in the end I had to resort to `Foo.__setattr__` to notify the ipywidget of changes in Foo instances. Thanks for the tip – jmborr May 30 '18 at 12:32