Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

PipeLine

By: a guest on Jan 16th, 2013  |  syntax: Python  |  size: 1.39 KB  |  views: 986  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. def PipeLine(*args, **kwargs):
  2.     """
  3.    Given an arbitrary number of functions we create a pipeline where the output
  4.    is piped between functions. you can also specify a tuple of arguments that
  5.    should be passed to functions in the pipeline. The first arg is always the
  6.    output of the previous function.
  7.    """
  8.     def wrapper(*data):
  9.         if len(args) == 1:
  10.             if args[-1].__name__ in kwargs:
  11.                 otherArgs = data + kwargs[args[-1].__name__]
  12.                 return args[-1](*otherArgs)
  13.             else:
  14.                 return args[-1](*data)
  15.         else:
  16.             if args[-1].__name__ in kwargs:
  17.                 otherArgs = kwargs[args[-1].__name__]
  18.                 del kwargs[args[-1].__name__]
  19.                 return args[-1](PipeLine(*args[:-1], **kwargs)(*data), *otherArgs)
  20.             else:
  21.                 return args[-1](PipeLine(*args[:-1], **kwargs)(*data))
  22.     return wrapper
  23.  
  24.  
  25. def testPipelineWithArgs():
  26.     """
  27.    Test all the major functionality:
  28.    multiple functions, initial arguments
  29.    per function arguments stored in kwargs
  30.    """
  31.     def add1(input_):
  32.         return input_ + 1
  33.  
  34.     def subX(input_, x):
  35.         return input_ - x
  36.  
  37.     def stringify(input_):
  38.         return str(input_)
  39.  
  40.     pipeline = PipeLine(
  41.         add1,
  42.         subX,
  43.         stringify,
  44.         subX=(2,),
  45.         )
  46.     print pipeline(10)