Statement decorators
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)
Python does not allow decorators on statements; they are only allowed on class & function definitions. You can see this near the top of the grammar specification.
Decorators were introduced in Python 2.4. Initially, they were only supported for function and method declarations (PEP 318).
Python 3 extended them to class declarations (PEP 3129).
Decorators are not supported on any other language constructs.