Skip to content

Instantly share code, notes, and snippets.

@numberoverzero
Created April 27, 2017 22:44
Show Gist options
  • Save numberoverzero/59458b8ecd47f9944e7b00763fd37f35 to your computer and use it in GitHub Desktop.
Save numberoverzero/59458b8ecd47f9944e7b00763fd37f35 to your computer and use it in GitHub Desktop.
Nested handlers without recursion
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
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