可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Is it posible to use docstring for plain variable? For example I have module called t
def f(): """f""" l = lambda x: x """l"""
and I do
>>> import t >>> t.f.__doc__ 'f'
but
>>> t.l.__doc__ >>>
Example is similar to PEP 258's (search for "this is g").
回答1:
No, it is not possible and it wouldn't be useful if you could.
The docstring is always an attribute of an object (module, class or function), not tied to a specific variable.
That means if you could do:
t = 42 t.__doc__ = "something" # this raises AttributeError: '__doc__' is read-only
you would be setting the documentation for the integer 42 not for the variable t
. As soon as you rebind t
you lose the docstring. Immutable objects such as numbers of strings sometimes have a single object shared between different users, so in this example you would probably actually have set the docstring for all occurences of 42
throughout your program.
print(42 .__doc__) # would print "something" if the above worked!
For mutable objects it wouldn't necessarily be harmful but would still be of limited use if you rebind the object.
If you want to document an attribute of a class then use the class's docstring to describe it.
回答2:
Epydoc allows for docstrings on variables:
While the language doesn't directly provides for them, Epydoc supports variable docstrings: if a variable assignment statement is immediately followed by a bare string literal, then that assignment is treated as a docstring for that variable.
Example:
class A: x = 22 """Docstring for class variable A.x""" def __init__(self, a): self.y = a """Docstring for instance variable A.y
回答3:
Some python documentation scripts have notation that can be use in the module/classes docstring to document a var.
E.g. for spinx, you can use :var and :ivar. See this document (about half-way down).
回答4:
Well, even though Python does not treat strings defined immediately after a global definition as a docstring for the variable, sphinx does and it is certainly not a bad practice to include them.
debug = False '''Set to True to turn on debugging mode. This enables opening IPython on exceptions. '''
Here is some code that will scan a module and pull out names of global variable definitions, the value and a docstring that follows.
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
回答5:
No, you can only do this for modules, (lambda and "normal") functions and classes, as far as I know. Other objects, even mutable ones inherit the docstrings of their class and raise AttributeError
if you try to change that:
>>> a = {} >>> a.__doc__ = "hello" Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'dict' object attribute '__doc__' is read-only
(Your second example is valid Python, but the string """l"""
doesn't do anything. It is generated, evaluated and discarded.)
回答6:
To add to to ford's answer about Epydoc, note that PyCharm will also use a string literal as the documentation for a variable in a class:
class Fields_Obj: DefaultValue=None """Get/set the default value of the data field"""
回答7:
Sphinx has a built-in syntax for documenting attributes (i.e. NOT the values as @duncan describes). Examples:
#: This is module attribute x = 42 class MyClass: #: This is a class attribute y = 43
You can read more in the Sphinx docs: http://www.sphinx-doc.org/en/1.4.8/ext/autodoc.html#directive-autoattribute
...or in this other question: How to document a module constant in Python?