Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda The Problem with Blocking Code | The Asyncio Foundation
Python Asyncio in Depth

The Problem with Blocking Code

Deslize para mostrar o menu

When a Python script makes an HTTP request, reads a file, or queries a database, it waits. Nothing else runs. The entire program is frozen until that operation finishes.

This is called blocking – the current operation blocks all other work.

1234567891011121314151617181920212223242526272829
import time import requests # Fetching weather data for three cities def fetch_weather(city, latitude, longitude): print(f"Fetching weather for {city}...") url = ( f"https://api.open-meteo.com/v1/forecast" f"?latitude={latitude}&longitude={longitude}" f"&current_weather=true" ) response = requests.get(url) data = response.json() temperature = data["current_weather"]["temperature"] print(f"{city}: {temperature}°C") start_time = time.time() cities = [ ("London", 51.5, -0.12), ("New York", 40.71, -74.01), ("Tokyo", 35.68, 139.69), ] for city, latitude, longitude in cities: fetch_weather(city, latitude, longitude) elapsed_time = time.time() - start_time print(f"Total time: {elapsed_time:.2f}s")

Each request waits for the previous one to finish. Three cities, three full waits – one after another.

Why This Matters

The bottleneck here is not the CPU. While waiting for the server to respond, your Python process is sitting idle. It has capacity to do other work but isn't allowed to.

This becomes a real problem at scale:

  • Fetching data from 100 APIs sequentially takes 100× longer than it needs to;
  • A web server handling 1,000 simultaneous users can't afford to block on each database query;
  • Data pipelines that read from multiple sources waste most of their runtime just waiting.

The CPU is fast. The network is slow. Blocking code forces fast hardware to wait for slow I/O.

The Alternative

The same three requests can run concurrently – started almost simultaneously, with results collected as they arrive:

12345678910111213141516171819202122232425262728293031
import asyncio import httpx import nest_asyncio nest_asyncio.apply() # Fetching weather data for three cities concurrently async def fetch_weather(client, city, latitude, longitude): print(f"Fetching weather for {city}...") url = ( f"https://api.open-meteo.com/v1/forecast" f"?latitude={latitude}&longitude={longitude}" f"&current_weather=true" ) response = await client.get(url) data = response.json() temperature = data["current_weather"]["temperature"] print(f"{city}: {temperature}°C") async def main(): cities = [ ("London", 51.5, -0.12), ("New York", 40.71, -74.01), ("Tokyo", 35.68, 139.69), ] async with httpx.AsyncClient() as client: await asyncio.gather( *[fetch_weather(client, city, lat, lon) for city, lat, lon in cities] ) asyncio.run(main())
Note
Note

All code samples in this course use two lines at the top:

import nest_asyncio
nest_asyncio.apply()

This is needed because this platform runs code inside a Jupyter-style environment, which already has a running event loop. Calling asyncio.run() inside a running loop raises a RuntimeErrornest_asyncio patches the loop to allow it.

Note
Note

Code samples throughout this course use httpx, a modern HTTP library with native async support. It mirrors the requests API you may already know, so the syntax will feel familiar. A full introduction to httpx – connection pooling, timeouts, error handling – appears in Section 3. For now, just install it with pip install httpx and treat await client.get(url) as the async equivalent of requests.get(url).

You don't need to understand every keyword yet – that's what this course is for. The point is the result: three requests, roughly the same time as one.

Asyncio is Python's built-in solution for writing concurrent code without threads or multiple processes.

question mark

What is the main reason blocking code is inefficient for I/O operations?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 1

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 1. Capítulo 1
some-alt