How to add and remove callbacks from on_change events properly?

I wanted to remove the callback that is triggered when some attribute is updated. But I found that using the method remove_on_change throws an error when the callback does not exist. Then I had to do this to prevent that:

    attr = 'value'
    if select_widget._callbacks != {} and attr in select_widget._callbacks and select_widget._callbacks[attr] != []:
        select_widget.remove_on_change(attr, on_change_some_value)

I don’t have other way to check if the callback is added or not to the attribute. As _callbacks attribute is meant to be private I don’t know if this is the most correct way to do it.

If I do not have any other better recommendation I would still use that code.

Update

Ah!! This may be a better approach:

    try:
        select_widget.remove_on_change('value', on_change_some_value)
    except Exception as e:
        lg.warning('Select callback could not be removed')

But how to check if the callback is already added to prevent from adding it again?

It’s not a question I can recall having come up before. Offhand the only other suggestion I have is to manually do whatever bookkeeping is required to know what you have already added, what has been removed, etc.

1 Like