Skip to content

Lesson 43 of 52Real projects

Modules and Packages

Split code into modules and packages, import it correctly, and debug ModuleNotFoundError and circular imports.

20 min read0/7 questions

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.)

Python
import sys, os, importlibfrom pathlib import Path Path("greetings.py").write_text('''DEFAULT = "Hello" def greet(name, greeting=DEFAULT): return f"{greeting}, {name}!" print("greetings module is being imported")''') sys.path.insert(0, os.getcwd()) # make sure this folder is searchedimportlib.invalidate_caches() import greetings # runs the file once, top to bottomimport greetings # cached: nothing printed the second timeprint(greetings.greet("Ada"))print(type(greetings).__name__, greetings.__name__)
Output
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

StatementWhat you getUse it when
import jsonthe name json bound to the modulethe default: json.loads(...) reads clearly
import numpy as npthe module under a shorter aliascommunity conventions (np, pd)
from math import sqrt, pijust those namesyou use a few names a lot
from os import path as pone name under an aliasavoiding a clash
from module import *every public namealmost never: it hides where names come from
Python
import mathfrom math import sqrt as rootfrom collections import Counter, defaultdict print(math.pi, root(16))print(Counter("banana").most_common(1))
Output
Press Run (⌘ Enter) to see what happens.
Quick check
Two different modules in your app both do import config. How many times does config.py's top-level code run?
Need a nudge? A hint rules out a wrong answer.

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:

report.py
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__.

Predict the outputPython

What does this print?

import json
print(__name__)
print(json.__name__)
Need a nudge? Hints walk you through it.

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.)

A small application package
  • 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.

Quick check
Inside shop/services/pricing.py, which import gets Order from shop/models/order.py?
Need a nudge? A hint rules out a wrong answer.

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 package

Relative 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.

Python
import os, runpy, sys, importlibfrom pathlib import Path Path("shop").mkdir(exist_ok=True)Path("shop/__init__.py").write_text("")Path("shop/prices.py").write_text("VAT = 0.2\n")Path("shop/main.py").write_text('''from .prices import VATprint(f" __name__={__name__!r} __package__={__package__!r} VAT={VAT}")''')sys.path.insert(0, os.getcwd())importlib.invalidate_caches() print("like `python shop/main.py`:")try: runpy.run_path("shop/main.py", run_name="__main__")except ImportError as e: print(" ImportError:", e) print("like `python -m shop.main`:")runpy.run_module("shop.main", run_name="__main__")
Output
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.

Quick check
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?
Need a nudge? A hint rules out a wrong answer.

__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.

Python
import os, sys, importlibfrom pathlib import Path Path("textutils.py").write_text('''__all__ = ["slugify"] import re # an import is a name in the module too def slugify(text): return _clean(text).replace(" ", "-") def shout(text): # public by name, but not in __all__ return text.upper() def _clean(text): # underscore: private by convention return re.sub(r"[^a-z0-9 ]", "", text.lower()).strip()''')sys.path.insert(0, os.getcwd())importlib.invalidate_caches() from textutils import *print(slugify("Hello, World!"))print("slugify" in dir(), "shout" in dir(), "_clean" in dir(), "re" in dir()) import textutilsprint(textutils.shout("still reachable"))
Output
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.

Predict the outputPython

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())
Need a nudge? Hints walk you through it.

How Python finds a module

When you write import x, Python goes through these steps:

Put it in order5 steps

Put the import lookup steps in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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).

Python
import sysfor p in sys.path[:4]: print(repr(p))print("json" in sys.modules, "math" in sys.builtin_module_names)
Output
Press Run (⌘ Enter) to see what happens.

Two classic causes of ModuleNotFoundError:

  1. Running from the wrong place. python shop/main.py puts shop/ on sys.path, not the project root, so import shop.models fails. Run python -m shop.main from the project root instead.
  2. 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.

Python
import os, sys, importlibfrom pathlib import Path # Your project folder accidentally contains a file named like a stdlib modulePath("project").mkdir(exist_ok=True)Path("project/statistics.py").write_text('print(" running ./project/statistics.py, not the standard library!")\n') sys.modules.pop("statistics", None) # pretend it was never importedsys.path.insert(0, os.path.abspath("project")) # what `python project/app.py` doesimportlib.invalidate_caches() import statisticsprint("loaded from:", Path(statistics.__file__).relative_to(Path.cwd()))print("has mean?", hasattr(statistics, "mean")) sys.path.pop(0)sys.modules.pop("statistics")import statisticsprint("after fixing sys.path:", statistics.mean([1, 2, 3]))
Output
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.

Quick check
Your script tools/report.py does import email and crashes with AttributeError: module 'email' has no attribute 'message_from_string'. What do you check first?
Need a nudge? A hint rules out a wrong answer.

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.

A circular import
models.pyservices.pymain.py

currentwaitingdone

main.py runs import models.

1/4

The fixes, from best to worst:

  1. 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).
  2. Depend in one direction. Lower layers (models) should never import higher layers (services, routes).
  3. Import the module, not the name (import models then models.Order at 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 pandas inside the one function that needs it. The first call pays; later calls hit the sys.modules cache 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 json binds 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 inside try, and how to opt in on older versions with __lazy_modules__).
cli.py
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 pandas

Profiling 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.

Python
import importlibimport osimport sysfrom pathlib import Path Path("exporters").mkdir(exist_ok=True)Path("exporters/__init__.py").write_text("")Path("exporters/csv_export.py").write_text('''def export(rows): return "\\n".join(",".join(map(str, r)) for r in rows)''')Path("exporters/md_export.py").write_text('''def export(rows): return "\\n".join("| " + " | ".join(map(str, r)) + " |" for r in rows)''')sys.path.insert(0, os.getcwd())importlib.invalidate_caches() def load_exporter(name): """Turn a name from config into a function, without an if/elif chain.""" module = importlib.import_module(f"exporters.{name}_export") return module.export rows = [("id", "total"), (1, 9.99)]for fmt in ["csv", "md"]: # imagine this list comes from a config file print(load_exporter(fmt)(rows))try: load_exporter("pdf")except ModuleNotFoundError as e: print("unknown format:", e.name)
Output
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.

pyproject.toml of a plugin package
[project.entry-points."shop.exporters"]
pdf = "shop_pdf.exporter:export"
shop/plugins.py
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 export

Calling .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.

ChallengeMedium

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_module is 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 name has 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
Python
def resolve(name: str, current_module: str) -> str | None: # Count the leading dots, then walk up from the current package. pass
Key terms
module
A single .py file. Importing it runs its top-level code once and caches it in sys.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 the if __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.