This is a simple test code and result.
import asyncio
async def test():
await asyncio.sleep(1)
if __name__ == '__main__':
asyncio.set_event_loop(None)
loop = asyncio.new_event_loop()
loop.run_until_complete(test())
Traceback (most recent call last):
File "test_test.py", line 11, in <module>
loop.run_until_complete(test())
File "/usr/lib/python3.5/asyncio/base_events.py", line 387, in run_until_complete
return future.result()
File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
raise self._exception
File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "test_test.py", line 5, in test
await asyncio.sleep(1)
File "/usr/lib/python3.5/asyncio/tasks.py", line 510, in sleep
loop = events.get_event_loop()
File "/usr/lib/python3.5/asyncio/events.py", line 632, in get_event_loop
return get_event_loop_policy().get_event_loop()
File "/usr/lib/python3.5/asyncio/events.py", line 578, in get_event_loop
% threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'MainThread'.
I run async def test()on new loopand expect that asyncio.sleep(1), nested test(), also uses new loop.
In contrast, it sleep()still has access to main loop, which I set as None.
I know that I can reinstall main loopas new loopwith asyncio.set_event_loop(loop)before the call run_until_complete(), and it will work without any exceptions.
However, I want to know that for asynciothis is normal, that main loopMust be installed and used for coroutines regardless of the cycle in which coroutines are executed.