Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to obtain trigger callback returns #17

Open
frthjf opened this issue Jan 9, 2019 · 1 comment
Open

How to obtain trigger callback returns #17

frthjf opened this issue Jan 9, 2019 · 1 comment
Assignees

Comments

@frthjf
Copy link

frthjf commented Jan 9, 2019

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?

@frthjf
Copy link
Author

frthjf commented Jan 9, 2019

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.

@timofurrer timofurrer self-assigned this Jan 20, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants