Challenge: Retry Decorator
You have now seen how decorators can enhance functions with additional behavior, such as logging, timing, or formatting. Sometimes, you may want to make your functions more robust by automatically retrying them when they fail due to exceptions. This is especially useful when dealing with unreliable operations, like network requests or file I/O, where a temporary glitch might cause a function to fail even though retrying would succeed. In this challenge, you will implement a decorator that retries a function up to three times if it raises an exception, and only gives up if all attempts fail.
Swipe to start coding
Write a decorator that retries a function up to three times if it raises an exception, then re-raises the exception if all attempts fail.
The decorator must:
- Attempt to call the decorated function.
- If the function raises an exception, catch it and retry up to two more times.
- If the function still raises an exception after three total attempts, re-raise the last exception.
- If the function succeeds on any attempt, return its result.
Løsning
Takk for tilbakemeldingene dine!
single
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Awesome!
Completion rate improved to 5.88
Challenge: Retry Decorator
Sveip for å vise menyen
You have now seen how decorators can enhance functions with additional behavior, such as logging, timing, or formatting. Sometimes, you may want to make your functions more robust by automatically retrying them when they fail due to exceptions. This is especially useful when dealing with unreliable operations, like network requests or file I/O, where a temporary glitch might cause a function to fail even though retrying would succeed. In this challenge, you will implement a decorator that retries a function up to three times if it raises an exception, and only gives up if all attempts fail.
Swipe to start coding
Write a decorator that retries a function up to three times if it raises an exception, then re-raises the exception if all attempts fail.
The decorator must:
- Attempt to call the decorated function.
- If the function raises an exception, catch it and retry up to two more times.
- If the function still raises an exception after three total attempts, re-raise the last exception.
- If the function succeeds on any attempt, return its result.
Løsning
Takk for tilbakemeldingene dine!
single