You could create a function decorator, similar to below:
def get_docstring(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs), func.__doc__
return wrapper
@get_docstring
def square(n):
"""
Returns the square of n
"""
return n ** 2
When calling the square()
function:
>>> square(5)
(25, '\n\tReturns the square of n\n\t')
>>> res, doc = square(5)
>>> res
25
>>> doc
'\n\tReturns the square of n\n\t'
>>> print(doc)
Returns the square of n
For print the docstring inside the function, just pass func.__doc__
before passing **kwargs
inside wrapper()
:
def get_docstring(func):
def wrapper(*args, **kwargs):
return func(*args, func.__doc__, **kwargs)
return wrapper
@get_docstring
def square(n, doc):
"""
Returns the square of n
"""
print(doc)
return n ** 2
When calling the square()
function:
>>> square(5)
Returns the square of n
25