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

event.named_call #99

Merged
merged 3 commits into from
Nov 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/miniflask/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,31 @@ def fn_wrap(*args, altfn=None, **kwargs):
setattr(self, name, fn_wrap)
return fn_wrap

def named_call(self, event_name, *args, **kwargs):
r"""
Retrieve the names of the modules together with the results.

**Note**:
Can be combined with `event.optional` functionality to return an empty dict if the event has not been registered, yet.

Args:
- `event_name`: (required)
Event to be called.
- `*args`, `**kwargs`:
Arguments to be passed to the event call.

Examples:
```python
for module_id, result in event.named_call('myevent', the_argument=42):
print(f"Module with id {module_id} has returned", result)
```
""" # noqa: W291
eobj = self._mf.event_objs[event_name]
results = getattr(self, event_name)(*args, **kwargs)
if eobj.unique:
results = [results]
return dict(zip(self._data[event_name]["modules"], results))

# disables deepcopy(event), as it is tightly bounded to other miniflask objects
def __deepcopy__(self, memo):
del memo
Expand Down
Empty file.
Empty file.
7 changes: 7 additions & 0 deletions tests/event/named_call/modules/module1/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

def main():
return 1337


def register(mf):
mf.register_event('main', main, unique=False)
Empty file.
8 changes: 8 additions & 0 deletions tests/event/named_call/modules/module2/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@

def main(state):
del state
return 2345


def register(mf):
mf.register_event('main', main, unique=False)
19 changes: 19 additions & 0 deletions tests/event/named_call/test_named_call.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from pathlib import Path
import miniflask # noqa: E402


def test_named_call(capsys):
mf = miniflask.init(
module_dirs=str(Path(__file__).parent / "modules"),
debug=False
)

mf.load(["module1", "module2"])
mf.parse_args([])
for module, result in mf.event.named_call("main").items():
print(module, result)
captured = capsys.readouterr()
assert "\n".join(captured.out.split("\n")[2:]) == """
modules.module1 1337
modules.module2 2345
""".lstrip()