Hi there, I am just starting to get quite fond the really nice possibilities the param
library has to offer
To give some context, I would like to make the param.Color
parameter also accept also short color names. This implies that short color names must be “translated” into valid color names before setting the value.
I am currently trying to customize some validation behavior but I could not find a “proper” way to do it in the documentation. So far I found 2 possibility to implement input transformation before validation but I am not sure either of those is the “right way”.
I would be already greatful if someone could point me in the right direction. Thanks
Solution 1: Subclassing param.Color
and intercept __set__
import param
SHORT_COLOR_MAPPING = {
"r": "red",
"g": "green",
"b": "blue",
"y": "yellow",
"m": "magenta",
"c": "cyan",
"k": "black",
"w": "white",
}
class MyParamColor(param.Color):
def __set__(self, obj, val):
val = SHORT_COLOR_MAPPING.get(val, val)
super().__set__( obj, val)
class Box(param.Parameterized):
color = MyParamColor()
mybox = Box()
mybox.color='r'
mybox.color
# [out] 'red'
Solution 2: Intercept __setattr__
on the main class where param.Color
is defined
import param
SHORT_COLOR_MAPPING = {
"r": "red",
"g": "green",
"b": "blue",
"y": "yellow",
"m": "magenta",
"c": "cyan",
"k": "black",
"w": "white",
}
class Box(param.Parameterized):
color = param.Color()
def __setattr__(self, name, value):
if name=='color':
value = SHORT_COLOR_MAPPING.get(value, value)
super().__setattr__(name, value)
mybox = Box()
mybox.color='r'
mybox.color
# [out] 'red'