Inheriting methods but over-riding docstrings
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Wed Jan 20 18:09:17 EST 2010
En Tue, 19 Jan 2010 08:44:09 -0300, Michele Simionato
<michele.simionato at gmail.com> escribió:
> 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.
>
> 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))
>
> class B(object):
> def m(self):
> "base"
> return 'ok'
>
> class C(B):
> pass
>
> setdocstring(C.m, 'C.m docstring')
This is basically the same technique as in
<http://permalink.gmane.org/gmane.comp.python.general/651001> but there is
a difference: you clone the function object *and* the code object it is
based on. As I understand it, code objects are immutable and there is no
need to clone them, but I may be wrong. Why did you feel the need to clone
the code object too?
--
Gabriel Genellina
More information about the Python-list
mailing list