Skip to content

Module 14 · Python Modules and Packages — topic 3 of 13

import

The import statement in detail: importing whole modules, where Python looks for them (sys.path), module caching, importing dynamically with importlib, and handling ModuleNotFoundError.

Beginner 8 min read·Lesson 211 of 306 in Python Programming

Learning objectives

  • Use import to load modules
  • Explain the module search path
  • Import modules dynamically and handle missing ones

Definition

import name finds a module, runs it if it hasn't been loaded yet, and binds the module object to name in the current namespace. Python searches the directories listed in sys.path to find it.

Introduction

import is the gateway to everything outside your own file: the standard library, installed packages and your own modules.

Why it matters

Understanding how import searches and caches explains common puzzles: why a module is 'not found', why changes don't appear until restart, and why a local file can hide a standard module.

Detailed explanation

import math binds the name math to the module object; access its contents with math.sqrt.

Several modules can be imported on separate lines (preferred) or in one statement separated by commas.

The search order is sys.path: the folder of the running script (or the current directory), entries from PYTHONPATH, the standard library, then site-packages where installed packages live.

Modules are loaded once per program and stored in sys.modules; later imports reuse the same object.

importlib.import_module("name") imports a module whose name is only known at runtime, such as a plugin chosen in a configuration file.

If no module is found, ModuleNotFoundError (a subclass of ImportError) is raised.

PEP 8 recommends imports at the top of the file, grouped: standard library, third-party, then your own modules.

Syntax

Python
import math
import statistics
import importlib
mod = importlib.import_module("json")
  • import binds a module name.
  • sys.path decides where to look.
  • importlib for dynamic imports.

Code examples

Importing modules

Python
import math
import statistics
print(math.floor(3.7), statistics.mean([1, 2, 3, 4]))
Output
3 2.5

Imports are cached

Python
import json
import json as j2
import sys
print(json is j2)
print("json" in sys.modules)
Output
True
True

More examples

Dynamic imports

Python
import importlib
for name in ["math", "statistics", "not_a_real_module"]:
try:
mod = importlib.import_module(name)
public = [n for n in dir(mod) if not n.startswith("_")]
print(name, "->", mod.__name__, len(public) > 5)
except ModuleNotFoundError as e:
print(name, "->", e)
Output
math -> math True
statistics -> statistics True
not_a_real_module -> No module named 'not_a_real_module'

Step-by-step explanation

  • import_module takes the module name as a string.
  • The returned object is the same kind of module object a normal import creates.
  • A missing module raises ModuleNotFoundError, which can be handled like any exception.

Expected output

Running “Dynamic imports” prints exactly:

TextOutput
math -> math True
statistics -> statistics True
not_a_real_module -> No module named 'not_a_real_module'

Practical applications

  • Plugin systems loading modules named in configuration.
  • Scripts that report a friendly message when an optional dependency is missing.

Best practices

  • Put imports at the top, grouped and one per line.
  • Use import_module only when the name is dynamic.
  • Avoid modifying sys.path by hand; organise code as packages instead.

Common mistakes

Expecting edits to reload

Avoid

import mymodule
# edit mymodule.py ...
import mymodule # still the old version

Prefer

Restart the program (or importlib.reload(mymodule) while experimenting).

Imports are cached for the life of the program.

Important notes

  • python -X importtime script.py shows how long each import takes.

Key takeaways

  • import loads a module once and binds its name.
  • Python searches sys.path in order.
  • importlib.import_module imports by string name.

Try it yourself

  1. 1
    Print the first three entries of sys.path and explain each.
  2. 2
    Write a function that imports a module by name and returns None if it is missing.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat happens the second time a module is imported in the same program?
Practise this topic