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

wchargin picture wchargin · Feb 25, 2012 · Viewed 378.6k times · Source

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)?

Answer

g.d.d.c picture g.d.d.c · Feb 25, 2012

It depends on how you want to access the import when you refer to it.

from urllib import request
# access request directly.
mine = request()

import urllib.request
# used as urllib.request
mine = urllib.request()

You can also alias things yourself when you import for simplicity or to avoid masking built ins:

from os import open as open_
# lets you use os.open without destroying the 
# built in open() which returns file handles.