AttributeError: module 'urllib' has no attribute 'parse'

我是研究僧i 提交于 2019-12-04 22:17:31

The urllib package serves as a namespace only. There are other modules under urllib like request and parse.
For optimization importing urllib doesn't import other modules under it. Because doing so would consume processor cycles and memory, but people may not need those other modules.
Individual modules under urllib must be imported separately depending on the needs.

Try these, the first one fails but the second succeeds because when flask is imported flask itself imports urllib.parse.

python3 -c 'import urllib, sys;print(sys.modules["urllib.parse"])'
python3 -c 'import flask, sys;print(sys.modules["urllib.parse"])'

For code 1 to work you need to import the urllib.parse module, not the function quote. This way you can refer to the quote function with full module qualifier. With this approach you can use any function defined in the parse module:

import urllib.parse
s = urllib.parse.quote('"')
print(s)

code 2 works, because you import only the parse function and refer to it without module qualifier, since it is not imported in the context of the module. With this approach you can use only the explicitly imported function from the parse module.

code 3 works, because flask imports implicitly the urllib.parse module. The parse module becomes available in the urllib module context. Once you import urllib, urllib.parse becomes readily available and you can use it as in code 1

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