Skip to content

Instantly share code, notes, and snippets.

@safhac
Created February 3, 2022 10:11
Show Gist options
  • Save safhac/2a968d5cd5ef88b83be9f91cbb89d806 to your computer and use it in GitHub Desktop.
Save safhac/2a968d5cd5ef88b83be9f91cbb89d806 to your computer and use it in GitHub Desktop.
awaitable descriptor
import asyncio
import time
import traceback
class Awaitable:
def __init__(self, block_fns):
self.fns: list = block_fns
def __await__(self, *args, **kwargs):
for a, _ in self.fns:
return _
def __get__(self, instance, owner):
if instance is None:
return self
return getattr(instance, self._attr)
class Interface:
def __init__(self):
self.as_await = Awaitable
@staticmethod
def blocking(caller=None):
return 42 if caller in 'main' else (time.sleep(1), 42)[1]
async def main():
c = Interface()
print(c.blocking("main"))
try:
print(c.as_await([c.blocking('await')]).fns)
except Exception as e:
traceback.print_exc()
print('error', e)
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment