Never Hang: Timeouts and Fallbacks

Medium ⏱ 12 min 53% acceptance ★★★★★ 4.6
A request without a timeout can hang forever. Write fetch_with_timeout(url, seconds, fallback) passing timeout=seconds and returning fallback if requests.exceptions.Timeout (or any RequestException) fires — production callers always get an answer.

Examples

Example 1
Input
fetch_with_timeout(slow_url, 2, {})
Output
{} when the server exceeds 2 s
Explanation

The timeout exception became a fallback value.

Constraints

  • Pass timeout explicitly.
  • Catch requests.exceptions.RequestException.

Topics

APIstimeout

Companies

NetflixUberSwiggy

Hints

Hint 1

Timeout subclasses RequestException.

Hint 2

Return response.json() on the happy path.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.