Python feature request : operator for function composition

Arnaud Delobelle arnodel at googlemail.com
Mon Feb 4 11:11:51 EST 2008


On Feb 4, 3:00 pm, Dustan <DustanGro... at gmail.com> wrote:
> On Feb 2, 11:09 pm, Kay Schluehr <kay.schlu... at gmx.net> wrote:
> [snip]
>
> While you're waiting for it to be implemented, you can build your own
> version as a decorator. Here's an example written in haste:
>
> >>> class composer(object):
>
>         def __init__(self, *funcs):
>                 self.funcs = funcs
>         def __and__(self, other):
>                 if isinstance(other, composer):
>                         return composer(*(self.funcs+other.funcs))
>                 else:
>                         return composer(*(self.funcs+(other,)))
>         def __call__(self, *args, **kargs):
>                 for func in reversed(self.funcs):
>                         args = (func(*args, **kargs),)
>                         if kargs:
>                                 kargs = {}
>                 return args[0]
>
> >>> @composer
>
> def double(x):
>         return 2*x
>
> >>> @composer
>
> def square(x):
>         return x*x
>
> >>> double_square = double & square
> >>> square_double = square & double
> >>> double_square(2)
> 8
> >>> square_double(2)
> 16
> >>> double_square(3)
> 18
> >>> square_double(3)
> 36
> >>> double_square(4)
> 32
> >>> square_double(4)
>
> 64
>
> Probably not the best implementation, but you get the idea.

This is nice.
* I wouldn't choose '&' as the composing operator as when I read
'double & square' I think 'take an x, double it & square it' which is
the wrong interpretation (perhaps << instead?).
* I would call the decorator 'composable'.

--
Arnaud



More information about the Python-list mailing list