[英]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. 其中之一是
help
功能,但它似乎是在激活整个程序,而不是返回字符串。 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 . 因此它没有文档。
You can use inspect.getdoc
, that will process the docstring of the object and return it as string: 您可以使用
inspect.getdoc
,它将处理对象的文档字符串并将其作为字符串返回:
>>> 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__
属性中:
>>> 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. 但是
__doc__
不会被清除:它可能包含前导和尾随的空换行符,并且缩进可能不一致。 So inspect.getdoc
should be the preffered option. 因此,
inspect.getdoc
应该是首选。
To get the documentation of PIL
functions you could use: 要获取
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
To get the documentations of all functions in a module you need to use getattr
: 要获取模块中所有功能的文档,您需要使用
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
模块没有文档字符串:
>>> 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
: 这是因为
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'.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.