[Python-ideas] Function composition (was no subject)

Steven D'Aprano steve at pearwood.info
Wed May 6 16:51:35 CEST 2015


On Wed, May 06, 2015 at 03:15:38PM +0200, Ivan Levkivskyi wrote:
> Dear all,
> 
> The matrix multiplication operator @ is going to be introduced in Python
> 3.5 and I am thinking about the following idea:
> 
> The semantics of matrix multiplication is the composition of the
> corresponding linear transformations.
> A linear transformation is a particular example of a more general concept -
> functions.
> The latter are frequently composed with ("wrap") each other. For example:
> 
> plot(real(sqrt(data)))
> 
> However, it is not very readable in case of many wrapping layers.
> Therefore, it could be useful to employ
> the matrix multiplication operator @ for indication of function
> composition. This could be done by such (simplified) decorator:

I like the idea of @ as a function compose operator.

There have been many requests and attempts at support for function 
composition:

http://code.activestate.com/recipes/574458-composable-functions/

http://code.activestate.com/recipes/52902-function-composition/

http://code.activestate.com/recipes/528929-dynamic-function-composition-decorator/

http://blog.o1iver.net/2011/08/09/python-function-composition.html

https://mail.python.org/pipermail/python-dev/2009-August/091161.html

http://stackoverflow.com/questions/2281693/is-it-a-good-idea-to-have-a-syntax-sugar-to-function-composition-in-python


The last one is notable, as it floundered in part on the lack of a good 
operator. I think @ makes a good operator for function composition.


I think that there are some questions that would need to be answered. 
For instance, given some composition:

    f = math.sin @ (lambda x: x**2)

what would f.__name__ return? What about str(f)?


Do the composed functions:

    (spam @ eggs @ cheese)(x)

perform acceptibly compared to the traditional syntax?

    spam(eggs(cheese(x))



-- 
Steve


More information about the Python-ideas mailing list