I'm wondering if there's any difference between the code fragment
from urllib import request and the fragment
import urllib.request or if they are interchangeable. If they are interchangeable, which is the "standard"/"preferred" syntax (if there is one)?
Answers
Both of the following code fragments are functionally equivalent in terms of importing the urllib.request
module:
-
Using
from urllib import request
:from urllib import request
This imports the
request
submodule directly fromurllib
, so you can use it like:request.urlopen('http://example.com')
-
Using
import urllib.request
:import urllib.request
This imports the
urllib
module, along with itsrequest
submodule, so you need to use it like:urllib.request.urlopen('http://example.com')
Differences:
-
Namespace visibility: The main difference is how the namespace is handled. With
from urllib import request
, you're directly importing therequest
submodule, so you refer to it simply asrequest
. Withimport urllib.request
, you're importing the entireurllib
module, and you have to access therequest
submodule through the fullurllib.request
path. -
Readability and explicitness: The second form (
import urllib.request
) is generally preferred in Python because it makes the code more explicit. It’s clearer whererequest
is coming from (i.e., from theurllib
module), which can improve code readability, especially in larger codebases.
Standard/Preferred Syntax:
The more common and "standard" form in Python is:
import urllib.request
This is preferred because it adheres to Python's philosophy of explicitness (as per the Zen of Python: "Explicit is better than implicit"). It makes it clear that request
is part of the urllib
module, which can help avoid confusion in larger projects where many modules might be used.