Is there a function that applies list of functions to a value?

fp2161 at gmail.com fp2161 at gmail.com
Fri Aug 30 02:17:19 EDT 2013


On Wednesday, August 28, 2013 8:50:53 PM UTC+2, Josh English wrote:
> Reduce tricks are nice, but I prefer clarity sometimes:
> 
> 
> 
> def double(x):
> 
>     return x*2
> 
> 
> 
> def add3(x):
> 
>     return x+3
> 
> 
> 
> 
> 
> def compose(*funcs):
> 
>     for func in funcs:
> 
>         if not callable(func):
> 
>             raise ValueError('Must pass callable functions')
> 
> 
> 
>     def inner(value):
> 
>         for func in funcs:
> 
>             value = func(value)
> 
>         return value
> 
> 
> 
>     return inner
> 
> 
> 
> 
> 
> add_then_double = compose(add3, double)
> 
> double_then_add = compose(double, add3)
> 
> 
> 
> print add_then_double(1) # prints 8
> 
> print double_then_add(1) # prints 5


This is my favourite design, simple, clear, straightforward, very pythonic imho.  So great that I actually dod not notice it, and wrote it again after you! Imho still, the ValueError you are raising is not that important in this context, it would raise an Error anyway.



More information about the Python-list mailing list