Best way to instantiate a param.Dict?

import param
import panel as pn
pn.extension()

class Test(param.Parameterized):
    x = param.Dict(default={}, instantiate=True)
    
    def __init__(self):
        print(self.x)
        self.x["key"] = "value"

If I remove default={}, it doesn’t work anymore (I thought instantiate would work alone)

Or is it better to do:

import param
import panel as pn
pn.extension()

class Test(param.Parameterized):
    x = param.Dict(instantiate=True)
    
    def __init__(self):
        self.x = {}
        print(self.x)
        self.x["key"] = "value"

The default for a Dict parameter is None, and with instantiate=True you’ll just get a fresh copy of None per instance. It seems like what you’re trying to get is a separate empty dictionary per instance, in which case, yes, supplying default={} seems like the right way to go about that.

To clarify, with default={} and instantiate=True, there’s no issue with unexpected mutations?

e.g. Python’s mutable keyword arguments

def test(x={}):
    x["a"] = "b"

should be written like

def test(x=None):
    if x is None:
        x = {}
    x["a"] = "b"

There shouldn’t be, because param does a copy.deepcopy(param_obj.default) when instantiate=True, unlike Python function arguments.

1 Like