AttributeError: module 'urllib' does not have attribute 'parse'

python 3.5.2

code 1

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

he gave this error:

AttributeError: module 'urllib' does not have attribute 'parse'

code 2

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

it works...

code3

 from flask import Flask # from urllib.parse import quote # s = quote('"') import urllib s = urllib.parse.quote('"') print(s) 

he works too. because of the flask?

Why don't I have a mistake anymore? this is mistake?

+9
source share
2 answers

The urllib package urllib used only as a namespace. There are other modules under urllib like request and parse .
For optimization, urllib import urllib not import other modules under it. Because it will require processor cycles and memory, but people may not need these other modules.
Separate modules under urllib should be imported separately depending on needs.

Try this, the first one will fail, but the second one is successful, because when flask 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"])' 
+7
source

For code 1 to work , you need to import the urllib.parse module, not the quote function. Thus, you can reference the quote function with the full qualifier of the module. 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 a module qualifier, since it is not imported in the context of the module. With this approach, you can only use an explicitly imported function from the parse module.

code 3 works because flask implicitly imports the urllib.parse module. The parse module becomes available in the context of the urllib module. After importing urllib urllib.parse becomes available and you can use it as in code 1

+5
source

Source: https://habr.com/ru/post/1013819/


All Articles