[Tutor] Really miss the C preprocessor!!

Steven D'Aprano steve at pearwood.info
Sat Mar 6 07:01:38 CET 2010


On Sat, 6 Mar 2010 04:13:49 pm Gil Cosson wrote:
> I have some code to perform an exponential backoff. I am interacting
> with a few different web services. Checking for a specific Exception
> and then re-invoking the failed call after waiting a bit. I don't
> want to  code the backoff in ten different places. Really miss the C
> pre-processor.
>
> I am tempted to try something like the following, but I understand
> that eval should be a last resort.
>
> Any pythonic best practice for this situation?:

Functions are first-class objects that can be passed around as data. Use 
them.

def check_some_website(url, x):
    # whatever


def exponential_backoff(function, args, exception, numretries):
    # Backoff 1 second, 2 seconds, 4 seconds, 8, 16, ...
    t = 1
    for i in xrange(numretries):
        try:
            return function(*args)
        except exception:
            time.sleep(t)
            t *= 2
    raise exception("no connection after %d attempts" % numretries)


result = exponential_backoff(check_some_website, 
    ("http://example.com", 42), HTTPError, 8)


Any time you think you need eval, you almost certainly don't.



-- 
Steven D'Aprano


More information about the Tutor mailing list