Decorators not worth the effort

Steve Howell showell30 at yahoo.com
Fri Sep 14 21:13:27 EDT 2012


On Sep 14, 6:05 am, Tim Chase <python.l... at tim.thechases.com> wrote:
> On 09/14/12 07:01, Steven D'Aprano wrote:> [snip timeout class]
>
> > Holy over-engineering Batman!!!
>
> > No wonder you don't think much of decorators,
>
> [snip]
>
> > Most of my decorator functions are under a dozen lines. And that's the
> > complicated ones!
>
> As are mine, and a sizable chunk of those under-a-dozen-lines are
> somewhat boilerplate like using @functools.wraps inside, actual def
> of the function, and returning that function. :-)
>
> -tkc

For parameterized decorators, I've usually seen the pattern below.
Basically, you have 6 lines of boilerplate, and 2 lines of signal.
The amount of boilerplate is fairly daunting, but I like the
explicitness, and the nature of decorators is that they tend to get a
lot of reuse, so you can amortize the pain of all the boilerplate.

    import functools

    def hello_world(name): # non-boilerplate signature
        def decorator(f):
            @functools.wraps(f)
            def wrapped(*args, **kw):
                print 'hello', name # non-boilerplate value-add
                f(*args, **kw)
            return wrapped
        return decorator

    @hello_world('earth')
    def add(x, y):
        print x + y

    add(2, 2)



More information about the Python-list mailing list