Skip to content
Advertisement

How to set class attribute with await in __init__

How can I define a class with await in the constructor or class body?

For example what I want:

JavaScript

or example with class body attribute:

JavaScript

My solution (But I would like to see a more elegant way)

JavaScript

Advertisement

Answer

Most magic methods aren’t designed to work with async def/await – in general, you should only be using await inside the dedicated asynchronous magic methods – __aiter__, __anext__, __aenter__, and __aexit__. Using it inside other magic methods either won’t work at all, as is the case with __init__ (unless you use some tricks described in other answers here), or will force you to always use whatever triggers the magic method call in an asynchronous context.

Existing asyncio libraries tend to deal with this in one of two ways: First, I’ve seen the factory pattern used (asyncio-redis, for example):

JavaScript

Other libraries use a top-level coroutine function that creates the object, rather than a factory method:

JavaScript

The create_pool function from aiopg that you want to call in __init__ is actually using this exact pattern.

This at least addresses the __init__ issue. I haven’t seen class variables that make asynchronous calls in the wild that I can recall, so I don’t know that any well-established patterns have emerged.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement