ali_m ali_m - 8 months ago 26
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

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()

# Class docstring

# Method docstring

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

# int(x=0) -> int or long
# int(x, base=10) -> int or long
# ...

The same thing applies to
getattr(tc, "prop").__doc__
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
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
able to access the docstring for


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:


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__:


Or use type to fetch the class: