Decorators not worth the effort

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Sep 14 08:01:57 EDT 2012


On Fri, 14 Sep 2012 11:28:22 +0200, Jean-Michel Pichavant wrote:

> PS : Here's the decorator, just to give you an idea about how it looks.
> Small piece of code, but took me more than 2 hours to write it. I
> removed some sensible parts so I don't expect it to run.

[snip timeout class]

Holy over-engineering Batman!!!

No wonder you don't think much of decorators, if this example of overkill 
is what you consider typical of them. It does much, much more than the 
simple code you were replacing:

def boot(self, timeout=15):
    if FPGA:
        self.sendCmd("bootMe", timeout=timeout*3)
    else:
        self.sendCmd("bootMe", timeout=timeout)

# becomes:

@timeout(15)
def boot(self, timeout=None):
    self.sendCmd("bootMe", timeout)


Most of my decorator functions are under a dozen lines. And that's the 
complicated ones!

Here's my solution to the example you gave:




# Untested!
def timeout(t=15):
    # Decorator factory. Return a decorator to actually do the work.
    if FPGA:
        t *= 3
    def decorator(func):
        @functools.wraps(func)
        def inner(self, timeout):
            self.sendCmd("bootMe", timeout=t)
        return inner
    return decorator
    

I reckon that will pretty much do what your example showed. Of course, 
once you start adding more and more functionality above the simple code 
shown above (arbitrary platforms, argument checking of the decorated 
function, logging, etc.) you're going to get a much more complex 
decorator. On the other hand, YAGNI.

http://en.wikipedia.org/wiki/You_ain%27t_gonna_need_it

 
-- 
Steven



More information about the Python-list mailing list