Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial function application with the original docstring in Python?

For partial function application, I know there are several ways to do that in Python. However, they seems not to preserve the original function's docstring.

Take functools.partial as example:

from functools import partial

def foo(a, b, c=1):
    """Return (a+b)*c."""
    return (a+b)*c

bar10_p = partial(foo, b=10)
print bar10_p.__doc__

partial(func, *args, **keywords) - new function with partial application 
of the given arguments and keywords.

Let's try fn.py:

from fn import F

def foo(a, b, c=1):
    """Return (a+b)*c."""
    return (a+b)*c

bar10_F = F(foo, b=10)
print bar10_F.__doc__

Provide simple syntax for functions composition
(through << and >> operators) and partial function
application (through simple tuple syntax).

Usage example:

>>> func = F() << (_ + 10) << (_ + 5)
>>> print(func(10))
25
>>> func = F() >> (filter, _ < 6) >> sum
>>> print(func(range(10)))
15

Is there any Python package/module providing partial application with preserved docstring?

UPDATE

As @Kevin and @Martijn Pieters mentioned, the function signature has changed such that it is not suggested to stick to the original function's docstring. I realized that I'm looking for an updated docstring with something like foo() with a default b value of 10 (Thanks for Kevin's simple but direct example.).

like image 471
Drake Guan Avatar asked Dec 08 '14 16:12

Drake Guan


1 Answers

__doc__ is writable, on partial objects as well as on functions; simply copy it over:

bar10_p = partial(foo, b=10)
bar10_p.__doc__ = func.__doc__

or use the functools.update_wrapper() function to do the copying for you; it'll copy a few other pieces of metadata for you too:

from functools import update_wrapper

bar10_p = partial(foo, b=10)
update_wrapper(bar10_p, foo)
like image 101
Martijn Pieters Avatar answered Oct 04 '22 01:10

Martijn Pieters