文档string的variables

使用docstring作为普通variables是否可行? 例如我有一个叫做t模块

 def f(): """f""" l = lambda x: x """l""" 

而我呢

 >>> import t >>> tf__doc__ 'f' 

 >>> tl__doc__ >>> 

例子类似于PEP 258的(search“这是g”)。

不,如果可以的话,它不会有用。

docstring始终是一个对象(模块,类或函数)的属性,而不是绑定到特定的variables。

这意味着如果你做到这一点:

 t = 42 t.__doc__ = "something" 

您将设置整数42的文档而不是variablest 。 只要您重新绑定,就会丢失文档string。 像string数量这样的不可变对象有时会在不同的用户之间共享一个对象,所以在这个例子中,您可能实际上已经在整个程序中设置了所有出现次数为42的文档string。

 print(42 .__doc__) # would print "something" if the above worked! 

对于可变对象来说,它不一定是有害的,但如果重新绑定对象,使用仍然是有限的。

如果你想logging一个类的属性,然后使用类的文档string来描述它。

Epydoc允许对variables进行文档化 :

虽然语言没有直接为它们提供,但是Epydoc支持variables文档string:如果一个variables赋值语句紧跟着一个空string文字,那么该赋值就被当作该variables的文档string。

例:

 class A: x = 22 """Docstring for class variable Ax""" def __init__(self, a): self.y = a """Docstring for instance variable Ay 

一些python文档脚本有可以在模块/类docstring中使用的记法来logging一个var。

例如,对于spinx,您可以使用:var和:ivar。 看到这个文件 (大约一半)。

那么,即使Python不把在全局定义之后立即定义的string视为variables的文档string,sphinx也是如此,包含它们当然不是一个坏习惯。

 debug = False '''Set to True to turn on debugging mode. This enables opening IPython on exceptions. ''' 

下面是一些代码,它们将扫描一个模块,并提取全局variables定义的名称,值和随后的文档string。

 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 

不,你只能对模块(lambda和“normal”)函数和类做这个,据我所知。 其他对象,即使是可变的,也会inheritance它们的类的文档string,并且如果您尝试更改AttributeError则会引发AttributeError

 >>> a = {} >>> a.__doc__ = "hello" Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'dict' object attribute '__doc__' is read-only 

(你的第二个例子是有效的Python,但是string"""l"""没有任何作用,它被生成,评估和丢弃。

要添加到ford关于Epydoc的答案中,请注意,PyCharm也将使用string作为类中variables的文档:

 class Fields_Obj: DefaultValue=None """Get/set the default value of the data field""" 

狮身人面像有一个内置的语法来logging属性(即不是@duncan描述的值)。 例子:

 #: This is module attribute x = 42 class MyClass: #: This is a class attribute y = 43 

您可以阅读更多的狮身人面像文件: http : //www.sphinx-doc.org/en/1.4.8/ext/autodoc.html#directive-autoattribute

…或者在这个其他问题: 如何在Python中logging模块常量?