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

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


def my_func():    """Docstring goes here."""    print my_func.__doc__

This will work as long as you don't change the object bound to the name my_func.

new_func_name = my_funcmy_func = Nonenew_func_name()# doesn't print anything because my_func is None and None has no docstring

Situations in which you'd do this are rather rare, but they do happen.

However, if you write a decorator like this:

def passmein(func):    def wrapper(*args, **kwargs):        return func(func, *args, **kwargs)    return wrapper

Now you can do this:

@passmeindef my_func(me):    print me.__doc__

And this will ensure that your function gets a reference to itself (similar to self) as its first argument, so it can always get the docstring of the right function. If used on a method, the usual self becomes the second argument.


This should work (in my tests it does, also included output). You could probably use __doc__ instead of getdoc, but I like it, so thats just what i used. Also, this doesn't require you to know the names of the class/method/function.

Examples both for a class, a method and a function. Tell me if it's not what you were looking for :)

from inspect import *class MySelfExplaningClass:    """This is my class document string"""    def __init__(self):        print getdoc(self)    def my_selfexplaining_method(self):        """This is my method document string"""        print getdoc(getattr(self, getframeinfo(currentframe()).function))explain = MySelfExplaningClass()# Output: This is my class document stringexplain.my_selfexplaining_method()# Output: This is my method document stringdef my_selfexplaining_function():    """This is my function document string"""    print getdoc(globals()[getframeinfo(currentframe()).function])my_selfexplaining_function()# Output: This is my function document string


This works:

def my_function():  """Docstring for my function"""  #print the Docstring here.  print my_function.__doc__my_function()

in Python 2.7.1

This also works:

class MyClass(object):    def my_function(self):        """Docstring for my function"""        #print the Docstring here, either way works.        print MyClass.my_function.__doc__        print self.my_function.__doc__foo = MyClass()foo.my_function()

This however, will not work on its own:

class MyClass(object):    def my_function(self):        """Docstring for my function"""        #print the Docstring here.        print my_function.__doc__foo = MyClass()foo.my_function()

NameError: global name 'my_function' is not defined