Async IO and Futures in Python: What's the Difference?

Mar 17, 2024 ยท 2 min read

Asynchronous programming has become increasingly popular in Python. Two key concepts for async are asyncio and futures. But what exactly is the difference between the two?

Async IO: Asynchronous I/O Made Easy

The asyncio module is used to write asynchronous code in Python. It provides infrastructure for writing async/await code that looks synchronous but allows other tasks to run while one is waiting for I/O.

Some key features of asyncio:

  • Provides an event loop to run tasks and callbacks
  • Enables running I/O operations asynchronously via async/await
  • Great for I/O bound apps like web servers and clients
  • For example:

    import asyncio
    
    async def fetch_data():
      print('fetching...')
      await asyncio.sleep(2) # pause for 2 seconds
      print('done!')
    
    async def main():
      await fetch_data()
    
    asyncio.run(main())

    This allows other tasks to run while fetch_data pauses for 2 seconds, enabling asynchronous concurrency.

    Futures: Managing Promise of a Result

    A future represents an eventual result of an asynchronous operation. They provide a way to indirectly wait for and get the result of a long running operation.

    Some key aspects of futures:

  • Represent a result that will be available in the future
  • Enable waiting for the result without blocking by using yield from
  • Integrate well with asyncio event loop
  • For example:

    from concurrent.futures import Future
    
    f = Future()
    
    def resolve_future():
      print('resolving future...')
      f.set_result('future is done!')
    
    f.add_done_callback(lambda x: print(x.result()))
    
    resolve_future()

    So in summary, asyncio provides infrastructure for async I/O concurrency while futures represent eventual results of asynchronous operations. The two concepts work together nicely in the async world!

    Browse by tags:

    Browse by language:

    The easiest way to do Web Scraping

    Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


    Try ProxiesAPI for free

    curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

    <!doctype html>
    <html>
    <head>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    ...

    X

    Don't leave just yet!

    Enter your email below to claim your free API key: