python-变量的文档字符串
是否可以将docstring用于纯变量? 例如,我有一个名为t的模块
def f():
"""f"""
l = lambda x: x
"""l"""
而我
>>> import t
>>> t.f.__doc__
'f'
但
>>> t.l.__doc__
>>>
示例类似于PEP 258(搜索“ this是g”)。
alexanderkuk asked 2019-12-26T11:26:48Z
7个解决方案
57 votes
不,这是不可能的,如果可以的话,它也不会有用。
docstring始终是对象(模块,类或函数)的属性,而不受特定变量的约束。
这意味着您可以:
t = 42
t.__doc__ = "something" # this raises AttributeError: '__doc__' is read-only
您将为整数42而不是变量t设置文档。重新绑定t后,您将丢失文档字符串。 不可变的对象(例如字符串数)有时在不同的用户之间共享一个对象,因此在此示例中,您可能实际上已为整个程序中发生的42设置了文档字符串。
print(42 .__doc__) # would print "something" if the above worked!
对于可变对象,它不一定是有害的,但是如果您重新绑定该对象,则其用途仍然有限。
如果要记录类的属性,请使用类的文档字符串来描述它。
Duncan answered 2019-12-26T11:27:30Z
26 votes
Epydoc允许在变量上使用文档字符串:
虽然该语言并未直接为其提供支持,但Epydoc支持 变量文档字符串:如果立即有变量赋值语句 然后是裸字符串文字,然后将该赋值视为 该变量的文档字符串。
例:
class A:
x = 22
"""Docstring for class variable A.x"""
def __init__(self, a):
self.y = a
"""Docstring for instance variable A.y
ford answered 2019-12-26T11:27:59Z
7 votes
一些python文档脚本具有可在模块/类docstring中用于记录var的符号。
例如。 对于Spinx,可以使用:var和:ivar。 请参阅此文档(大约一半)。
Gary van der Merwe answered 2019-12-26T11:28:24Z
6 votes
好吧,即使Python不会将在全局定义之后立即定义的字符串视为变量的文档字符串,但sphinx会这样做,并且将它们包括在内当然不是一个坏习惯。
debug = False
'''Set to True to turn on debugging mode. This enables opening IPython on
exceptions.
'''
这是一些代码,这些代码将扫描模块并提取全局变量定义的名称,值和随后的文档字符串。
def GetVarDocs(fname):
'''Read the module referenced in fname (often .__file__) and return a
dict with global variables, their value and the "docstring" that follows
the definition of the variable
'''
import ast,os
fname = os.path.splitext(fname)[0]+'.py' # convert .pyc to .py
with open(fname, 'r') as f:
fstr = f.read()
d = {}
key = None
for node in ast.walk(ast.parse(fstr)):
if isinstance(node,ast.Assign):
key = node.targets[0].id
d[key] = [node.value.id,'']
continue
elif isinstance(node,ast.Expr) and key:
d[key][1] = node.value.s.strip()
key = None
return d
bht answered 2019-12-26T11:28:49Z
4 votes
不,据我所知,您只能对模块(lambda和“ normal”)函数和类执行此操作。 其他对象,甚至是可变对象,都将继承其类的文档字符串,并且如果尝试更改该对象,则会引发"""l""":
>>> a = {}
>>> a.__doc__ = "hello"
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'dict' object attribute '__doc__' is read-only
(您的第二个示例是有效的Python,但是字符串"""l"""没有任何作用。它是生成,评估和丢弃的。)
Tim Pietzcker answered 2019-12-26T11:29:14Z
4 votes
Sphinx具有用于记录属性的内置语法(即,不是@duncan描述的值)。 例子:
#: This is module attribute
x = 42
class MyClass:
#: This is a class attribute
y = 43
您可以在Sphinx文档中阅读更多信息:[http://www.sphinx-doc.org/en/1.4.8/ext/autodoc.html#directive-autoattribute]
...或另一个问题:如何在Python中记录模块常量?
benjaoming answered 2019-12-26T11:29:43Z
3 votes
为了增加福特关于Epydoc的答案,请注意,PyCharm还将使用字符串文字作为类中变量的文档:
class Fields_Obj:
DefaultValue=None
"""Get/set the default value of the data field"""
David Cater answered 2019-12-26T11:30:04Z