Two syntax questions (newbie)

Michael Hoffman cam.ac.uk at mh391.invalid
Mon Apr 23 11:09:16 EDT 2007


Diez B. Roggisch wrote:
>> This is already better. Is it possible to define function composition
>> as an operator and have something like (list at reversed@sorted)(items)
>> or (list*reversed*sorted)(items) ?
> 
> Not on functions, but on classes/instances. So something like this might
> work for you (untested):
> 
> class FunctionComposer(object):
>     def __init__(self, f=None):
>         if f is None:
>            f = lambda x: x
>         self._f = f
> 
>     def __call__(self, *args, **kwargs):
>         return self._f(*args, **kwargs)
> 
>     def __mul__(self, other):
>         def combined(*args, **kwargs):
>             return other(self._f(*args, **kwargs))
>         return FunctionComposer(combined)
> 
> fc = FunctionComposer
> 
> Then you can write
> 
> (fc() * list * reversed * sorted)(items)

A clever little hack, but please don't do this. Anyone else who will 
read your code will thank you.
-- 
Michael Hoffman



More information about the Python-list mailing list