[Python-ideas] Function composition (was no subject)
Ron Adam
ron3200 at gmail.com
Sun May 10 21:55:03 CEST 2015
On 05/10/2015 05:57 AM, Steven D'Aprano wrote:
> There's lots of code that assumes that a tuple of functions is a
> sequence:
>
> for f in (len, str, ord, chr, repr):
> test(f)
>
> so we would need to keep that. But we don't want a composed function to
> be a sequence, any more than we want a partial or a regular function to
> be sequences. If I pass you a Composed object, and you try slicing it,
> that should be an error.
It seems to me a linked list of composed objects works (rather than a
sequence). It's easier to understand what is going on in it.
from functools import partial
from operator import *
from statistics import mean
def root(x):
return x ** .5
def square(x):
return x ** 2
class CF:
def __init__(self, f, *rest):
if isinstance(f, tuple):
self.f = partial(*f)
else:
self.f = f
if rest:
self.child = CF(*rest)
else:
self.child = None
def __call__(self, data):
if self.child == None:
return self.f(data)
return self.f(self.child(data))
def __repr__(self):
if self.child != None:
s = repr(self.child)
else:
s = "CS()"
return s[:3] + ("%s, " % repr(self.f)) + s[3:]
CF(print, root, mean, (map, square)) ([4, 9, 16])
Prints:
10.847426730181986
More information about the Python-ideas
mailing list