PEP 309 (Partial Function Application) Idea

bonono at gmail.com bonono at gmail.com
Sun Jan 15 11:50:11 EST 2006


Giovanni Bajo wrote:
> Ronald Mai wrote:
>
> > Here is a reference implementation:
> >
> > _ = lambda x: x.pop(0)
> >
> > def partial(func, *args, **keywords):
> >         def newfunc(*fargs, **fkeywords):
> >             newkeywords = keywords.copy()
> >             newkeywords.update(fkeywords)
> >             newargs = (lambda seq: tuple([(a == _ and a(seq)) or a for
> > a in args] + seq))(list(fargs))
> >             return func(*newargs, **newkeywords)
> >         newfunc.func = func
> >         newfunc.args = args
> >         newfunc.keywords = keywords
> >         return newfunc
> >
> > Here is example of use:
> >
> >>>> def capture(*args):
> > return args
> >
> >>>> partial(capture)()
> > ()
> >>>> partial(capture, _)(1)
> > (1,)
> >>>> partial(capture, _, 2)(1)
> > (1, 2)
> >>>> partial(capture, 1)(2)
> > (1, 2)
> >>>> partial(capture, 1, _)(2)
> > (1, 2)
> >>>> partial(capture, 1, _)()
> > IndexError: pop from empty list
> >>>> partial(capture, 1, _, _)(2, 3)
> > (1, 2, 3)
>
> Other implementations I have seen (boost::bind comes to mind) use ordered
> placeholders such as _1, _2, _3, etc to provide more flexibility in adaptation:
>
> >>> partial(capture, "a", _1, _2)("b", "c")
> ("a", "b", "c")
> >>> partial(capture, "a", _2, _1)("b", "c")
> ("a", "c", "b")
>
> I don't see mention of this in the PEP, but it's a nice feature to have IMO.
> --
> Giovanni Bajo
Since python has named parameter(and I assume this PEP would support it
as well), is it really that useful to have these place holder things  ?
As when the parameter list gets long, named param should be easier to
read.

The only case I find it useful is for binary ops where I would like to
either bind the left hand side or the right hand side but that can be
handled easily with a "flip" function as in haskell.




More information about the Python-list mailing list