Statement decorators
Question: We have some code that looks like this:

    
    
    from third_party_library import foo
    
    for n in range(3):
        try:
            foo(args)
            break
        except:
            print "Retry %i / 3" % n
    

I would like to use a decorator, allowing our code to be more consise, looking
like this:

    
    
    from third_party_library import foo
    
    @retry(3)
    foo(args)
    

This gives a syntax error. Am I missing something, or does python just not
allow decorators on statements?


Answer: Decorators can only be applied to function and class _definitions_ such as:

    
    
    @decorator
    def func():
        ...
    
    @decorator
    class MyClass(object):
        ...
    

You cannot use them anywhere else in the language.

* * *

To do what you want, you could make a normal `retry` function and pass `foo`
and `args` as arguments. The implementation would look something like this:

    
    
    def retry(times, func, *args, **kwargs):
        for n in xrange(times):
            try:
                func(*args, **kwargs)
                break
            except Exception:  # Try to catch something more specific
                print "Retry %i / %i" % (n, times)
    

