Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 242
Hong Yinjie Avatar asked Jan 06 '17 08:01

Hong Yinjie


1 Answers

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"])' 
like image 61
Nizam Mohamed Avatar answered Sep 19 '22 16:09

Nizam Mohamed