utils.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from collections.abc import Awaitable
  2. from inspect import CO_ITERABLE_COROUTINE
  3. from types import CoroutineType
  4. from types import GeneratorType
  5. async def do_await(obj):
  6. return await obj
  7. def do_yield_from(gen):
  8. return (yield from gen)
  9. def await_(obj):
  10. obj_type = type(obj)
  11. if (
  12. obj_type is CoroutineType
  13. or obj_type is GeneratorType
  14. and bool(obj.gi_code.co_flags & CO_ITERABLE_COROUTINE)
  15. or isinstance(obj, Awaitable)
  16. ):
  17. return do_await(obj).__await__()
  18. else:
  19. return do_yield_from(obj)
  20. def __aiter__(self):
  21. return self.__wrapped__.__aiter__()
  22. async def __anext__(self):
  23. return await self.__wrapped__.__anext__()
  24. def __await__(self):
  25. return await_(self.__wrapped__)
  26. def __aenter__(self):
  27. return self.__wrapped__.__aenter__()
  28. def __aexit__(self, *args, **kwargs):
  29. return self.__wrapped__.__aexit__(*args, **kwargs)
  30. def identity(obj):
  31. return obj
  32. class cached_property:
  33. def __init__(self, func):
  34. self.func = func
  35. def __get__(self, obj, cls):
  36. if obj is None:
  37. return self
  38. value = obj.__dict__[self.func.__name__] = self.func(obj)
  39. return value