What is the best way to define nested Parameters in Parameterized class

First approach:

  • is to create separate Parameterized classes
import param as pm

class B(pm.Parameterized):
    class A(pm.Parameterized):
        a = pm.Integer(10)
        b = pm.Number(0)
    
    a = A()
    b = pm.Integer(50)
    
    def __init__(self, **params):
        super().__init__(**params)
        
    @pm.depends("a.a", watch=True)
    def callback(self):
        print(self.a.a * 10)

Second approach:
- as Class Selector

import param as pm



class B(pm.Parameterized):
    class A(pm.Parameterized):
        a = pm.Integer(10)
        b = pm.Number(0)
    
    a = pm.ClassSelector(class_=A, default=A())
    b = pm.Integer(50)
    
    def __init__(self, **params):
        super().__init__(**params)
        
    @pm.depends("a.param", watch=True)
    def callback(self):
        print(self.a.a * 10)

Maybe there are another approaches?
What difference between them?

1 Like

The aim of nested parameters is to create something similar to nested dicts (or nested configs)

1 Like

Hi @Illia

I’ve would do something close to your second approach.

import param as pm

class X(pm.Parameterized):
        a = pm.Integer(10)
        b = pm.Number(0)

class Y(pm.Parameterized):
    c = pm.ClassSelector(class_=X)
    d = pm.Integer(50)

    def __init__(self, **params):
        if not "c" in params:
            params["c"]=X()

        super().__init__(**params)

    @pm.depends("c.param", watch=True)
    def callback(self):
        self.d+=1
        print("c", self.c.a, self.c.b)
        print("d", self.d)

If I add the test_case below to the script

def test_case():
    y=Y()
    for _ in range(0,2):
        y.c.a+=1
        y.c.b+=1

test_case()

and run python name_of_script.py I see

c 11 0
d 51
c 11 1
d 52
c 12 1
d 53
c 12 2
d 54
1 Like

For further inspiration check out the Param subobjects notebook.

1 Like

Oh, I missed this notebook.
Thank you

2 Likes