38

I found the following line in Python code:

from six.moves import urllib

Simultaneously, I can find urllib.py anywhere. I found that there is a file six.py in package root and it has class Module_six_moves_urllib(types.ModuleType): inside.

Is this it? How is this defined?

UPDATE

Sorry I am new to Python and the question is about Python syntax. I learned, that what is after import is Python file name without a py extension. So, where is this file in this case?

Dims
  • 47,675
  • 117
  • 331
  • 600

1 Answers1

68

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.

Zvika
  • 1,236
  • 12
  • 16
karlson
  • 5,325
  • 3
  • 30
  • 62