ali_m ali_m - 5 months ago 12
Python Question

How can I retrieve the docstring for a property of a Python class instance?

Suppose I have a class like this:

class TestCase(object):
"""Class docstring"""

def meth(self):
"""Method docstring"""
return 1

@property
def prop(self):
"""Property docstring"""
return 2


It's easy enough for me to get the docstrings for the class itself, or for a regular method:

tc = TestCase()

print(tc.__doc__)
# Class docstring

print(tc.meth.__doc__)
# Method docstring


However, this approach doesn't work for properties - instead I get the
__doc__
attribute of whatever object is returned by the property getter method (in this case,
int
):

print(tc.prop.__doc__)
# int(x=0) -> int or long
# int(x, base=10) -> int or long
# ...


The same thing applies to
getattr(tc, "prop").__doc__
and
getattr(tc.prop, "__doc__")
.

I know that Python's introspection mechanisms are capable of accessing the docstring I'm looking for. For example, when I call
help(tc)
I get:

class TestCase(__builtin__.object)
| Class docstring
|
| Methods defined here:
|
| meth(self)
| Method docstring
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| prop
| Property docstring


How is
help
able to access the docstring for
tc.prop
?

Answer

You are trying to access the __doc__ from the instance which will try to first , evaluate the property, for which the returned value may have no attribute __doc__, or use the __doc__ of the returned type.

Instead, you should access the __doc__ for the property from the class itself:

TestCase.prop.__doc__

So to extend this to your class instance, you would use __class__ to get the class of the instance and then the property, and finally the __doc__:

tc.__class__.prop.__doc__

Or use type to fetch the class:

type(tc).prop.__doc__