observable
observable copied to clipboard
How to obtain trigger callback returns
First, thanks for this neat package! It looks like it's not possible to obtain the return value of the triggered callbacks as trigger('foo')
always returns True
.
However, I think it would be nice to have this option to use callbacks to influence the control flow. Consider the following example where an event is triggered in a save method.
def save(data):
observable.trigger('save', data)
with open('bla.txt') as f:
f.write(data)
# ...
observable.on('save', lambda data: True)
The user can hook into the save method but the callback cannot send anything back to influence what's happening at the trigger point, like here:
def save(data):
if observable.trigger('save', data) is False:
return
with open('bla.txt') as f:
f.write(data)
# ...
def custom_save(data):
with open('a_differnt_save_method.txt') as f:
f.write(data)
return False # returns False to prevent execution of default save logic
observable.on('save', custom_save)
If trigger
would collect the callback returns such 'extension via event' could be implemented. Would you consider enhancing the trigger behaviour?
Looking a bit more closely, if I change the trigger function to
def trigger(self, event: str, *args: T.Any, **kw: T.Any) -> list:
callbacks = list(self._events.get(event, []))
return [callback(*args, **kw) for callback in callbacks]
the return is not bool any longer. However, it would behave like it since bool([]) is False
. I'd be happy to prepare a pull request for that.