Decorator cllass hides docstring from doctest?

Peter Otten __peter__ at
Thu Sep 21 15:54:13 CEST 2006

Berthold Höllmann wrote:

> Saving the following code to a file and running the code through
> python does not give the expected error. disableling the "@decor" line
> leads to the expected error message. Is this a bug or an overseen
> feature?

Neither, I'd say. Just an unfortunate interaction between doctest and
function decoration. For the most common case where one function is wrapped
by another, Python 2.5 has grown a "meta-decorator"

>>> import functools
>>> def deco(f):
...     @functools.wraps(f)
...     def g():
...             f()
...     return g
>>> @deco
... def f():
...     "yadda yadda"
>>> f.__doc__
'yadda yadda'

but with callable objects you're on your own, I think. 
I came up with:

def register_doctest(name, doc):
    global __test__
    if doc:
        except NameError:
            __test__ = {name: doc}
            if name in __test__:
                raise ValueError("name clash")
            __test__[name] = doc

class decor(object):
    def __init__(self, f):
        self.f = f
        register_doctest(f.__name__, f.__doc__)
    def __call__(self, *args, **kw):
        return self.f(*args, **kw)

def f(a, b):
    >>> f(1,2)
    >>> f(2,2)
    return a == b

import doctest


More information about the Python-list mailing list