I am trying to set default values dynamically on instances of a Parameterized Object.
class TabularDataLoader(Loader):
def _field_delimiter_default_fn(self):
""" Read the source file and perform a statistical character analysis of the first 1000 lines,
looking for any characters with an equal number of characters in each line
"""
# print(self)
self.param.field_delimiter.default = '\t'
return 'computed'
# some attributes have compute_default functions, which might be of interest.
field_delimiter = param.Selector(
label = "Field Delimiter",
objects={"comma: ," :',', "tab: \\t": '\t'},
compute_default_fn=_field_delimiter_default_fn, # <- this is calling the class method.
)
When I can Parameterized.param.field_delimiter.compute_default()
then it complains that the called function does not receive the positional self
argument, which I’d expect given the code being called:
# from: https://github.com/holoviz/param/blob/aa484c4305c569a182289793307bd46ee078bf68/param/__init__.py#L1514
def compute_default(self):
"""
If this parameter's compute_default_fn is callable, call it
and store the result in self.default.
Also removes None from the list of objects (if the default is
no longer None).
"""
if self.default is None and callable(self.compute_default_fn):
self.default = self.compute_default_fn() # <- callable is called without arguments
if self.default not in self.objects:
self.objects.append(self.default)
I understand why I get this error in the current configuration, since it has simply stored a reference to the callable object as an instance attribute, and we provided a reference to the class method. Is there a clever way to get that callable to be a reference to the instantiated instance method?
I don’t think that it can be done in the class definition, it would probably have to be done during the instance initialization, which is far less elegant. Would love to be proven wrong though!
if the above compute_default
function was modified to check for named arguments expecting ‘self’ in the supplied callable, then it could be modified to supply self
in the special-case, but I appreciate that that is also not particularly elegant.