5

help() doesn't show the __doc__ of a partial object. Yet, the example in the docs sets it:

>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18

Why set __doc__, if it doesn't help?

Community
  • 1
  • 1
Chris Wesseling
  • 6,226
  • 2
  • 36
  • 72
  • 1
    Apparently, `pydoc` does not know about `partial` objects and does not expect them to have a doctoring. In theory, a smarter tool would. – chepner Nov 21 '13 at 15:44
  • Ran into the same. I showed here how to rewrite `partial()` as a decorator factory that preserves `__doc__`: https://stackoverflow.com/a/64093057/534674 – Jake Stevens-Haas Sep 29 '20 at 03:48
  • idk when this changed, but the example works fine in python 3.11. help(basetwo) does show the docstring. – Capi Etheriel Mar 08 '23 at 17:53

2 Answers2

1

It works as expected in python 3.11:

>>> help(basetwo)
Help on partial in module functools:

functools.partial(<class 'int'>, base=2)
    Convert base 2 string to an int.

You might want to consider setting __name__ as well:

>>> basetwo.__name__ = "basetwo"
>>> help(basetwo)
Help on partial in module functools:

basetwo = functools.partial(<class 'int'>, base=2)
    Convert base 2 string to an int.

Or be even more complete: https://stackoverflow.com/a/64093057/383793

Chris Wesseling
  • 6,226
  • 2
  • 36
  • 72
0

setting __doc__ for a partial function is the same as doing this for a larger function:

def somefunc(somerandomarg):
    """This is a docstring
    What I am doing is shorthand for __doc__ = "random docstring"
    For partials, you can't do this, so you set it with __doc__"""
    pass

It's always good to document anything, even partials.

  • I expected them to be the same too. But if you read the `help()` question I linked, you'll see, that they aren't the same; a partial isn't a function, but an object. `help()` will show the __doc__ of the partial class and its methods. – Chris Wesseling Dec 10 '13 at 11:25
  • As it said in the link, you can't override that without messing with the Python code. In Python, though, pydoc will show the docstring when you type it in. –  Dec 10 '13 at 14:28
  • What do you mean by type it in? When I type this in a part.py and `pydoc part.basetwo` shows the __doc__ of partial, not the __doc__ I typed in. – Chris Wesseling Dec 12 '13 at 07:20
  • Go into Python Shell, and define a partial function basetwo like in the docs. Then type in `basetwo(`. Your doc will show up. I think the reason help doesn't work is that no one coded pydoc to appreciate the functional nature of partial objects. However, both accessing the direct `basetwo.__doc__` and typing `basetwo(` will work, so for some things setting `__doc__` actually helps. –  Dec 14 '13 at 21:52