How do I programmatically set the docstring? How do I programmatically set the docstring? python python

How do I programmatically set the docstring?


An instancemethod gets its docstring from its __func__. Change the docstring of __func__ instead. (The __doc__ attribute of functions are writeable.)

>>> class Foo(object):...     def bar(self):...         pass...>>> Foo.bar.__func__.__doc__ = "A super docstring">>> help(Foo.bar)Help on method bar in module __main__:bar(self) unbound __main__.Foo method    A super docstring>>> foo = Foo()>>> help(foo.bar)Help on method bar in module __main__:bar(self) method of __main__.Foo instance    A super docstring

From the 2.7 docs:

User-defined methods

A user-defined method object combines a class, a class instance (or None) and any callableobject (normally a user-defined function).

Special read-only attributes: im_self is the class instance object, im_func is the functionobject; im_class is the class of im_self for bound methods or the class that asked for themethod for unbound methods; __doc__ is the method’s documentation (same asim_func.__doc__); __name__ is the method name (same as im_func.__name__);__module__ is the name of the module the method was defined in, or None if unavailable.

Changed in version 2.2: im_self used to refer to the class that defined the method.

Changed in version 2.6: For 3.0 forward-compatibility, im_func is also available as__func__, and im_self as __self__.


I would pass the docstring into the factory function and use type to manually construct the class.

def make_testcase(filename, myfunc, docstring):    def test_something(self):        data = loadmat(filename)        result = myfunc(data)        self.assertTrue(result > 0)    clsdict = {'test_something': test_something,               '__doc__': docstring}    return type('ATest', (unittest.TestCase,), clsdict)MyTest = makeTestCase('some_filename', my_func, 'This is a docstring')


This is an addition to the fact that the __doc__ attribute of classes of type type cannot be changed. The interesting point is that this is only true as long as the class is created using type. As soon as you use a metaclass you can actually just change __doc__.

The example uses the abc (AbstractBaseClass) module. It works using a special ABCMeta metaclass

import abcclass MyNewClass(object):    __metaclass__ = abc.ABCMetaMyClass.__doc__ = "Changing the docstring works !"help(MyNewClass)

will result in

"""Help on class MyNewClass in module __main__:class MyNewClass(__builtin__.object) |  Changing the docstring works !"""