A context manager that controls event loop life cycle. The context manager always creates a new event loop, allows to run async functions inside it, and properly finalizes the loop at the context manager exit. If debug is True, the event loop will be run in debug mode. If loop_
| 19 | |
| 20 | |
| 21 | class Runner: |
| 22 | """A context manager that controls event loop life cycle. |
| 23 | |
| 24 | The context manager always creates a new event loop, |
| 25 | allows to run async functions inside it, |
| 26 | and properly finalizes the loop at the context manager exit. |
| 27 | |
| 28 | If debug is True, the event loop will be run in debug mode. |
| 29 | If loop_factory is passed, it is used for new event loop creation. |
| 30 | |
| 31 | asyncio.run(main(), debug=True) |
| 32 | |
| 33 | is a shortcut for |
| 34 | |
| 35 | with asyncio.Runner(debug=True) as runner: |
| 36 | runner.run(main()) |
| 37 | |
| 38 | The run() method can be called multiple times within the runner's context. |
| 39 | |
| 40 | This can be useful for interactive console (e.g. IPython), |
| 41 | unittest runners, console tools, -- everywhere when async code |
| 42 | is called from existing sync framework and where the preferred single |
| 43 | asyncio.run() call doesn't work. |
| 44 | |
| 45 | """ |
| 46 | |
| 47 | # Note: the class is final, it is not intended for inheritance. |
| 48 | |
| 49 | def __init__(self, *, debug=None, loop_factory=None): |
| 50 | self._state = _State.CREATED |
| 51 | self._debug = debug |
| 52 | self._loop_factory = loop_factory |
| 53 | self._loop = None |
| 54 | self._context = None |
| 55 | self._interrupt_count = 0 |
| 56 | self._set_event_loop = False |
| 57 | |
| 58 | def __enter__(self): |
| 59 | self._lazy_init() |
| 60 | return self |
| 61 | |
| 62 | def __exit__(self, exc_type, exc_val, exc_tb): |
| 63 | self.close() |
| 64 | |
| 65 | def close(self): |
| 66 | """Shutdown and close event loop.""" |
| 67 | if self._state is not _State.INITIALIZED: |
| 68 | return |
| 69 | try: |
| 70 | loop = self._loop |
| 71 | _cancel_all_tasks(loop) |
| 72 | loop.run_until_complete(loop.shutdown_asyncgens()) |
| 73 | loop.run_until_complete( |
| 74 | loop.shutdown_default_executor(constants.THREAD_JOIN_TIMEOUT)) |
| 75 | finally: |
| 76 | if self._set_event_loop: |
| 77 | events.set_event_loop(None) |
| 78 | loop.close() |
no outgoing calls
no test coverage detected
searching dependent graphs…