param.parameterized.Parameters.watch#
- Parameters.watch(fn, parameter_names: str | list[str], what: str = 'value', onlychanged: bool = True, queued: bool = False, precedence: int = 0) Watcher[source]#
Register a callback function to be invoked for parameter events.
This method allows you to register a callback function (
fn) that will be triggered when specified events occur on the indicated parameters. The behavior of the watcher can be customized using various options.- Parameters:
fn (callable) – The callback function to invoke when an event occurs. This function will be provided with
Eventobjects as positional arguments, allowing it to determine the triggering events.parameter_names (str or list[str]) – A parameter name or a list of parameter names to watch for events.
what (str, optional) – The type of change to watch for. By default, this is
'value', but it can be set to other parameter attributes such as'constant'. Default is'value'.onlychanged (bool, optional) – If
True(default), the callback is only invoked when the watched item changes. IfFalse, the callback is invoked even when the`what`item is set to its current value.queued (bool, optional) – By default (
False), additional watcher events generated inside the callback fn are dispatched immediately, effectively doing depth-first processing of Watcher events. However, in certain scenarios, it is helpful to wait to dispatch such downstream events until all events that triggered this watcher have been processed. In such cases settingqueued=Trueon this Watcher will queue up new downstream events generated duringfnuntilfncompletes and all other watchers invoked by that same event have finished executing), effectively doing breadth-first processing of Watcher events.precedence (int, optional) – The precedence level of the watcher. Lower precedence levels are executed earlier. User-defined watchers must use positive precedence values. Negative precedences are reserved for internal watchers (e.g., those set up by
depends()). Default is0.
- Returns:
The
Watcherobject that encapsulates the registered callback.- Return type:
See also
Examples
Register two watchers for parameter changes, one directly in the constructor and one after the instance is created:
>>> import param >>> class MyClass(param.Parameterized): ... a = param.Number(default=1) ... b = param.Number(default=2) ... ... def __init__(self, **params): ... super().__init__(**params) ... self.param.watch(self.callback, ['a']) ... ... def callback(self, event): ... print(f"Event triggered by: {event.name}, new value: {event.new}") ... >>> instance = MyClass()
Watch for changes to
b:>>> instance.param.watch(instance.callback, ['b'])
Trigger a change to invoke the callback:
>>> instance.a = 10 Event triggered by: a, new value: 10 >>> instance.b = 11 Event triggered by: b, new value: 11