Lesson 43 of 52Real projects
Modules and Packages
Split code into modules and packages, import it correctly, and debug ModuleNotFoundError and circular imports.
Your scripts so far have lived in one file. Real projects are not one file. A FastAPI service might have routes/, models/, services/ and tests/, with dozens of files importing each other. Knowing exactly how import finds code is what lets you fix ModuleNotFoundError in thirty seconds instead of an afternoon, and structure a project so it does not tangle itself into circular imports.
A module is just a .py file
Any Python file is a module. Its name is the filename without .py. Everything defined at the top level of the file (functions, classes, variables) becomes an attribute of the module object when you import it.
Let's create a module on the fly and import it. (The code windows here have a small in-memory file system, so this really works.)
Press Run (⌘ Enter) to see what happens.Two key facts are visible here. Importing a module executes its top-level code. And it happens only once per process: Python caches modules in sys.modules, so later imports just hand back the same module object.
The forms of import
| Statement | What you get | Use it when |
|---|---|---|
import json | the name json bound to the module | the default: json.loads(...) reads clearly |
import numpy as np | the module under a shorter alias | community conventions (np, pd) |
from math import sqrt, pi | just those names | you use a few names a lot |
from os import path as p | one name under an alias | avoiding a clash |
from module import * | every public name | almost never: it hides where names come from |
Press Run (⌘ Enter) to see what happens.import config. How many times does config.py's top-level code run?if __name__ == "__main__":
Every module has a __name__. When the file is imported, it is the module's name ("greetings"). When the file is run directly (python greetings.py), Python sets it to "__main__". That gives you a way to write code that runs only as a script, not on import:
def build_report(rows):
return f"{len(rows)} rows"
def main():
print(build_report([1, 2, 3]))
if __name__ == "__main__": # true for `python report.py`, false for `import report`
main()Without that guard, import report from a test would print and run main() as a side effect. With it, tests can import build_report safely. python -m package.module also runs the module as __main__.
What does this print?
import json print(__name__) print(json.__name__)
Packages: folders of modules
A package is a folder of modules. Adding an __init__.py file makes it a regular package: that file runs when the package is first imported, and is a good place to expose a small public API. (Folders without one still import as "namespace packages", but in your own projects, include __init__.py.)
- shop/
- __init__.pyruns on "import shop"; may re-export names
- main.pyentry point
- models/
- __init__.py
- product.pyclass Product
- order.pyclass Order, uses Product
- services/
- __init__.py
- pricing.pydef total(order)
- utils.pysmall helpers
Modules inside are addressed with dots: shop.models.product. Each dot is one folder level.
# absolute imports: the full path from the top-level package
from shop.models.product import Product
from shop.services import pricing
# relative imports, written inside shop/models/order.py
from .product import Product # same package (shop.models)
from ..utils import format_price # one level up (shop)Absolute imports spell out the full path. Relative imports start with dots: one dot is the current package, two dots its parent, and so on. Relative imports only work inside a package, never in a file you run directly as a script. PEP 8 (the style guide) recommends absolute imports for clarity; relative ones are fine inside a package for short hops.
shop/services/pricing.py, which import gets Order from shop/models/order.py?Running code inside a package: python -m
Sooner or later you will see this error after adding a relative import:
ImportError: attempted relative import with no known parent packageRelative imports are resolved from the module's __package__, the dotted name of the package it belongs to. When you run a file by path, python shop/main.py, Python loads it as a standalone script called __main__ with no package at all, so from .prices import VAT has nothing to be relative to. When you run python -m shop.main from the project root, Python imports shop first, then runs shop/main.py as __main__ with __package__ = "shop", and every import resolves exactly as it does in production.
Press Run (⌘ Enter) to see what happens.runpy is the standard-library module the python command itself uses for both modes. The two also differ in what lands at the front of sys.path: running by path adds the script's folder (shop/), while -m adds the current directory (the project root). That is why -m from the root makes import shop.anything work everywhere.
Absolute or relative, then? Absolute imports (from shop.prices import VAT) work identically in scripts, tests and the REPL, show up clearly in a grep, and are what PEP 8 and most linters prefer. Relative imports save typing inside deep packages and survive renaming the top-level package. Most teams pick absolute imports as the default and enforce it with a linter rule (Ruff has one), allowing a single dot for siblings at most. Whatever you choose, never mix in sys.path.append(...) hacks to make imports work: they hide a layout problem that the src layout in Project Structure solves properly. Once the project is installed into its virtual environment (uv sync does this), the package imports from anywhere.
shop/cli.py starts with from .config import load. Running python shop/cli.py fails with "attempted relative import with no known parent package". What is the right fix?__all__ and import *
from module import * copies every public name from a module into yours. By default "public" means every top-level name that does not start with an underscore, including things the module merely imported, such as re or os. If the module defines __all__, a list of strings, then import * takes exactly those names and nothing else.
Press Run (⌘ Enter) to see what happens.__all__ is not access control. textutils.shout and even textutils._clean are still reachable by name; Python has no private modules. What __all__ does is document the public API: documentation tools, IDE autocomplete and type checkers read it, and a package's __init__.py often re-exports a few names and lists them there (from .client import Client plus __all__ = ["Client"]), so users import from mylib import Client without knowing the internal layout. In your own application code, avoid import * outside the REPL: it makes it impossible to tell where a name came from, and a later version of the module can silently overwrite one of your names.
What does this print?
# colors.py contains:
# __all__ = ["RED"]
# RED = "#f00"
# BLUE = "#00f"
# _GREEN = "#0f0"
from colors import *
from colors import BLUE
print(RED, BLUE)
print("_GREEN" in dir())How Python finds a module
When you write import x, Python goes through these steps:
Put the import lookup steps in order.
- Tap the steps below in the right order.
sys.path starts with the folder of the script you ran (or the current directory with python -m), then the standard library, then site-packages, where pip installs things (inside your virtual environment, which is the next lesson).
Press Run (⌘ Enter) to see what happens.Two classic causes of ModuleNotFoundError:
- Running from the wrong place.
python shop/main.pyputsshop/onsys.path, not the project root, soimport shop.modelsfails. Runpython -m shop.mainfrom the project root instead. - Wrong environment. The package is installed in one Python and you are running another. Check with
python -c "import sys; print(sys.executable)".
And a sneaky one: naming your own file random.py or email.py. It shadows the standard library module for every import in that folder.
Shadowing the standard library
That last cause deserves its own section, because it produces the most confusing errors in Python. You write a quick experiment called random.py or statistics.py or json.py. Later, in the same folder, import random loads your file, because the script's folder is first on sys.path. The error appears far from the cause: AttributeError: module 'random' has no attribute 'randint', or a circular-import error from deep inside a library that imports random itself.
Press Run (⌘ Enter) to see what happens.The diagnosis takes one line: print(module.__file__) tells you which file was actually loaded. Python 3.13 and newer also help: when an AttributeError happens on a module whose name matches a standard-library module and the file is local, the error message says it may be shadowed. The fix is to rename your file (and delete the stale __pycache__ folder next to it).
The same mechanism is a security issue. If you run a script inside a folder you downloaded (a repo, an unzipped archive, a data dump), any json.py or os.py planted in that folder runs on your first import json. That is why you should run untrusted code's neighbours with python -I (isolated mode), or at least python -P (3.11+, also PYTHONSAFEPATH=1), which stops Python from adding the script's folder or the current directory to sys.path. Python Security Pitfalls covers the wider supply-chain picture.
tools/report.py does import email and crashes with AttributeError: module 'email' has no attribute 'message_from_string'. What do you check first?Circular imports
A circular import is when module A imports B while B imports A. Because importing executes code top to bottom, one of them sees the other half-initialised.
main.py runs import models.
The fixes, from best to worst:
- Restructure. A cycle usually means two modules are really one concept, or that shared pieces should move into a third module both can import (
types.py,schemas.py). - Depend in one direction. Lower layers (models) should never import higher layers (services, routes).
- Import the module, not the name (
import modelsthenmodels.Orderat call time), or move the import inside the function that needs it. These work, but treat them as patches.
Import cost and lazy imports
Because importing executes code, imports cost time. Importing a large library (a data-frame library, a cloud SDK, a machine-learning framework) can take hundreds of milliseconds, and it happens at startup whether or not this run uses it. For a long-running web server that is paid once. For a CLI that should answer --help instantly, a serverless function on a cold start, or a test suite that starts thousands of times a day, it adds up.
Measure before you change anything. -X importtime prints how long every import took, nested by who imported what, to stderr:
python3 -X importtime -c "import json"Each line shows the time spent in that module alone ("self") and including everything it imported ("cumulative"). Sort by the cumulative column and the expensive one is usually obvious.
There are two ways to defer the cost:
- Function-level imports work in every version. Move
import pandasinside the one function that needs it. The first call pays; later calls hit thesys.modulescache and cost almost nothing. The downside is that a missing dependency now fails at call time, not at startup, and readers cannot see all dependencies at the top of the file. Use it for heavy, optional or rarely used imports, not as a default. - Explicit lazy imports arrived in Python 3.15 (PEP 810):
lazy import jsonbinds a placeholder at module level and only really imports the module the first time the name is used. It keeps imports at the top where readers expect them. What Changed in Python 3.11 to 3.15 covers the rules (module level only, not insidetry, and how to opt in on older versions with__lazy_modules__).
import argparse # cheap, always needed
def export(path: str) -> None:
import pandas as pd # heavy: paid only when someone runs `export`
pd.read_csv(path).to_parquet(path.replace(".csv", ".parquet"))
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("command", choices=["export", "version"])
parser.add_argument("path", nargs="?")
args = parser.parse_args()
if args.command == "export":
export(args.path)
else:
print("1.4.0") # answers instantly, never touches pandasProfiling and Making Python Fast covers measuring the rest of startup.
importlib and plugins
Sometimes the module to import is only known at run time: a format name from a config file, a list of enabled plugins, a job type from a queue message. importlib.import_module("package.name") imports a module from a string and returns it, using the same cache and lookup as import. This replaces long if/elif chains with a naming convention.
Press Run (⌘ Enter) to see what happens.Never pass unvalidated user input to import_module: it executes whatever module the string names. Check the name against an allow-list first.
For plugins that live in other installed packages, Python's standard mechanism is entry points. A plugin package declares, in its pyproject.toml, that it provides an object under a named group. Your application asks importlib.metadata for everything in that group, without knowing in advance which packages are installed. This is how pytest finds its plugins and how [project.scripts] turns a function into a command.
[project.entry-points."shop.exporters"]
pdf = "shop_pdf.exporter:export"from importlib.metadata import entry_points
def available_exporters() -> dict:
return {ep.name: ep for ep in entry_points(group="shop.exporters")}
def load(name: str):
return available_exporters()[name].load() # imports shop_pdf.exporter, returns exportCalling .load() only when a plugin is actually used keeps startup fast, the same idea as lazy imports. Packaging and Publishing a Library explains how entry points get into the installed metadata.
Resolve a relative import
Write resolve(name, current_module) that works out which absolute module a (possibly relative) import refers to, the way Python does.
current_moduleis the full dotted name of the module doing the import, e.g."shop.models.order". Its package is everything before the last dot ("shop.models").- If
namehas no leading dots, it is already absolute: return it unchanged. - One leading dot means the current package, two dots its parent, and so on. Then append the rest of
name, if any. - If there are more dots than package levels (or the module is not in a package at all), return
None(Python would raise "attempted relative import beyond top-level package").
resolve(".product", "shop.models.order") # "shop.models.product"
resolve("..utils", "shop.models.order") # "shop.utils"
resolve(".", "shop.models.order") # "shop.models"
resolve("json", "shop.main") # "json"
resolve("...x", "shop.models.order") # None- module
- A single
.pyfile. Importing it runs its top-level code once and caches it insys.modules. - package
- A folder of modules, usually with an
__init__.py, addressed with dotted names. - __main__
- The
__name__of the module being run directly; used in theif __name__ == "__main__":guard. - relative import
- An import starting with dots (
from .x import y), resolved from the current package. - sys.path
- The ordered list of folders Python searches for modules; the first match wins.
- circular import
- Two modules importing each other, so one sees the other partially initialised.
- __all__
- A module-level list of public names; controls
import *and documents the API, but does not hide anything. - shadowing
- A local file with the same name as a standard-library or installed module, found first on
sys.path. - entry point
- Package metadata naming an object in a group, discovered at run time with
importlib.metadata.entry_points.