[Python-Dev] functools.compose to chain functions together

Steven D'Aprano steve at pearwood.info
Tue Aug 18 10:01:05 CEST 2009

On Mon, 17 Aug 2009 07:14:05 pm Stefan Behnel wrote:
> Antoine Pitrou wrote:
> > Raymond Hettinger <python <at> rcn.com> writes:
> >> IMO, its only virtue is that people coming from functional
> >> languages are used to having compose.  Otherwise, it's a YAGNI.
> >
> > Then I wonder how partial() ended up in the stdlib. It seems
> > hardly more useful than compose().
> I would certainly consider it more useful, but that aside, it's
> also a lot simpler to understand and use than the proposed
> compose() function. I think the main difference is that compose()
> requires functional/math skills to be used and read correctly (and
> might still be surprising in some corner cases), whereas partial()
> only requires you to understand how to set a function argument.
> Totally different level of mental complexity, IMHO.

I find the opposite -- compose() seems completely simple and 
straight-forward to me, while partial() is still a mystery no matter 
how many times I use it. I always have to look it up to see which way 
it binds.

Putting that aside, partial() too is easy enough to implement with 
lambda: partial(f, 2) is the same as lambda *args: f(2, *args). To my 
mind, there are two important reasons for preferring named functions 
like partial() and compose() over lambda solutions:

* performance: a good C implementation should be better than a 
pure-Python lambda; and

* specificity: there's only one thing compose() or partial() could do, 
whereas a lambda is so general it could do anything. Contrast:

compose(f, g, h)
lambda x: f(g(h(x)))

You need to read virtually the entire lambda before you can 
distinguish it from some other arbitrary lambda:

lambda x: f(g(h))(x)
lambda x: f(g(x) or h(x))
lambda x: f(g(x)) + h(x)

Steven D'Aprano 

More information about the Python-Dev mailing list