DEV Community

Tu codigo cotidiano
Tu codigo cotidiano

Posted on

How to Organize Python Code with Modules and Packages — A Practical Beginner Guide

A Python program can work perfectly and still become difficult to maintain.

That usually happens when one file slowly starts doing everything:

program.py

├── register expenses
├── save CSV files
├── calculate totals
├── generate reports
└── run the program

Nothing is necessarily broken.

The problem is that finding and changing one responsibility starts requiring you to understand several unrelated parts of the file.

The first useful question

When a Python project grows, don't start by asking:

How many lines should a file have?

A better question is:

Which responsibilities belong together, and which ones should be able to change separately?

For example, an expense tracker could evolve from one large file into:

expense_tracker/
├── main.py
└── finance/
├── init.py
├── expenses.py
├── files.py
└── reports.py

Now the structure itself tells us something:

expenses.py handles expense logic.

files.py handles persistence.

reports.py handles calculations and summaries.

main.py coordinates the program.

That is the real value of modules and packages: they help the code communicate its structure.

A tiny example

Instead of keeping every function in main.py, we can create a module:

file: finance/expenses.py

def add_expense(expenses, date, category, amount):
expenses.append({
"date": date,
"category": category,
"amount": amount
})

Then use it from another file:

file: main.py

from finance.expenses import add_expense

expenses = []

add_expense(
expenses,
"2026-09-02",
"Food",
18000
)

The behavior is simple, but the important change is architectural:

the responsibility now has a clear home.

The mistake to avoid

Learning modules doesn't mean creating one file for every function.

This:

calculator/
├── add.py
├── subtract.py
├── multiply.py
└── divide.py

is not automatically better than:

calculator.py

More files do not always mean better organization.

The goal is not fragmentation.

The goal is clarity.

Want the full visual walkthrough?

I wrote a complete step-by-step guide in Spanish on TuCódigoCotidiano.

It covers:

modules and packages;

import;

init.py;

if name == "main";

absolute and relative imports;

circular imports;

pycache;

when to split code — and when not to.

👉 Read the complete guide:

https://tucodigocotidiano.yarumaltech.com/leer_guias/modulos-y-paquetes-organiza-tu-codigo-sin-perderte/

If you're moving from small Python scripts to projects with multiple files, this is exactly the transition the guide is designed to explain.

Top comments (0)