How Python Finds Imported Modules

  • google plus

In Brief...

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

Take our Introduction to Python Training course for free.

See the Course Outline and Register

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']

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, XML, Windows, Java, Adobe, HTML5, JavaScript, Angular, and much more. Check out our complete course catalog.

Categories

Courses

Author: Nat Dunn

Nat Dunn founded Webucator in 2003 to combine his passion for technical training with his business expertise and to help companies benefit from both. His previous experience was in sales, business and technical training, and management. Nat has an MBA from Harvard Business School and a BA in International Relations from Pomona College.

Discuss