/edgedb/compat.py

https://github.com/edgedb/edgedb-python · Python · 55 lines · 28 code · 9 blank · 18 comment · 9 complexity · 0f9e747643277ed85ed50af4064cea52 MD5 · raw file

  1. #
  2. # This source file is part of the EdgeDB open source project.
  3. #
  4. # Copyright 2016-present MagicStack Inc. and the EdgeDB authors.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. #
  18. import asyncio
  19. import sys
  20. if sys.version_info < (3, 7):
  21. # Workaround for https://bugs.python.org/issue37658
  22. import functools
  23. async def _cancel_and_wait(fut):
  24. def _release_waiter(waiter, *args):
  25. if not waiter.done():
  26. waiter.set_result(None)
  27. waiter = asyncio.get_event_loop().create_future()
  28. cb = functools.partial(_release_waiter, waiter)
  29. fut.add_done_callback(cb)
  30. try:
  31. fut.cancel()
  32. await waiter
  33. finally:
  34. fut.remove_done_callback(cb)
  35. async def wait_for(fut, timeout):
  36. fut = asyncio.ensure_future(fut)
  37. try:
  38. return await asyncio.wait_for(fut, timeout)
  39. except (asyncio.CancelledError, asyncio.TimeoutError):
  40. if fut.done():
  41. return fut.result()
  42. else:
  43. await _cancel_and_wait(fut)
  44. raise
  45. else:
  46. wait_for = asyncio.wait_for