Desi Programmer @ Work

Attempt Retries decorator in Python

In certain situations particularly when dealing with networks and distributed systems you'd want your program to retry certain a particular operation certain number of times in case it fails before giving up. For instance your program is trying to connect to a mail server which is due to network connectivity temporarily giving socket error.

The simple way is to put a loop, try certain number of times and if the result still fails give up. I found this pattern normal so I wrote a decorator in Python which can be generically used.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def attempt_retries(func, retries=3, delay=3, IgnoreException=Exception):    
    """    
    Decorator for ignoring certain exception for certain number of times 
    and retrying with certain delay   
     e.g.   func = @retry(connect_imap, 10, 5, SocketError) # Tries ten times    
     e.g.2. retry(connect_imap)(username, password)    
     """    
    def dec(*args, **kwargs):        
        for i in range(retries-1):            
            try:                
                return func(*args, **kwargs)            
            except IgnoreException:                
                sleep(delay)        
        return func(*args, **kwargs)    
    return dec

Usage:

attempt_retries( server_connect, 10, 20, SocketError ) ( host, user, pass)

or

r_server_connect = attempt_retries( server_connect, 10, 50, SocketError )
r_server_connect( host, user, pass)