abc
abc

Reputation: 3551

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

None of these commands will retrieve the docstring of a function and assign it to a variable. How can it be achieved?

I attempted various things. One of which is the help function, but it seems to activate an entire program as opposed to returning a string. I have tried various commands but none of them work to retrieve the docstring.

import PIL

PILCommands=dir('PIL')

ListA=[]
ListB=[]
ListC=[]
ListD=[]
ListE=[]
LisfF=[]
ListG=[]
ListH=[]

for x in PILCommands:
    print(x)
    try:
        ListA.append(x.__doc__)
    except:
        pass
    try:
        ListB.append(x.__doc__())
    except:
       pass
    try:
        ListC.append(str(x))
    except:
        pass
   try:
       ListD.append(help(x))
   except:
       pass
   try:
       ListE.append(eval("x.__doc__"))
   except:
       pass
   try:
       ListF.append(eval("inspect.getdoc(x)"))
   except:
        pass
   try:
        ListG.append(eval("dir(x)"))
   except:
        pass
   try:
        ListH.append(eval("PIL.x.__doc__"))
   except:
        pass

print
print("Command1: x.__doc__")
print(ListA)
print
print("Command1: x.__doc__()")
print(ListB)
print
print("Command1: str(x)")
print(ListC)
print
print("help(x)")
print(ListD)
print
print('Command1: eval("eval("x.__doc__")')
print(ListE)
print
print('Command1: eval("inspect.getdoc(x)")')
print(ListE)
print
print('Command1: eval("dir(x)")')
print(ListG)
print
print('Command1: eval("PIL.x.__doc__")')
print(ListG)

Answer :

python << EOF
import inspect
import PIL 
doc = inspect.getdoc(PIL)
print doc
print type(doc)
EOF

So it has no documentation .

Upvotes: 4

Views: 5811

Answers (1)

MSeifert
MSeifert

Reputation: 152647

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

Upvotes: 6

Related Questions