So my scenario is the following: I would like my parameterized class to have a parameter that is set during initialization, and never changed again. constant=True
seems to do the trick except I can’t dynamically set the parameter during the initialization:
class T(param.Parameterized):
c = param.Parameter(default=None, constant=True)
d = param.Parameter(constant=False)
def __init__(self, *argv, **kwarg):
super().__init__(*argv, **kwarg)
if self.c is None:
self.c = self.d*2 # TypeError: Constant parameter 'c' cannot be modified
t = T(d=123)
A workaround could be using a context manager, but this seems overkill, see below. Is there any way param
can accommodate the desired behavior, possibly by another kwarg on param.Parameter
?
Thanks!
class ModifyConstant:
def __init__(self, instance, name):
self.instance = instance
self.name = name
if not getattr(instance.param, name).constant:
instance.param.warning('Modifying a parameter with a mechanism intended for constants')
def __enter__(self):
self._set_constant(self.instance, self.name, False)
return self
def __exit__(self, *exc):
self._set_constant(self.instance, self.name, True)
@staticmethod
def _set_constant(instance, name, val):
getattr(instance.param, name).constant = val
class T(param.Parameterized):
c = param.Parameter(constant=True)
d = param.Parameter(constant=False)
def __init__(self, *argv, **kwarg):
super().__init__(*argv, **kwarg)
if self.c is None:
with ModifyConstant(self, 'c'):
self.c = self.d*2+1
t = T(c=None, d=123)
t
PS: The param code also seems to indicate that parameters can be computed/updated on the fly, using hooks. I never managed to figure out how that would work, but maybe that would address the problem here?