Repeat Python function call on exception?

后端 未结 7 680
抹茶落季
抹茶落季 2021-02-08 07:48

Hey everybody I\'m working on a data scraping project and I\'m looking for a clean way to repeat a function call if an exception is raised.

Pseudo-code:

         


        
7条回答
  •  生来不讨喜
    2021-02-08 07:57

    To raise Exception as usual after n retries

    from functools import wraps
    
    def retry(times):
        """
        Decorator to retry any functions 'times' times.
        """
        def retry_decorator(func):
            @wraps(func)
            def retried_function(*args, **kwargs):
                for i in range(times - 1):
                    try:
                        func(*args, **kwargs)
                        return
                    except Exception:  
                        pass
                func(*args, **kwargs)
    
            return retried_function
    
        return retry_decorator
    
    
    # test
    
    attempts = 3
    
    @retry(4)
    def function_that_raises_error():
        global attempts
        if 0 < attempts:
            print("fail")
            attempts -= 1
            raise Exception
    
        print("pass")
    
    function_that_raises_error()
    

提交回复
热议问题