In Python, suppose you want to implement a class which has a dynamically generated docstring. The easiest way to do this would be to use the @property decorator for the __doc__ attribute. (You also need your class to be a “new-style” class, i.e., inherit from object). For example:
class A(object):
"""Docstring for class."""
def __init__(self, x):
self.x = x
@property
def __doc__(self):
return "My value of x is %s." % self.x
This gives the desired result:
>>> a = A(10) >>> print(a.__doc__) My value of x is 10.
But hides the docstring for the class A:
>>> A.__doc__ <property at 0x2083db8>
Read on to see how we can fix this. Continue reading A data descriptor for __doc__