Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. import inspect
  2. from functools import wraps
  3.  
  4. def async_init_wrapper(func):
  5. def wrapper_stage1(instance):
  6. async def wrapper_stage2(*args, **kw):
  7. value = await func(instance, *args, **kw)
  8. if value is not None:
  9. raise TypeError("__async_init__() should return None")
  10. return instance
  11. return wrapper_stage2
  12. wrapper_stage1.__name__ = func.__name__
  13. return wrapper_stage1
  14.  
  15.  
  16. class AwaitableClass(type):
  17. def __new__(mcls, name, bases, ns, **kw):
  18. if "__init__" in ns and inspect.iscoroutinefunction(ns["__init__"]):
  19. ns["__async_init__"] = async_init_wrapper(ns.pop("__init__"))
  20. return super().__new__(mcls, name, bases, ns, **kw)
  21.  
  22. def __call__(cls, *args, **kw):
  23. instance = super().__call__(*args, **kw)
  24. if not isinstance(instance, cls) or not hasattr(cls, "__async_init__"):
  25. return instance
  26. return instance.__async_init__()(*args, **kw)
  27.  
  28.  
  29. def test_awaitable_class():
  30. import asyncio
  31.  
  32. class Server(metaclass=AwaitableClass):
  33.  
  34. async def __init__(self):
  35. self.connection = await self.connect()
  36.  
  37. async def connect(self):
  38. await asyncio.sleep(1)
  39. return 'server initialized connection'
  40.  
  41. async def concurrent_task():
  42. await asyncio.sleep(0.5)
  43. print("doing stuff while server is initialized")
  44.  
  45. async def init_server():
  46. print("starting server initialization")
  47. server_instance = await Server()
  48. print("server ready")
  49. return server_instance
  50.  
  51. async def main():
  52. results = await asyncio.gather(
  53. init_server(),
  54. concurrent_task()
  55. )
  56. return results[0]
  57. loop = asyncio.get_event_loop()
  58. server_instance = loop.run_until_complete(main())
  59. print(server_instance.connection)
  60.  
  61.  
  62. if __name__ == "__main__":
  63.  
  64. test_awaitable_class()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement