...

/

Magic Asynchronous Methods

Magic Asynchronous Methods

Learn about the asynchronous magic methods in Python.

We can take advantage of the magic methods in Python to make the abstractions we created blend naturally with the syntax of the language and this way achieve better, more compact, and perhaps cleaner code.

But what happens if on any of these methods we need to call a coroutine? If we have to call await in a function, that means the function itself would have to be a coroutine (defined with async def), or else there will be a syntax error.

But then, how does this work with the current syntax and magic methods? It doesn't. We need new syntax, and new magic methods, in order to work with asynchronous programming. The good news is that they're analogous to the previous ones.

Here's a summary of the new magic methods and how they relate to the new syntax.

Asynchronous Syntax and Their Magic Methods

Concept

Magic Methods

Syntax Usage

Context Manager

__aenter__

__aexit__

async with async_cm() as x:

...

Iteration

__aiter__

__anext__

async for e in aiter:

...

This new syntax is mentioned in PEP-492 ...