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.\"\"\"
There's quite a simple method for doing this that nobody has mentioned yet:
import inspect
def func():
"""Doc string"""
print inspect.getdoc(func)
And this does what you want.
There's nothing fancy going on here. All that's happening is that by doing func.__doc__
in a function defers attribute resolution long enough to have looking up __doc__
on it work as you'd expect.
I use this with docopt for console script entry points.
You've posed your question like a class method rather than a function. Namespaces are important here. For a function, print my_function.__doc__
is fine, as my_function is in the global namespace.
For a class method, then print self.my_method.__doc__
would be the way to go.
If you don't want to specify the name of the method, but rather pass a variable to it, you can use the built-in functions hasattr(object,attribute) and getattr(obj,attr), which do as they say, allowing you to pass variables in with strings being the name of a method. e.g.
class MyClass:
def fn(self):
"""A docstring"""
print self.fn.__doc__
def print_docstrings(object):
for method in dir( object ):
if method[:2] == '__': # A protected function
continue
meth = getattr( object, method )
if hasattr( meth , '__doc__' ):
print getattr( meth , '__doc__' )
x = MyClass()
print_docstrings( x )