Getting the Docstring from a Function

Getting the docstring from a function

Interactively, you can display it with

help(my_func)

Or from code you can retrieve it with (surround it with print(.) to get a formatted output):

my_func.__doc__

How to get the docstring of a function into a variable?

You can use inspect.getdoc, that will process the docstring of the object and return it as string:

>>> import inspect
>>> doc = inspect.getdoc(I)

>>> print(doc)
This is the documentation string (docstring) of this function .
It contains an explanation and instruction for use .

Generally the documentation is stored in the __doc__ attribute:

>>> doc = I.__doc__
>>> print(doc)

This is the documentation string (docstring) of this function .
It contains an explanation and instruction for use .

But the __doc__ won't be cleaned: it might contain leading and trailing empty newlines and the indentation may not be consistent. So inspect.getdoc should be the preferred option.

The following is based on your original question:

To get the documentation of PIL functions you could use:

>>> import PIL
>>> import inspect

>>> doc = inspect.getdoc(PIL.Image.fromarray)
>>> print(doc)
Creates an image memory from an object exporting the array interface
(using the buffer protocol).

If obj is not contiguous, then the tobytes method is called
and :py:func:`~PIL.Image.frombuffer` is used.

:param obj: Object with array interface
:param mode: Mode to use (will be determined from type if None)
See: :ref:`concept-modes`.
:returns: An image object.

.. versionadded:: 1.1.6

To get the documentations of all functions in a module you need to use getattr:

for name in dir(PIL.Image):
docstring = inspect.getdoc(getattr(PIL.Image, name)) # like this

To get a list of all docstrings:

list_of_docs = [inspect.getdoc(getattr(PIL, obj)) for obj in dir(PIL)]

Or if you need to corresponding name then a dict would be better:

list_of_docs = {obj: inspect.getdoc(getattr(PIL, obj)) for obj in dir(PIL)}

However not everything actually has a documentation. For example the PIL.Image module has no docstring:

>>> PIL.Image.__doc__
None
>>> inspect.getdoc(PIL.Image)
None

and when attempting to get the docstring of an instance you might get surprising results:

>>> inspect.getdoc(PIL.__version__)
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.

That's because PIL.__version__ is a string instance and simply shows the docstring of its class: str:

>>> inspect.getdoc(str)  # the built-in "str"
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.

Print docstring from class, function, method, module

You can print the module's docstring:

"""This module does things"""

if __name__ == '__main__':
print __doc__

Or just have a main function:

def main():
"""What I do when ran as a script"""
pass

if __name__ == '__main__':
print main.__doc__
main()

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_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.

How do I get the docstring from a calling module?

a.py

"""
Foo bar
"""

import b
if __name__ == '__main__':
b.show_your_docs()

b.py

def show_your_docs():
name = caller_name(1)
print(__import__(name).__doc__)

Where caller_name is code from this gist

The weakness of this approach though is it is getting a string representation of the module name and reimporting it, instead of getting a reference to the module (type).

Printing help docstring of all the functions in the string module: Python

In python2:

for i in dir(r):
if not i.startswith('__'):
print getattr(r, i).__doc__

In python3:

for i in dir(r):
if not i.startswith('__'):
print(getattr(r, i).__doc__)

(it's basically the same, changes the print function only). You need to get the method object wth getattr in order to show its __doc__ attribute.



Related Topics



Leave a reply



Submit