Lesson 29 of 30
In progress
Project structure: modules and imports
Split a growing script into modules, import without side effects, and lay out a project another person can navigate.
One file of 600 lines is not a project; it is a file you are afraid to edit. Splitting code into modules is mostly about giving each part a name and a clear boundary, not about ceremony.
What you will learn
- Split code into modules and import it without surprises.
- Use the
__main__guard so imports do not run a program. - Lay out a small project that another person can navigate.
A module is just a file
Any .py file can be imported. Its definitions become attributes of the module object.
# money.py
def to_paise(rupees):
return int(round(rupees * 100))
def format_paise(paise):
return f"{paise / 100:.2f}"
# app.py
import money
print(money.to_paise(12.5))
print(money.format_paise(1250))
import money looks for money.py in the same folder, then in the installed packages, then in the standard library. The module name is the filename without .py. Keeping the module name in front of the function (money.to_paise) tells the reader where it came from, which matters once there are five modules.
from money import to_paise is shorter and fine when the name is distinctive. Avoid from money import *: it hides the origin of every name and can overwrite your own.
Imports run the file
Importing executes the module’s top-level code once. That is why a module full of print calls and immediate work is unpleasant to import.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
if __name__ == "__main__":
main()
print("module name:", __name__)
Press Run to see the output.
When run directly, __name__ is "__main__" and main() runs. When imported, __name__ is the module name and the guard is skipped. Put definitions at the top, the guard at the bottom, and no work in between.
A layout that scales
A small project needs fewer folders than the internet suggests. This is enough for most work:
tasker/
tasker/
__init__.py
cli.py
storage.py
models.py
tests/
test_storage.py
README.md
pyproject.toml
The inner folder is the package; __init__.py marks it as importable and can stay empty. cli.py handles arguments, storage.py reads and writes files, models.py holds classes and pure functions. Tests import the package, not the script, which is why the __main__ guard matters.
Flat is fine at the start: three modules in one folder beat a package hierarchy you cannot explain. Add structure when a file passes a few hundred lines or when two concerns keep changing for different reasons.
Imports between your own modules
Inside a package, use absolute imports: from tasker.storage import load_tasks. Relative imports (from .storage import load_tasks) work too and are common inside libraries, but absolute paths are easier to read in application code.
Circular imports happen when two modules import each other. The symptom is an ImportError about a partially initialised module. The fix is usually to move the shared piece into a third module that both can import, or to import inside the function that needs it. Restructuring is better than the local-import trick; the cycle is telling you the boundary is wrong.
A module named after a standard library module, such as json.py or random.py, shadows the real one and produces baffling errors. Name files after what they do: storage.py, not json.py.
Environments, briefly
Install project dependencies into a virtual environment so they do not leak into the system Python.
python3 -m venv .venv
source .venv/bin/activate # Windows: .venvScriptsactivate
python -m pip install -r requirements.txt
Record dependencies in requirements.txt or pyproject.toml. This track uses only the standard library, so you can skip this step until you add a package. When you do, commit the dependency file and never commit .venv.
Running python app.py from the parent folder when app.py expects to be run from its own folder makes relative file paths fail. Anchor data paths to the script instead of the working directory: Path(__file__).parent / "data" / "tasks.json". That expression is the same wherever the command is started.
Take this single-file program and split its responsibilities into three functions: load, summarise and render. Then add a main() with the __main__ guard so importing the file does nothing visible.
rows = ["ana,88", "ravi,72", "mei,95"]
scores = [int(row.split(",")[1]) for row in rows]
print(f"{len(scores)} scores, average {sum(scores) / len(scores):.1f}")
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def summarise(scores):
return len(scores), sum(scores) / len(scores)
def render(count, average):
return f"{count} scores, average {average:.1f}"
def main():
rows = ["ana,88", "ravi,72", "mei,95"]
count, average = summarise(load(rows))
print(render(count, average))
if __name__ == "__main__":
main()
Press Run to see the output.
Each function now has one job and can be tested alone: load on a list of strings, summarise on numbers, render on a count and an average. The guard means an import would define them without printing.
Recap
- A module is a
.pyfile; importing runs its top-level code once. - The
__main__guard separates definitions from script behaviour. - Absolute imports, descriptive filenames and a small package beat a deep hierarchy.
Next, you will build the capstone: a task manager that stores its data in JSON and survives between runs.
Do I need __init__.py?
Should every function live in its own file?
Progress is saved in this browser only. No account, no email.