3

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 .

abc
  • 3,223
  • 1
  • 15
  • 15
  • 3
    `.__doc__` would work just fine, but `x` is a string, the *name* of the thing, not the thing itself. Try `PIL[x].__doc__`. – jonrsharpe May 27 '17 at 10:23
  • 1
    @jonrsharpe Modules are not subscriptable, but `getattr` should work fine. – MSeifert May 27 '17 at 10:52
  • @MSeifert good point, thanks – jonrsharpe May 27 '17 at 10:53
  • @user2564386 I removed the "fails to import PIL" part of the code because it contained an indentation error and it's not really relevant for the question (see [mcve]). If I accidentally introduced mistakes - feel free to edit the question again. :) – MSeifert May 27 '17 at 11:44
  • 1
    [Don’t use `except: pass`](https://stackoverflow.com/q/21553327/216074). And most of those lines won’t ever raise exceptions, so this just adds complexity where no complexity should be. – poke May 27 '17 at 11:46
  • You included *parts* (the `getattr` part is missing) of my answer in the question as "not working". Could you explain why it's not working? Either as comment on my answer or in your question. I'll gladly improve or expand the answer if I know what's wrong with it :) – MSeifert May 27 '17 at 11:47
  • After the declaration of a function is its explanation and instruction for use . That is what i am after . How do i get it ? – abc May 27 '17 at 15:14

1 Answers1

6

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'.
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
MSeifert
  • 145,886
  • 38
  • 333
  • 352