Write a python function to call a function repeatedly until an exception is raised.


Topic: Write a python function to call a function repeatedly until an exception is raised.

Solution

def iter_except(func, exception, first=None):
    """Converts a call-until-exception interface to an iterator interface.
    Like builtins.iter(func, sentinel) but uses an exception instead
    of a sentinel to end the loop.
    Examples:
        iter_except(s.pop, KeyError)                             # non-blocking set iterator
    """
    try:
        if first is not None:
            yield first()            # For database APIs needing an initial cast to db.first()
        while True:
            yield func()
    except exception:
        pass



List all Python Programs