fork download
  1. import asyncio
  2.  
  3. from collections import UserDict
  4. from typing import Any
  5.  
  6.  
  7. class AwaitDict(UserDict):
  8. def __init__(self, dict=None, /, **kwargs):
  9. self._await_task: dict[str, asyncio.Future] = {}
  10. super().__init__(dict=None, **kwargs)
  11.  
  12. def __setitem__(self, key: str, item: Any):
  13. if future := self._await_task.get(key):
  14. if future.done():
  15. raise Exception('Expected value has not been received yet')
  16. future.set_result(item)
  17.  
  18. super().__setitem__(key, item)
  19.  
  20. def __getitem__(self, item: str) -> Any:
  21. if item in self._await_task:
  22. self._await_task.pop(item)
  23.  
  24. return super().__getitem__(item)
  25.  
  26. async def await_elem(self, key: str) -> Any:
  27. future = asyncio.Future()
  28. self._await_task[key] = future
  29. await future
  30. return future.result()
  31.  
  32.  
  33. async def set_elem(aw: AwaitDict, key: str, value: Any):
  34. await asyncio.sleep(3)
  35. aw[key] = value
  36.  
  37.  
  38. async def main():
  39. my_dict = AwaitDict()
  40. asyncio.create_task(
  41. set_elem(
  42. aw=my_dict,
  43. key='123',
  44. value=123
  45. )
  46. )
  47. data = await my_dict.await_elem('123')
  48. print(data)
  49. print(my_dict['123'])
  50.  
  51. asyncio.run(main())
  52.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Traceback (most recent call last):
  File "/usr/lib/python3.7/py_compile.py", line 143, in compile
    _optimize=optimize)
  File "<frozen importlib._bootstrap_external>", line 791, in source_to_code
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "./prog.py", line 8
    def __init__(self, dict=None, /, **kwargs):
                                  ^
SyntaxError: invalid syntax

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.7/py_compile.py", line 147, in compile
    raise py_exc
py_compile.PyCompileError:   File "./prog.py", line 8
    def __init__(self, dict=None, /, **kwargs):
                                  ^
SyntaxError: invalid syntax

stdout
Standard output is empty