Skip to content

Instantly share code, notes, and snippets.

@btknight
Created January 23, 2023 20:01
Show Gist options
  • Save btknight/b9b8081890cd854bb013dfa904d0f3fd to your computer and use it in GitHub Desktop.
Save btknight/b9b8081890cd854bb013dfa904d0f3fd to your computer and use it in GitHub Desktop.
"""Helper class to run a chain of callbacks on input data."""
from typing import Callable, Any
class CbChain(object):
"""Chain callbacks together.
Instances of this object are themselves Callable. When called, it passes the supplied arguments to the first
callback in the chain. The result of the first callback is fed to the second, the result of the second fed to
the third, and so on.
Sample usage:
> p = CbChain(lambda x: x + 9).CbChain(lambda x: x * 3)
> p(3)
36
Attributes
cb: Callable
The Callable to be run when this object is itself called.
prev: CbChain
The CbChain object whose callback should be run before the callback in this object.
"""
def __init__(self, cb: Callable[..., Any]):
self.cb = cb
self.prev = None
def CbChain(self, cb: Callable[..., Any]):
"""Returns a new Pipe object linked to the current with the supplied callback."""
new_pipe = CbChain(cb)
new_pipe.prev = self
return new_pipe
def __call__(self, *args, **kwargs) -> Any:
"""Runs the chain of callbacks on command line arguments."""
if self.prev is not None:
return self.cb(self.prev(*args, **kwargs))
else:
return self.cb(*args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment