Add dependencies between functions and a dynamic number of params

Hi, I have a param.parameterized class, in which I initialized a certain number of params with the self.param._add_parameter() function. It works very well but now I need to link these parameters to some functions in order to refresh the visualization when I change a parameter.
In that case I don’t think I can use the @param.depends decorator since I need to link a parameter to a function of an already instantiated object.

I tried to use the function param.depends(viewer.myfunc,‘myparam’), it changes the attribute dinfo, but the dependence doesn’t work in the resulting panel GUI.

Is there a way to link some parameters and some function of an instantiated object without using the @param.depends() decorator ?

Here is an example :

class testview(param.Parameterized):
    check_val=0

    def add_parameters(self,k):
          for i in range(k):
               self.param._add_parameter(f'param{i}',param.Integer(default=0))

    def increment_val(self):
          self.check_val+=1
          return hv.Text(0.5,0.5, str(self.check_val))


viewer = testview()
viewer.add_parameters(3)
pn.Row(pn.Param(viewer.param),viewer.increment_val())

In this example I have now 3 Integer widget and a holoview display of the attribute check_val.
I want to link each param to the increment_val() function, in order to refresh the view when I change the value of a parameter.

Hi @AurelienSciarra

One way is to use self.param.watch, make your check_val a parameter and make the plot function dependent on changes in check_val.

import param
import panel as pn
import holoviews as hv
from param import parameterized

class testview(param.Parameterized):
    check_val = param.Integer(default=0)
    parameters = param.List(default=[])

    def add_parameters(self,k):
        parameters = self.parameters
        for i in range(k):
            name = f'param{i}'
            self.param._add_parameter(name, param.Integer(default=0))
            parameters.append(name)
        self.param.watch(self.increment_val, parameters)
        self.parameters = parameters

    def increment_val(self, *events):
        self.check_val+=1
        print(self.check_val)

    @param.depends("check_val")
    def plot(self):
        print("plot")
        return hv.Text(0.5,0.5, str(self.check_val))


viewer = testview()
viewer.add_parameters(3)
pn.Row(pn.Param(viewer.param, parameters=viewer.parameters),viewer.plot).servable()

1 Like

@Marc Thank you, It works now.

I’ve tried something similar but it didn’t work well because I didn’t put *events in the increment_val function.

I’ll try to use this method on a more complex case

1 Like

Hi @AurelienSciarra

Thanks for feedback.

Regarding the events. I think there would have been errors shown in the Browser console.You can look for them using CTRL+shift+I.