Why should I set the __doc__ of a partial object in Python?
Question:
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?
Answers:
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.
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
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?
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.
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