How Python Finds Imported Modules

  • google plus

In Brief...

The Python interpreter must locate imported modules. Where does it look for them?

Instructions

The Python interpreter must locate the imported modules. Where does it look for them?

When import is used within a script, the interpreter searches for the imported module in the following places sequentially:

  1. The current directory (same directory as script doing the importing).
  2. The library of standard modules.
  3. The paths defined inĀ sys.path.*

*sys.path contains a list of strings specifying the search path for modules. The list is os-dependent. To see your list, run the following code at your Python command prompt or in an IPython notebook cell:

import sys
sys.path

That will output something like this:

['',
 'D:\\Anaconda3\\python35.zip',
 'D:\\Anaconda3\\DLLs',
 'D:\\Anaconda3\\lib',
 'D:\\Anaconda3',
 'd:\\anaconda3\\lib\\site-packages\\setuptools-20.3-py3.5.egg',
 'D:\\Anaconda3\\lib\\site-packages',
 'D:\\Anaconda3\\lib\\site-packages\\Sphinx-1.3.1-py3.5.egg',
 'D:\\Anaconda3\\lib\\site-packages\\cryptography-1.0.2-py3.5-win-amd64.egg',
 'D:\\Anaconda3\\lib\\site-packages\\win32',
 'D:\\Anaconda3\\lib\\site-packages\\win32\\lib',
 'D:\\Anaconda3\\lib\\site-packages\\Pythonwin',
 'D:\\Anaconda3\\lib\\site-packages\\IPython\\extensions',
 'C:\\Users\\Nat\\.ipython']

Author: Nat Dunn

Nat Dunn founded Webucator in 2003 to combine his passion for web development with his business expertise and to help companies benefit from both.

Discuss