如何将函数的docstring转换为变量?

时间:2017-05-27 10:20:14

标签: python python-2.7 function module docstring

这些命令都不会检索函数的文档字符串并将其分配给变量。如何实现?

我尝试了各种各样的事情。其中一个是help函数,但它似乎激活整个程序而不是返回一个字符串。我尝试了各种命令,但没有一个能够检索文档字符串。

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)

答案:

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

所以它没有文档。

1 个答案:

答案 0 :(得分:6)

您可以使用inspect.getdoc来处理对象的docstring并将其作为字符串返回:

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

通常,文档存储在__doc__属性中:

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

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

但是__doc__不会被清除:可能包含前导和尾随空的换行符,缩进可能不一致。所以inspect.getdoc应该是优先选项。

以下内容基于您的原始问题:

要获取您可以使用的PIL函数的文档:

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

要获取模块中所有功能的文档,您需要使用getattr

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

获取所有文档字符串的列表:

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

或者如果你需要相应的名字,那么dict会更好:

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

然而,并非所有都有文档。例如,PIL.Image模块没有docstring:

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

并且在尝试获取实例的docstring时,您可能会得到令人惊讶的结果:

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

那是因为PIL.__version__是一个字符串实例,只是显示其类的文档字符串: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'.