Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python __doc__ documentation on instances

I'd like to provide documentation (within my program) on certain dynamically created objects, but still fall back to using their class documentation. Setting __doc__ seems a suitable way to do so. However, I can't find many details in the Python help in this regard, are there any technical problems with providing documentation on an instance? For example:

class MyClass:
    """
    A description of the class goes here.
    """

a = MyClass()
a.__doc__ = "A description of the object"

print( MyClass.__doc__ )
print( a.__doc__ )
like image 817
c z Avatar asked May 31 '26 20:05

c z


1 Answers

__doc__ is documented as a writable attribute for functions, but not for instances of user defined classes. pydoc.help(a), for example, will only consider the __doc__ defined on the type in Python versions < 3.9.

Other protocols (including future use-cases) may reasonably bypass the special attributes defined in the instance dict, too. See Special method lookup section of the datamodel documentation, specifically:

For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary.

So, depending on the consumer of the attribute, what you intend to do may not be reliable. Avoid.

A safe and simple alternative is just to use a different attribute name of your own choosing for your own use-case, preferably not using the __dunder__ syntax convention which usually indicates a special name reserved for some specific use by the implementation and/or the stdlib.

like image 187
wim Avatar answered Jun 02 '26 09:06

wim