Docstring for variable

前端 未结 9 1911
予麋鹿
予麋鹿 2021-01-31 13:35

Is it posible to use docstring for plain variable? For example I have module called t

def f():
    \"\"\"f\"\"\"

l = lambda x: x
\"\"\"l\"\"\"
         


        
9条回答
  •  一向
    一向 (楼主)
    2021-01-31 14:11

    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.

提交回复
热议问题