是否可以将docstring用于普通变量?例如,我有一个名为的模块t
def f():
"""f"""
l = lambda x: x
"""l"""
Run Code Online (Sandbox Code Playgroud)
而我呢
>>> import t
>>> t.f.__doc__
'f'
Run Code Online (Sandbox Code Playgroud)
但
>>> t.l.__doc__
>>>
Run Code Online (Sandbox Code Playgroud)
示例类似于PEP 258(搜索"this is g").
Dun*_*can 57
docstring始终是对象(模块,类或函数)的属性,不依赖于特定变量.
这意味着如果你能做到:
t = 42
t.__doc__ = "something" # this raises AttributeError: '__doc__' is read-only
Run Code Online (Sandbox Code Playgroud)
你将设置整数42的文档而不是变量t.重新绑定后,t您将丢失文档字符串.不可变对象(如字符串数)有时会在不同用户之间共享一个对象,因此在本示例中,您可能实际上已为42整个程序中的所有出现设置了文档字符串.
print(42 .__doc__) # would print "something" if the above worked!
Run Code Online (Sandbox Code Playgroud)
对于可变对象,它不一定是有害的,但如果你重新绑定对象,它仍然是有限的用途.
如果要记录类的属性,请使用类的docstring来描述它.
for*_*ord 28
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
Run Code Online (Sandbox Code Playgroud)
ben*_*ing 10
Sphinx 具有用于记录属性的内置语法(即不是@duncan 描述的值)。例子:
#: This is module attribute
x = 42
class MyClass:
#: This is a class attribute
y = 43
Run Code Online (Sandbox Code Playgroud)
您可以在 Sphinx 文档中阅读更多内容:https : //www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#directive-autoattribute
...或在另一个问题中:如何在 Python 中记录模块常量?
好吧,即使Python不将全局定义后立即定义的字符串视为变量的文档字符串,sphinx也会这样做,包含它们肯定不是一个坏习惯.
debug = False
'''Set to True to turn on debugging mode. This enables opening IPython on
exceptions.
'''
Run Code Online (Sandbox Code Playgroud)
下面是一些代码,它们将扫描模块并提取全局变量定义的名称,值和后面的文档字符串.
def GetVarDocs(fname):
'''Read the module referenced in fname (often <module>.__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
Run Code Online (Sandbox Code Playgroud)
要添加到 ford 关于 Epydoc 的答案,请注意 PyCharm 还将使用字符串文字作为类中变量的文档:
class Fields_Obj:
DefaultValue=None
"""Get/set the default value of the data field"""
Run Code Online (Sandbox Code Playgroud)
不,据我所知,您只能对模块、(lambda 和“普通”)函数和类执行此操作。其他对象,即使是可变对象,也会继承其类的文档字符串,并AttributeError在您尝试更改它时引发:
>>> a = {}
>>> a.__doc__ = "hello"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object attribute '__doc__' is read-only
Run Code Online (Sandbox Code Playgroud)
(您的第二个示例是有效的 Python,但该字符串"""l"""不执行任何操作。它被生成、评估和丢弃。)