Created
June 30, 2017 16:54
-
-
Save saintsGrad15/f42caf5328615549ca89ac3cac8e4388 to your computer and use it in GitHub Desktop.
A composition class for Python
This file contains 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
class Compose(object): | |
""" | |
Return a function that, when called, will execute each function in 'functions' | |
in order, passing the return value of each to the next one | |
and returning the result of the last one. | |
NOTE: Generator functions cannot be used. | |
:param functions: A list of functions. | |
NOTE: Ensure that the output of one function makes sense | |
as an input to the next function. A list of values can be | |
returned. They will be unpacked and passed as positional | |
arguments to the next function. | |
:return: A function that will compose 'functions' | |
""" | |
def __init__(self, functions=list()): | |
self.functions = functions | |
if len(self.functions) < 1: | |
raise Exception("At least one function must be passed.") | |
if not all(map(lambda function_: callable(function_), self.functions)): | |
raise Exception("All elements of the argument must be callable.") | |
def compose(self, *args, **kwargs): | |
""" | |
Execute each function in 'functions' in order, | |
passing the return value of each to the next one | |
and returning the result of the last one. | |
NOTE: It is optimally maintainable if | |
each function signature is the same. | |
:param args: An arbitrary list of positional arguments | |
:param args: An arbitrary dict of keyword arguments | |
:return: The return value of the last element of 'functions. | |
""" | |
# Call the first function | |
result = self.functions[0](*args, **kwargs) | |
# Call each function | |
for function_ in self.functions[1:]: | |
# Coerce 'result' to a list if it is not one | |
if type(result) is not list: | |
result = [result] | |
# Call 'function' by unpacking 'result' to positional arguments | |
result = function_(*result) | |
# Return the result of the final function call | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment