`from ... import` vs `import .`

ghz 3months ago ⋅ 34 views

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:

  1. Using from urllib import request:

    from urllib import request
    

    This imports the request submodule directly from urllib, so you can use it like:

    request.urlopen('http://example.com')
    
  2. Using import urllib.request:

    import urllib.request
    

    This imports the urllib module, along with its request 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 the request submodule, so you refer to it simply as request. With import urllib.request, you're importing the entire urllib module, and you have to access the request submodule through the full urllib.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 where request is coming from (i.e., from the urllib 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.