python 3.5.2
code 1
import urllib
s = urllib.parse.quote('"')
print(s)
it gave this error:
AttributeError: module 'urllib' has no 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)
it works,too. because of flask?
Why I don't have the error anymore? is it a bug ?
The
urllib
package serves as a namespace only. There are other modules underurllib
likerequest
andparse
.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 importedflask
itself importsurllib.parse
.For code 1 to work you need to import the
urllib.parse
module, not the functionquote
. This way you can refer to thequote
function with full module qualifier. With this approach you can use any function defined in theparse
module: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 theparse
module.code 3 works, because
flask
imports implicitly theurllib.parse
module. Theparse
module becomes available in theurllib
module context. Once you importurllib
,urllib.parse
becomes readily available and you can use it as in code 1