alexanderkuk alexanderkuk - 1 month ago 22
Python Question

Docstring for variable

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").

Answer

No, 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"

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.