Skip to content

Instantly share code, notes, and snippets.

@joedougherty
Last active April 4, 2020 17:03
Show Gist options
  • Save joedougherty/71564fffbe45dfe6dc433de3170d2662 to your computer and use it in GitHub Desktop.
Save joedougherty/71564fffbe45dfe6dc433de3170d2662 to your computer and use it in GitHub Desktop.
A small to class to chain together multiple single-argument functions.
class FunctionChain:
"""
Chains together two or more functions together
and returns final result when called.
functions:
* must be named
* must take *exactly one* required argument
* ought to have explict return statements
# Example code:
def multiply_by_4(n):
return n * 4
def add_12(n):
return n + 12
def divide_by_2(n):
return n/2
special_op = FunctionChain(
multiply_by_4,
add_12,
divide_by_2,
)
# This call ...
special_op(5)
# ... is functionally equivalent to:
divide_by_2(add_12(multiply_by_4(5)))
# Also: has a cute string representation
>> print(special_op)
multiply_by_4() -> add_12() -> divide_by_2()
"""
def __init__(self, *functions):
self.functions = [f for f in functions]
def __call__(self, arg):
for idx, fn in enumerate(self.functions):
if idx == 0:
result = fn(arg)
else:
result = fn(result)
return result
def __repr__(self):
return " -> ".join(["{}()".format(f.__name__) for f in self.functions])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment