Callbacks¶
What are callbacks ?¶
Callback is a functionnality that allows you to call a function to calculate an option’s default value. This is very usefull if an option’s value depends on another one.
It’s structure is the following :
1 | #opt = OptionType('name', 'doc', callback=function_name, callback_params=Params(ParamOption(first_param), ParamOption(second_param), ...))
|
Let’s see with a more concrete example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | # First we'll need a function
def double_value(value : int) :
return value*2
opt1 = IntOption('opt1', '', default=4)
opt2 = IntOption('opt2', '', callback=double_value, callback_params=Params(ParamOption(opt1)))
rootod = OptionDescription('root', '', [opt1, opt2])
cfg = Config(rootod)
# We want opt2 to have the double of opt1's value
print(cfg.option('opt2').value.get())
#>>> 8
# The callback is working !
# But what if we change the value of op1 ?
cfg.option('opt1').value.set(5)
print(cfg.option('opt2').value.get())
#>>> 10
# The value of opt2 changed too !
|
Of course this example is very simple, but you can do a lot more complex ones with bigger functions using much more parameters !
Note
The value returned by the callback function will be the default value of the option,
so you can’t have a default setting parameter with a callback at he same time. You can still
set the option’s value, only its default value will be calculated by the function.