In the following code, I would like b.view to update when any of the a values are updated.
import param as pm
import panel as pn
pn.extension()
class A(pm.Parameterized):
a = pm.Integer(0)
class B(pm.Parameterized):
a_list = pm.List(class_=A)
def sum_a_list(self):
return sum([a.a for a in self.a_list])
@pm.depends('a_list')
def view(self):
return pn.Row(self, self.sum_a_list)
a1 = A(a=1)
a2 = A(a=2)
b = B(a_list=[a1,a2])
pn.Column(a1, a2, b.view)
Does anyone know how this can be achieved?
Thanks!
With a little help from chatgpt I was able to achieve this functionality:
import param as pm
import panel as pn
pn.extension()
class A(pm.Parameterized):
a = pm.Integer(0)
class B(pm.Parameterized):
a_list = pm.List(class_=A)
@pm.depends('a_list', watch=True, on_init=True)
def _update_watchers(self):
for a in self.a_list:
# Watch the 'a' parameter of each instance in a_list
a.param.watch(self._on_a_change, 'a')
def _on_a_change(self, event):
# Trigger an update when 'a' changes
self.param.trigger('a_list')
def sum_a_list(self):
return sum([a.a for a in self.a_list])
@pm.depends('a_list')
def view(self, *args): # Modified to accept *args
return pn.Column(*self.a_list, self, self.sum_a_list())
a1 = A(a=1)
a2 = A(a=2)
b = B(a_list=[a1, a2])
pn.Column(b.view)
Is there a more straightforward way of doing it?
I’m having performance issues with the above.