Skip to content

Instantly share code, notes, and snippets.

@maxsei
Last active July 28, 2021 15:04
Show Gist options
  • Save maxsei/1185a4eecb2046cc270fef9a901da6ad to your computer and use it in GitHub Desktop.
Save maxsei/1185a4eecb2046cc270fef9a901da6ad to your computer and use it in GitHub Desktop.
Chain functions together by defining the order of operations that are performed on an object. Can allow users to dynamically create functions.
from functools import partial
def add(x, y):
return x + y
def mul(x, y):
return x * y
def chain(obj, funcs, callback=None):
func = funcs[-1]
if callback:
callback(funcs)
if len(funcs) == 1:
return func(obj)
return func(chain(obj, funcs[:-1], callback=callback))
ops = [
partial(add, 2),
partial(mul, 3),
partial(add, -1),
]
x_plus_2_times_three_minus_1 = partial(
chain,
funcs=[
partial(add, 2),
partial(mul, 3),
partial(add, -1),
],
)
print(chain(5, ops, callback=lambda xx: print("on function: ", xx[-1])))
"""
>>> on function: functools.partial(<function add at 0x7f2ab0d4cea0>, -1)
>>> on function: functools.partial(<function mul at 0x7f2ab0d4ce18>, 3)
>>> on function: functools.partial(<function add at 0x7f2ab0d4cea0>, 2)
>>> 20
"""
print(x_plus_2_times_three_minus_1(5))
"""
>>> 20
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment