async contextmanager
![](https://secure.gravatar.com/avatar/c6cdaadab563444e30d5489656b3ff60.jpg?s=120&d=mm&r=g)
Has anyone tried to build an asynchronous version of @contextmanager? Is it even possible... given the use of yield?
![](https://secure.gravatar.com/avatar/c0962616cb99f5c874a17440934191e9.jpg?s=120&d=mm&r=g)
Certainly. You can use asyncio_extras for that: http://pythonhosted.org/asyncio_extras/#asyncio-extras-contextmanager 01.11.2016, 18:15, Federico Marani kirjoitti:
Has anyone tried to build an asynchronous version of @contextmanager? Is it even possible... given the use of yield?
_______________________________________________ Async-sig mailing list Async-sig@python.org https://mail.python.org/mailman/listinfo/async-sig Code of Conduct: https://www.python.org/psf/codeofconduct/
![](https://secure.gravatar.com/avatar/4e332fe1cf22e027fd875b467a835ae4.jpg?s=120&d=mm&r=g)
I played with it some time ago. Actually, original code <https://github.com/python/cpython/blob/master/Lib/contextlib.py> with few changes works fine. Here's example: https://gist.github.com/germn/6b2f8a1afbfc322daa01365cacd1d9ad Test it: import asyncio from acontextlib import acontextmanager state = [] @acontextmanager async def woohoo(): state.append(1) yield 42 state.append(999) async def main(): async with woohoo() as x: assert state == [1] assert x == 42 if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) 01.11.2016 19:15, Federico Marani пишет:
Has anyone tried to build an asynchronous version of @contextmanager? Is it even possible... given the use of yield?
_______________________________________________ Async-sig mailing list Async-sig@python.org https://mail.python.org/mailman/listinfo/async-sig Code of Conduct: https://www.python.org/psf/codeofconduct/
![](https://secure.gravatar.com/avatar/feb5a3fc022be305ce8c428bc8ffaf3d.jpg?s=120&d=mm&r=g)
Has anyone tried to build an asynchronous version of @contextmanager? Is it even possible... given the use of yield?
Thanks to PEP 525 - Asynchronous generators [1], it will be possible in python 3.6. Here's a possible implementation [2]. [1] https://www.python.org/dev/peps/pep-0525/ [2] https://github.com/vxgmichel/aiostream/blob/master/aiostream/context_utils.p... /Vincent
participants (4)
-
Alex Grönholm
-
Federico Marani
-
Vincent Michel
-
Герасимов Михаил