import logging


def retry_if_raises(times: int):
  """Returns a decorator to retry a function when exception is raised.

  Args:
    times: number of times to retry

  Returns:
    A decorator.
  """

  def dec(func):
    """Decorates a function to retry when exception is raised.

    Raises internal error after maximum number of retries.

    Args:
      func: Function to be wrapped.

    Returns:
      The wrapped function.
    """

    def wrapper(*args, **kwargs):
      for trial in range(times + 1):
        try:
          return func(*args, **kwargs)
        except RuntimeError as e:
          logging.exception('Failed for trial: %s', trial)
          if trial == times:
            raise e
    return wrapper

  return dec