Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to print the docstring of a python function from inside the function itself. for eg.

def my_function(self):   """Doc string for my function."""   # print the Docstring here. 

At the moment I am doing this directly after my_function has been defined.

print my_function.__doc__ 

But would rather let the function do this itself.

I have tried calling print self.__doc__ print self.my_function.__doc__ and print this.__doc__ inside my_function but this did not work.

like image 228
shane87 Avatar asked Jan 11 '12 16:01

shane87


People also ask

How do you print a docstring in a function?

Try: class MyClass(): # ... def my_function(self): """Docstring for my function""" print MyClass. my_function.

How do you display the docstring for a function in Python?

Docstrings are accessible from the doc attribute (__doc__) for any of the Python objects and also with the built-in help() function. An object's docstring is defined by including a string constant as the first statement in the object's definition.

What is print (__ doc __) in Python?

The print(__doc__) command simply re-uses that documentation string to write it to your terminal each time you run the script, and any other python tool (like the interactive interpreter help() function, for example) can introspect that same value.


1 Answers

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_func my_func = None  new_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:

@passmein def 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.

like image 169
kindall Avatar answered Oct 07 '22 12:10

kindall