Skip to content

Instantly share code, notes, and snippets.

@akiross
Last active March 1, 2018 18:41
Show Gist options
  • Save akiross/57682a8ea4f9e6c6c560d2a6d1691755 to your computer and use it in GitHub Desktop.
Save akiross/57682a8ea4f9e6c6c560d2a6d1691755 to your computer and use it in GitHub Desktop.
How to use async __init__ magic method in Python
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