Repeat Python function call on exception?

后端 未结 7 664
抹茶落季
抹茶落季 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:49

    To do precisely what you want, you could do something like the following:

    import functools
    def try_x_times(x, exceptions_to_catch, exception_to_raise, fn):
        @functools.wraps(fn) #keeps name and docstring of old function
        def new_fn(*args, **kwargs):
            for i in xrange(x):
                try:
                    return fn(*args, **kwargs)
                except exceptions_to_catch:
                     pass
            raise exception_to_raise
        return new_fn
    

    Then you just wrap the old function in this new function:

    #instead of
    #risky_method(1,2,'x')
    not_so_risky_method = try_x_times(3, (MyError,), myError2, risky_method)
    not_so_risky_method(1,2,'x')
    
    #or just
    try_x_times(3, (MyError,), myError2, risky_method)(1,2,'x')
    

提交回复
热议问题