Python 3.4+until 3.16Async programmingfunction
asyncio.set_event_loop_policy()
event loop
Deprecated: replaces the global event loop policy; deprecated since 3.14 with removal in 3.16. Use loop_factory of asyncio.run() and Runner instead.
Syntax
asyncio.set_event_loop_policy(policy)
The classic old recipe is set_event_loop_policy(uvloop.EventLoopPolicy()) or WindowsSelectorEventLoopPolicy() for libraries that fail under Proactor. The swap is global: it affects the whole process, other libraries and tests included. Today the same is done locally: asyncio.run(main(), loop_factory=uvloop.new_event_loop). set_event_loop_policy(None) restores the default policy.
Examples
# Python 3.12+
import asyncio
async def main():
await asyncio.sleep(0.01)
return 'ок'
# вместо set_event_loop_policy(...) — цикл для одного запуска
print(asyncio.run(main(), loop_factory=asyncio.new_event_loop)) # → ок
import asyncio
import warnings
with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning) # с 3.14 вызов устарел
asyncio.set_event_loop_policy(None) # None — политика по умолчанию
print(asyncio.run(asyncio.sleep(0.01, result='ок'))) # → ок
# Python 3.16+
import asyncio
async def main():
await asyncio.sleep(0)
return 'ок'
# вместо set_event_loop_policy(...): один цикл на несколько запусков
with asyncio.Runner(loop_factory=asyncio.EventLoop) as runner:
print(runner.run(main()), runner.run(main())) # → ок ок
See also
Open in the full glossarydocs.python.orgReport an inaccuracy