Python feature request : operator for function composition

Kay Schluehr kay.schluehr at gmx.net
Sun Feb 3 18:38:24 EST 2008


On Feb 3, 11:34 pm, George Sakkis <george.sak... at gmail.com> wrote:
> On Feb 3, 12:09 am, Kay Schluehr <kay.schlu... at gmx.net> wrote:
>
> > As you know, there is no operator for function composition in Python.
> > When you have two functions F and G and  want to express the
> > composition F o G you have to create a new closure
>
> > lambda *args, **kwd: F (G (*args, **kwd))
>
> > or you write a composition in functional style
>
> > compose( F, G )
>
> > None of these solutions is particular terse.
>
> What if F takes more than one (positional and/or keyword) arguments?
> How common is this special use case where F takes a single argument
> (the result of G) to deserve a special operator ?
>
> George

O.K. Point taken. Here is a more general form of compose that is
applicable when both F and G take *args and **kwd arguments.

def compose(F,G):
    def prepare_args(args, kwd = {}):
        return args if isinstance(args, tuple) else (args,), kwd
    def apply_composition(*args, **kwd):
        nargs, nkwd = prepare_args(G(*args, **kwd))
        return F(*nargs, **nkwd)
    return apply_composition








More information about the Python-list mailing list