Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Iterators, generators & decoratorsMiddleVery commonPractical

Write a retry decorator that retries only a specified exception type and preserves the wrapped function's metadata.

Answer

Use a decorator factory so the exception type and attempt count are configuration, then wrap the function with `functools.wraps`. Catch only the configured exception instead of `Exception`, retry a bounded number of times, and re-raise the final failure. This avoids hiding unrelated programming errors and keeps the decorated function inspectable.

Strong answer includes

  • uses a decorator factory and functools.wraps
  • catches only the configured exception
  • uses bounded attempts and re-raises the final failure

Practical example

Bounded retry decorator
Python
editable · browser sandbox
Result
Run the code to see the result.

The decorator retries only TimeoutError, stops after three total attempts, and `@wraps` preserves the original function's name and metadata.

Expected result: ok, then 3.

#decorators#retry#functions

Sources

functools — Higher-order functions and operations on callable objectsPython Software Foundation · lru_cache, partial, wraps, reduce and singledispatch behaviorErrors and ExceptionsPython Software Foundation · try/except/else/finally control flow and exception chaining