Python __await__() Magic Method

Rate this post

The __await__() magic method defines the behavior of an awaitable object. An awaitable object is used to implement asynchronous behavior in Python.

For example, you can implement an asynchronous function that waits for the data based to access some data like so (see source):

async def read_data(db):
    data = await db.fetch('SELECT ...')

Syntax __await__()

object.__await__(self)

The __await__() method must return an iterator. Otherwise, it raises a TypeError.

What is await in Python?

Say, you call await do_something() in the body of the function f. In this case, function f will suspend its execution while do_something() runs. As soon as the do_something() terminates, the event loop — responsible for running asynchronous tasks — will resume the execution of function f and will pass the result to the calling environment.

The behavior of the await keyword on the awaitable object (in our case do_something()) can be defined using the __await__() method.

“A coroutine waiting for a Future-like object is suspended until the Future-like object’s __await__() completes, and returns the result.” (source)

? You can learn more about the concept of coroutines here.