Skip to content

Instantly share code, notes, and snippets.

@nhoad

nhoad/code.py

Last active Aug 29, 2015
Embed
What would you like to do?
asynchronous object initialisation
import asyncio
class AsyncInitMeta(type):
@asyncio.coroutine
def __call__(cls, *args, **kwargs):
self = cls.__new__(cls)
yield from self.__init__(*args, **kwargs)
return self
class Person(metaclass=AsyncInitMeta):
def __init__(self, f):
name = yield from f
self.name = name
def __repr__(self):
return 'Person(name={})'.format(self.name)
f = asyncio.Future()
f.set_result('nathan')
person = asyncio.get_event_loop().run_until_complete(Person(f))
print('hello', person.name)
print('person?', person)
hello nathan
person? Person(name=nathan)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment