Skip to content

Instantly share code, notes, and snippets.

@nhoad
Last active August 29, 2015 14:18
Show Gist options
  • Save nhoad/82738c289b2bb598aa52 to your computer and use it in GitHub Desktop.
Save nhoad/82738c289b2bb598aa52 to your computer and use it in GitHub Desktop.
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