Allan Xu
Allan Xu

Reputation: 9298

How to print the __doc__ string of a function inside the function without specifying the name of the function

Lets say I have a function like this:

def square(n):
    '''Takes in a number n, returns the square of n'''
    how_can_I_do_this = __doc__

Is there any way I get the __doc__ string without mentioning the function name? That is, how do I print the __doc__ string of a function inside the function without specifying the name of the function?

Upvotes: 1

Views: 573

Answers (3)

Jacob Lee
Jacob Lee

Reputation: 4680

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

Upvotes: 1

lllrnr101
lllrnr101

Reputation: 2343

You can make use of built-in library inspect to get the required info. You can use it to getinfo about the caller also (which you mention in your comment). Please see example below:

import inspect

def sq(num):
    '''returns square of number'''
    info = inspect.stack()
    current = globals()[info[0].function]
    caller = globals()[info[1].function]
    print(current.__doc__)
    print(caller.__doc__)
    return num*num

def call_sq(num):
    '''calls sq with num'''
    ans = sq(num)
    return ans

def print_sq(num):
    '''calls call_sq to get ans and prints it'''
    ans = call_sq(num)
    print(f'Square of {num} is {ans}')

print_sq(5)

Running this gives me:

returns square of number
calls sq with num
Square of 5 is 25

Upvotes: 1

leaf_soba
leaf_soba

Reputation: 2518

reference:

How to print Docstring of python function from inside the function itself?

code:

import inspect

def square(n):
    '''Takes in a number n, returns the square of n'''
    print(inspect.getdoc(globals()[inspect.getframeinfo(inspect.currentframe()).function]))

square(0)

result:

Takes in a number n, returns the square of n

Upvotes: 2

Related Questions