问题
The aiohttp
library's documentation states:
loop – event loop used for processing HTTP requests. If param is None, asyncio.get_event_loop() is used for getting default event loop, but we strongly recommend to use explicit loops everywhere. (optional)
It is possible to pass the loop
to ClientSession
objects, to provided "module-level" functions etc.
I am new to the asynchronous programming concept as a whole, could you explain to me why it's recommended to explicitely provide the loop to use, rather than letting the objects/functions just use the default?
One use that comes to mind is making testing easier, by being able to provide my own loop mocks, is there a performance reason?
回答1:
The reason is readability and not performance.
Specifying a loop explicitly will make it easier for a developer to see where the loop instance originates from, and might make it easier to change the loop if a custom loop needs to be injected to the program.
Another popular option would be to never specify the loop parameter, and therefore assume asyncio.get_event_loop()
is always called to get a loop instance.
(It is possible to use more than one loop - for example in different threads, but this is not a common use case)
来源:https://stackoverflow.com/questions/42350334/why-use-explicit-loop-parameter-with-aiohttp