On Jan 16, 6:55 pm, Steven D'Aprano <st...@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
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to