Inheriting methods but over-riding docstrings

Michele Simionato michele.simionato at gmail.com
Tue Jan 19 06:44:09 EST 2010


On Jan 16, 6:55 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> I have a series of subclasses that inherit methods from a base class, but
> I'd like them to have their own individual docstrings.

The following is not tested more than you see and will not work for
builtin methods, but it should work in the common cases:

from types import FunctionType, CodeType

def newfunc(func, docstring):
    c = func.func_code
    nc = CodeType(c.co_argcount, c.co_nlocals, c.co_stacksize,
                  c.co_flags, c.co_code, c.co_consts, c.co_names,
                  c.co_varnames, c.co_filename, func.__name__,
                  c.co_firstlineno, c.co_lnotab, c.co_freevars,
c.co_cellvars)
    nf = FunctionType(nc, func.func_globals, func.__name__)
    nf.__doc__ = docstring
    return nf

def setdocstring(method, docstring):
    cls = method.im_class
    basefunc = getattr(super(cls, cls), method.__name__).im_func
    setattr(cls, method.__name__, newfunc(basefunc, docstring))


# example of use

class B(object):
    def m(self):
        "base"
        return 'ok'

class C(B):
    pass

setdocstring(C.m, 'C.m docstring')

print B.m.__doc__ # the base docstring
print C.m.__doc__ # the new docstring



More information about the Python-list mailing list