Decorator cllass hides docstring from doctest?

Peter Otten __peter__ at web.de
Thu Sep 21 09:54:13 EDT 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:
        try:
            __test__
        except NameError:
            __test__ = {name: doc}
        else:
            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)

@decor
def f(a, b):
    """
    >>> f(1,2)
    False
    >>> f(2,2)
    False
    """
    return a == b

import doctest
doctest.testmod()

Peter



More information about the Python-list mailing list