Last active
August 29, 2015 14:18
-
-
Save nhoad/82738c289b2bb598aa52 to your computer and use it in GitHub Desktop.
asynchronous object initialisation
This file contains 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 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) |
This file contains 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
hello nathan | |
person? Person(name=nathan) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment