Why use explicit loop parameter with aiohttp?

旧时模样 提交于 2019-12-24 09:18:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!