[Tutor] Really miss the C preprocessor!!

Steven D'Aprano steve at pearwood.info
Sat Mar 6 14:51:30 CET 2010

On Sat, 6 Mar 2010 07:17:43 pm you wrote:

> I thought about suggesting using decorators for this, since I've done
> something similar (not exactly exponential backoff, but retrying a
> few times on exception). However, as I started writing the example, I
> got stuck at expressing a generic way to pass the exception and
> numretries. I was just wondering is there some way to do this sort of
> thing with decorators ??
> is there a way to decorate a function alongwith additional parameters
> which will be passed to the function ?

Yes, you need a decorator factory -- a function which returns a 

def factory(exception, numretries):
    def decorator(func):
        def inner(*args, **kwargs):
            t = 1
            for i in range(numretries):
                    return func(*args, **kwargs)
                except exception:
                    t *= 2
            msg = "no connection after %d attempts" % numretries
            raise exception(msg)
        return inner
    return decorator

@factory(HTTPError, 8)
def check_some_website(url, x):

I haven't tested the above code, but it should do the trick.

Steven D'Aprano

More information about the Tutor mailing list