PEP 309 (Partial Function Application) Idea

Giovanni Bajo noway at sorry.com
Sun Jan 15 10:56:22 EST 2006


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





More information about the Python-list mailing list