Python Glossary Русский

Python 3.4+Async programmingfunction

asyncio.set_event_loop()

event loop

Makes a loop current for this OS thread, so that get_event_loop() returns it outside coroutines.

Syntax

asyncio.set_event_loop(loop)

You need it only when managing a loop by hand: asyncio.run() and asyncio.Runner set and clear the current loop themselves. Each thread has its own current loop, so a loop set in the main thread is invisible to a worker thread. After closing the loop call set_event_loop(None), or get_event_loop() will hand back a closed loop.

Examples

import asyncio
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
print(asyncio.get_event_loop() is loop)  # → True
loop.run_until_complete(asyncio.sleep(0.01))
loop.close()
asyncio.set_event_loop(None)  # не оставлять закрытый цикл текущим

See also

Open in the full glossarydocs.python.orgReport an inaccuracy