Created
April 27, 2017 22:44
-
-
Save numberoverzero/59458b8ecd47f9944e7b00763fd37f35 to your computer and use it in GitHub Desktop.
Nested handlers without recursion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Any, Callable, Iterable | |
def noop(next_handler: Callable, *args: Any, **kwargs: Any) -> None: | |
pass | |
def process(handlers: Iterable[Callable], *args: Any, **kwargs: Any) -> None: | |
next_args = args | |
next_kwargs = kwargs | |
continue_processing = True | |
def next_handler(*args: Any, **kwargs: Any) -> None: | |
nonlocal next_args, next_kwargs, continue_processing | |
next_args = args | |
next_kwargs = kwargs | |
continue_processing = True | |
for handler in [*handlers, noop]: | |
if not continue_processing: | |
break | |
continue_processing = False | |
handler(next_handler, *next_args, **next_kwargs) # type: ignore |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def first(next_handler: Callable, client: str, data: str) -> None: | |
print("in first") | |
print(client, data) | |
next_handler(client + "(1)", data + "(1)") | |
def second(next_handler: Callable, client: str, data: str) -> None: | |
print("in second") | |
print(client, data) | |
next_handler(client + "(2)", data + "(2)") | |
def third(next_handler: Callable, client: str, data: str) -> None: | |
print("in third") | |
print(client, data) | |
next_handler(client + "(3)", data + "(3)") | |
process([first, second, third], "client", "data") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment