Skipping decorators in unit tests

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Oct 11 01:51:30 EDT 2013


On Fri, 11 Oct 2013 15:36:29 +1100, Cameron Simpson wrote:

> But is it reliable? Will it work on any decorated function?

*Any* decorated function? No, of course not, since decorators can do 
anything they like:

def decorate(func):
    return lambda *args: "Surprise!"

@decorate
def something_useful(x, y):
    return x+y


They don't even have to return a function. Or the function being 
decorated can end up in a different cell:

def factory(x, y):
    def decorator(func):
        def inner(*args):
            _ = (x, y)  # pretend x and y are useful
            return func(*args)
        return inner
    return decorator


@factory(lambda: None, 42)
def func(a):
    return a



py> func.func_closure[0].cell_contents
42
py> func.func_closure[1].cell_contents
<function <lambda> at 0xb7c4609c>
py> func.func_closure[2].cell_contents
<function func at 0xb7c4617c>


So consider this a *cooperative* undecorator. It can only undecorate 
things that are decorated the way you expect them to be decorated. 


-- 
Steven



More information about the Python-list mailing list