What does `from six.moves import urllib` do in Python?

six is a package that helps in writing code that is compatible with both Python 2 and Python 3.

One of the problems developers face when writing code for Python2 and 3 is that the names of several modules from the standard library have changed, even though the functionality remains the same.

The six.moves module provides those modules under a common name for both Python2 and 3 (mostly by providing the Python2 module under the name of the Python 3 module).

So your line

from six.moves import urllib

imports urllib when run with Python3 and imports a mixture of urllib, urllib2 and urlparse with Python2, mimicking the structure of Python3’s urllib. See also here.

EDIT to address the update of the question:

TLDR; There is not necessarily a direct relation between the imported module urllib and a file on the filesystem in this case. The relevant file is exactly what six.__file__ points to.

Third party modules are defined in a file/directory that is
listed in sys.path. Most of the time you can find the name of the file a module is imported from by inspecting the __file__ attribute of the module in question, e.g. six.__file__. However with six.moves things are not as simple, precisely because the exposed modules might not actually map one to one to actual Python modules but hacked versions of those.

Leave a Comment

tech