pythonfunctools

Why should I set the __doc__ of a partial object in Python?


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?


Solution

  • 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