Last active
March 1, 2018 18:41
-
-
Save akiross/57682a8ea4f9e6c6c560d2a6d1691755 to your computer and use it in GitHub Desktop.
How to use async __init__ magic method in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
class AsyncClass: | |
async def __new__(cls, *args, **kwargs): | |
o = super().__new__(cls) | |
# Explicit async call | |
await o.__init__(*args, **kwargs) | |
return o # __init__ will be called anyway | |
async def __init__(self, *args, **kwargs): | |
print('Executing async init!', args, kwargs) | |
async def runner(): | |
obj = await AsyncClass('foo', bar=123) | |
print(obj) | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(runner()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment