Modules, packages & imports
Split a project into modules and import between them without circular imports.
By Invicly Tech, , in Python Programming from Zero. About 11 minutes to read.
In short
A module is any .py file; a package is a folder of modules. Importing lets you split a program into focused files and reuse the huge standard library without copying code.
Explained simply
As a program grows, one long file becomes hard to read. Modules let you split it into smaller files, each with one job. Any .py file is a module. If you have storage.py, another file can write import storage and use the functions inside it.
Python also ships with hundreds of ready-made modules called the standard library: math for maths, random for random numbers, datetime for dates, json for JSON, pathlib for files. You do not install them; you just import them.
A package is a folder of modules. Putting related modules in one folder, like tracker/models.py and tracker/storage.py, keeps a bigger project tidy. You then import with dots: from tracker.storage import save.
Every file can be both a script you run and a module you import. The if __name__ == "__main__": check tells them apart. Code under it runs only when you run the file directly, not when another file imports it, so importing never starts the program by accident.
Press Play on a diagram to walk through it one step at a time.
- main.py
- Entry point with __main__ guard
- tracker/ (package)
- __init__.py
- models.py
- storage.py
- report.py
- tests/
- test_storage.py
- Step 1Check sys.modules
Already imported? Reuse it, do not rerun
- Step 2Find the file
Search the script folder, stdlib, site-packages
- Step 3Run it once
Top-level code executes, creating functions
- Step 4Bind the name
Your file can now use storage.save()
- 1cli.py
Imports services; nothing imports cli
- 2services.py
Business rules; imports models and storage
- 3storage.py
Reads and writes files; imports models
- 4models.py
Dataclasses only; imports no project code
- 5Standard library
json, pathlib, dataclasses
In depth
Where Python looks when you import
import name searches the folders listed in sys.path, in order, and uses the first match. The first entry is the folder of the script you ran (or the current directory when you use python -m or the interactive prompt). Then come any folders in the PYTHONPATH environment variable, then the standard library, then site-packages, where pip installs third-party packages.
Because your script's folder comes first, a file of yours named random.py or json.py hides the real standard module. Then import random loads your file, and you get confusing errors like AttributeError: module 'random' has no attribute 'randint'. Rename the file and delete any __pycache__ folder next to it.
To see exactly where a module came from, print module.__file__. To see the search list, print sys.path. Python also caches compiled bytecode in __pycache__/*.pyc files so later imports start faster; you can safely delete them and should not commit them.
- 1sys.modules cache
Already imported? Reuse it
- 2Script's folder
Your own files win, even json.py
- 3PYTHONPATH
Extra folders, if the variable is set
- 4Standard library
math, json, pathlib, datetime
- 5site-packages
Packages installed with pip
- 6Not found
ModuleNotFoundError
The import forms and when to use each
import math keeps the module name, so code reads math.sqrt(2); it is clear where sqrt came from. from math import sqrt copies just that name into your file, which is shorter for names you use often. import numpy as np and from datetime import datetime as dt give shorter or clearer aliases.
Avoid from module import * in real code: it dumps every public name into your file, can silently overwrite your own names, and makes it hard to see where anything comes from. A module can limit what * exports by defining __all__ = ["save", "load"].
PEP 8, the Python style guide, says to put imports at the top of the file, grouped as standard library, then third-party, then your own modules, with a blank line between groups. Tools like Ruff can sort them automatically.
- One import per line for modules: import os, then import sys
- Absolute imports (from tracker.storage import save) are the clearest
- A name starting with _ signals private: do not import it from outside
Packages, __init__.py and relative imports
A folder with an __init__.py file is a regular package. When you import the package, Python runs its __init__.py once; it can be empty, or it can re-export the main names so users can write from tracker import Expense instead of from tracker.models import Expense. Keep it light, because heavy work there slows every import.
Since Python 3.3, folders without __init__.py also work as namespace packages, but for your own projects include __init__.py so the intent is clear and tools behave predictably.
Inside a package, modules can use relative imports: from . import storage (same package) or from .models import Expense. Relative imports only work in modules that are part of a package. If you run such a file directly with python tracker/cli.py, you get ImportError: attempted relative import with no known parent package. Run it as a module instead, from the project root: python -m tracker.cli.
- Runs the file as a plain script
- sys.path starts at tracker/
- Relative imports fail
- Fine for single-file scripts
- Runs it as part of the package
- sys.path starts at the current folder
- Relative and package imports work
- Use from the project root
Circular imports and how to untangle them
A circular import happens when a.py imports b.py and b.py imports a.py. Python starts running a.py, reaches import b, pauses a halfway, and runs b. When b asks for something from a that has not been defined yet, you get an error like: ImportError: cannot import name 'save' from partially initialized module 'a' (most likely due to a circular import).
It is a design smell: two modules depend on each other. The best fix is to move the shared code into a third module that both import, for example models.py that both storage.py and report.py use. Another fix is to import the module rather than names (import a, then use a.save() inside a function), because the name is looked up later, after both files have finished loading. As a last resort, move the import inside the function that needs it.
A healthy project has dependencies that flow one way: cli uses services, services use models and storage, and models import nothing of yours.
What __name__ really is
Every module has a built-in variable __name__. When the module is imported, __name__ is its import name, such as "tracker.storage". When the file is run directly, Python sets __name__ to "__main__" instead. The guard if __name__ == "__main__": simply checks which case you are in.
The usual pattern is to put all real work in a main() function and call it only under the guard. Then tests and other modules can import your functions without the program starting, asking for input or writing files. It also avoids a subtle problem: multiprocessing on Windows and macOS starts new processes that import your main file, and without the guard they would start the whole program again.
A package can be runnable too: add a __main__.py file inside it, and python -m tracker runs that file.
- Imported: __name__ is the module path, like "tracker.storage"
- Run directly: __name__ is "__main__"
- python -m tracker runs tracker/__main__.py
Learn it in 4 short steps
About 30m each. Track them with a timer in your plan.
- 1Import from the standard library~30m
- 2Split code into your own modules~30m
- 3Create a package with __init__.py~30m
- 4Use the if __name__ == '__main__' guard~30m
Key points
- import math then math.sqrt(); or from math import sqrt.
- A module's top-level code runs once, the first time it is imported.
- if __name__ == "__main__": runs code only when the file is executed directly.
- Circular imports happen when two modules import each other; move shared code out.
Key terms
Tap a card to flip it. 0/5 known
Examples
# tracker/storage.py
import json
from pathlib import Path
def save(items, path=Path("items.json")):
path.write_text(json.dumps(items), encoding="utf-8")
# main.py
from tracker.storage import save
def main():
save(["milk", "eggs"])
print("saved")
if __name__ == "__main__":
main()Splitting one file into a package
You have a 300-line expenses.py. Step 1: create a folder expenses/ with an empty __init__.py. Step 2: move the dataclass to models.py, file reading and writing to storage.py, and the totals logic to report.py. Step 3: each module imports only what it needs, always downwards (report and storage import models). Step 4: create expenses/__main__.py with the main() function and the guard. Step 5: run it from the project folder with python -m expenses.
# expenses/report.py
from collections import defaultdict
from .models import Expense
def totals_by_category(items: list[Expense]) -> dict[str, float]:
out: dict[str, float] = defaultdict(float)
for e in items:
out[e.category] += e.amount
return dict(out)
# expenses/__main__.py
from .storage import load
from .report import totals_by_category
if __name__ == "__main__":
print(totals_by_category(load()))Fixing "module has no attribute" caused by a file name
You write a script called random.py to practise, and it crashes with AttributeError: module 'random' has no attribute 'choice'. Step 1: print random.__file__ to see which file was imported; it is your own random.py. Step 2: understand why: the script's folder comes first in sys.path. Step 3: rename your file to dice.py. Step 4: delete __pycache__ in that folder so the old compiled copy is gone. Step 5: run again; now the standard module loads.
# dice.py (renamed from random.py)
import random
print(random.__file__) # now a path inside the standard library
print(random.choice(["rock", "paper", "scissors"]))Quick reference
- print(module.__file__) shows which file was actually imported
- Never name your files after standard modules: random.py, json.py, email.py
- Group imports: standard library, third-party, your own; one blank line between
- from . import x works only inside a package; run it with python -m package.module
- A module's top-level code runs once; later imports reuse sys.modules
- Fix circular imports by moving shared code into a third module
- Add __main__.py to a package so python -m package runs it
Common mistakes
- Naming your file random.py or json.py, which shadows the standard module.
- Putting work at module top level, so it runs on every import.
- Using from module import * and losing track of where names come from.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Create greet.py with a function hello(name) and a __main__ guard that calls it with "world". Import it from another file and check the guard code does not run.
- Exercise 2medium
Build a package shapes/ with circle.py (area(r)) and square.py (area(s)). In shapes/__init__.py re-export both as circle_area and square_area, then use them from main.py.
- Exercise 3hard
models.py imports format_money from report.py, and report.py imports Expense from models.py, causing a circular import. Restructure so it works and dependencies flow one way.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Do I still need __init__.py in Python 3?
- Python can import folders without it (namespace packages), but you should include it in your own packages. It makes the package explicit and avoids surprises with tools and tests.
- What is the difference between a module and a package?
- A module is a single .py file. A package is a folder that groups modules, and it can contain sub-packages.
- Why does my module's code only run once even if I import it many times?
- After the first import, Python stores the module in sys.modules and later imports reuse it. Use importlib.reload(module) if you really need to re-run it, for example in an interactive session.
- What is ModuleNotFoundError: No module named 'requests'?
- Python cannot find the package on sys.path, usually because it is not installed in the environment you are running. Activate the right virtual environment and run python -m pip install requests.