The Invent with Python Blog

Fri 31 March 2017

Python Import Tutorial: Rules, Paths, and Pitfalls

Posted by Al Sweigart in python   

NOTE: This tutorial is still under construction. It is incomplete and the information in it has not been verified.

My personal knowledge of Python's import statement has always been patchy. I kinda sorta knew how it worked, and could consult Stack Overflow to figure out problems as they came up. But I never sat down to formally sutdy how imports in Python worked. I've written this tutorial to organize my thoughts. The level of the target audeince for this tutorial is for people comfortable with basic Python syntax. Assume the information in this tutorial is for Python 3.6 except when otherwise stated.

  • If you just want to skim this document, the main points are in bullets like this.
  • And this.
  • And this.

Basics of Importing

Importing modules from Python's standard library is straight-forward and familiar to anyone who's done basic Python:

>>> import math
>>> math.sqrt(25)
5.0

The previous code always works, no matter what the cwd, or current working directory, is or the location of the .py file that runs the above code.

You can also import other .py files as modules. Imagine the following coffee.py and america.py scripts are both in the same folder:

coffee.py

print('Coffee!')

def shouldDrinkCoffee():
    return True

america.py

import coffee

print('I should drink coffee:', coffee.shouldDrinkCoffee())

Running america.py produces the following output:

Coffee!
I should drink coffee: True

The america.py Python script imports coffee.py and calls a function in it. Three things to note:

  • The import statement accepts an identifier, not a string. It's import coffee, not import 'coffee'.
  • You do not include the .py: It's import coffee, not import coffee.py
  • Note that importing a module runs the code inside of it, hence why print('Coffee!') was executed when coffee.py was imported.

If you want to import modules by string, use the

If you import a module a second time, the code the module doesn't run again. The module is cached. If you ran:

import coffee
import coffee

The print('Coffee!') line is only executed by the first import coffee statement.

NOTES: "module search path" sys.path is set from PYTHONPATH? (What if I don't have that env var set?) Changing sys.path direclty is like changing your PYTHONPATH env var. sys == sys.modules['sys'] sys.modules always has real name of the module, not the "as foo" name. sys.builtin_module_names doesnt change as you import modules. its a tuple importlib.import_module() is a wrapper for __import__. >>> __import__('random') >>> random.randint(1, 10) Traceback (most recent call last): File "", line 1, in NameError: name 'random' is not defined importlib is new in Python 2.7. import statement imports into the current scope How does this affect sys.modules importing modules doesn't affect sys.modules. Why not? A package is just a folder with some Python files in it. if __name__ best practice from __future__ import absolute_imports (use on python 2, allows for *explicit* relative imports)

Comments