
Creating Custom Modules and Multi-File Projects
Every script you have written so far lived in a single .py file. That works fine when a program is 50 or 100 lines long. Once an app grows to several hundred lines, scrolling up and down one giant file becomes slow and frustrating.
Professional Python developers split growing apps into custom modules and packages. In this lesson, you will learn how to organize code across multiple files, finally demystify the if __name__ == "__main__": guard you saw in earlier lessons, understand absolute vs. relative imports, and refactor a single-file task app into a clean multi-file package.
1. Splitting Code Across Multiple Files
Any .py file you write is already a Python module. Suppose you create a helper file named greetings.py in your project folder:
# greetings.py
def welcome(name: str) -> str:
"""Return a friendly greeting message."""
return f"Welcome back, {name}!"
In a second file named app.py in the same folder, you can import and call welcome() just like a standard library function:
# app.py
from greetings import welcome
print(welcome("Rey"))
Each file now has one clear job. If you ever need to update the greeting logic, you know the exact file to open.
2. Understanding the if __name__ == ā__main__ā: Guard
When Python imports a module, it runs every top-level line inside that file. If greetings.py had a bare print(welcome("Test")) at the bottom, that test line would accidentally print every time another file imported greetings.
To prevent that, Python sets a special built-in variable called __name__ inside every file:
- When you run a file directly (
python greetings.py), Python sets__name__to"__main__". - When another file imports it (
import greetings), Python sets__name__to the moduleās name ("greetings").
# greetings.py
def welcome(name: str) -> str:
"""Return a friendly greeting message."""
return f"Welcome back, {name}!"
if __name__ == "__main__":
# Runs ONLY when you execute: python greetings.py
print(welcome("Local Test"))
That is why we placed if __name__ == "__main__": at the bottom of our projects in Lessons 9 through 14. It lets a file work both as a runnable program and as a safely importable module.
3. Packages, __init__.py, and Absolute vs. Relative Imports
When you have several related modules, group them inside a folder called a package and add a file named __init__.py inside that folder. The __init__.py file tells Python that the folder is a package and lets you expose clean shortcuts for users of your package.
task_manager_project/
main.py
task_toolkit/
__init__.py
storage.py
formatter.py
Inside this structure, there are two ways to import modules:
- Absolute import: Starts from the project root folder, such as
from task_toolkit.storage import load_tasks. This is clear and recommended for most code. - Relative import: Uses a leading dot (
.) inside a package to refer to a sibling file, such asfrom .storage import load_tasksinsidetask_toolkit/__init__.py.
4. Practical Project: Modular Task Manager Package
Letās refactor a single-file task manager into the 4-file package shown above. Create a folder named task_manager_project, and inside it create a subfolder named task_toolkit.
First, create task_toolkit/storage.py to handle saving and loading JSON safely (including missing, empty, or corrupted files):
# task_toolkit/storage.py
import json
from pathlib import Path
def load_tasks(file_path: Path) -> list[str]:
"""Load saved tasks from a JSON file, returning an empty list if missing."""
if not file_path.exists():
return []
try:
text = file_path.read_text(encoding="utf-8").strip()
if not text:
return []
data = json.loads(text)
return data if isinstance(data, list) else []
except json.JSONDecodeError:
print("Warning: tasks.json is corrupted. Starting with an empty list.")
return []
def save_tasks(file_path: Path, tasks: list[str]) -> None:
"""Save the task list to a formatted JSON file."""
file_path.write_text(json.dumps(tasks, indent=4), encoding="utf-8")
Next, create task_toolkit/formatter.py to keep display logic separate from file storage:
# task_toolkit/formatter.py
def format_tasks(tasks: list[str]) -> str:
"""Format a list of tasks into a numbered string."""
if not tasks:
return "No tasks yet."
lines = [f"{index}. {task}" for index, task in enumerate(tasks, start=1)]
return "\n".join(lines)
Now create task_toolkit/__init__.py using relative imports to expose the packageās public functions in one place:
# task_toolkit/__init__.py
from .formatter import format_tasks
from .storage import load_tasks, save_tasks
Finally, create main.py in the outer task_manager_project/ folder. Notice how clean and readable it becomes when storage and formatting live in their own modules:
# main.py
from pathlib import Path
from task_toolkit import format_tasks, load_tasks, save_tasks
TASKS_FILE = Path("tasks.json")
def main() -> None:
"""Run the modular Task Manager CLI."""
tasks = load_tasks(TASKS_FILE)
print("=== Modular Task Manager ===")
while True:
print("\n1. View Tasks 2. Add Task 3. Remove Task 4. Exit")
choice = input("Choose an option (1-4): ").strip()
if choice == "1":
print("\n" + format_tasks(tasks))
elif choice == "2":
new_task = input("Enter a new task: ").strip()
if not new_task:
print("Task cannot be empty.")
continue
tasks.append(new_task)
save_tasks(TASKS_FILE, tasks)
print("Task added.")
elif choice == "3":
if not tasks:
print("No tasks to remove.")
continue
print("\n" + format_tasks(tasks))
try:
num = int(input("Enter task number to remove: "))
if 1 <= num <= len(tasks):
removed = tasks.pop(num - 1)
save_tasks(TASKS_FILE, tasks)
print(f"Removed: {removed}")
else:
print("Invalid task number.")
except ValueError:
print("Please enter a whole number.")
elif choice == "4":
print("Goodbye!")
break
else:
print("Invalid choice. Please enter 1, 2, 3, or 4.")
if __name__ == "__main__":
main()
Open your terminal inside task_manager_project/ (not inside task_toolkit/) and run python main.py. Everything works together cleanly, and each module is easy to test or reuse in future projects.
Common Beginner Mistakes
- Running
python storage.pyfrom inside the package folder when using relative imports: Relative imports (from .formatter import ...) only work when imported as part of a package. Always run your entry script (main.py) from the project root folder. - Creating circular imports: If
file_a.pyimportsfile_b.pyandfile_b.pyalso importsfile_a.py, Python raises anImportError. Keep dependencies flowing in one direction (for example,main.pyimportsstorage.py, never the reverse). - Running from the wrong working directory: If you run
python task_manager_project/main.pyfrom a parent folder, relative file paths likePath("tasks.json")will be saved in that parent folder instead of inside your project. - Forgetting the
__name__ == "__main__"guard: Leaving testprint()orinput()calls at the top level of a helper module causes them to run unexpectedly whenever another script imports that module.
Try It Yourself
- Add a Stats Module (
task_toolkit/stats.py): Create a new module with acount_summary(tasks: list[str]) -> strfunction, export it in__init__.py, and display the count inmain.py. - Standalone Module Test (
task_toolkit/formatter.py): Add anif __name__ == "__main__":block at the bottom offormatter.pythat prints a sample formatted list when run directly, and verify it does not print when you runpython main.py. - Refactor an Earlier Project (
budget_app/main.py): Take your Personal Expense Tracker from Lesson 11 and split it intocsv_store.py,reports.py, andmain.py.
Frequently Asked Questions
Does __init__.py have to contain code, or can it be empty?
It can be completely empty. Adding imports inside __init__.py is optional, but it makes importing from your package shorter and cleaner.
Why did Python create a __pycache__ folder inside my project?
Python compiles imported modules into bytecode files inside __pycache__ so future runs start faster. You can safely ignore this folder and add __pycache__/ to your .gitignore.
Should I prefer absolute imports or relative imports?
Prefer absolute imports (from task_toolkit.storage import load_tasks) in most files because they are explicit and easy to read. Relative imports (from .storage import load_tasks) work well inside a packageās own __init__.py.
Why do I get ModuleNotFoundError: No module named ātask_toolkitā?
Check two things: make sure your folder spelling matches exactly, and confirm your terminal is inside the project root folder (task_manager_project) when running python main.py.
Need to set up an isolated workspace first? Check out the previous lesson: Virtual Environments and Package Management with Pip. In our next article, Working with Web APIs: Connecting Python to the Internet, you will use the requests library to fetch live data from the web and build a real-time weather dashboard.
Learning programming works best as a collaborative process, and your questions and insights help make these tutorials more effective for everyone. If you hit an ImportError, wonder how to organize your own project folders, or refactor one of your earlier apps into a package, please share your experience in the comments. Your feedback helps create a learning community where we can all benefit from each otherās discoveries and solutions.
You Might Also Like

Virtual Environments and Package Management with Pip
Learn how to create Python virtual environments with venv and manage packages using pip an...

Python Modules and Standard Library Highlights
Explore Python modules and the standard library (math, random, datetime, sys) while buildi...

Working with JSON Data: Python and Web Standards
Learn how to parse, write, and format JSON data in Python using json.load() and json.dump(...

Working with CSV Files: Tabular Data in Python
Learn to read, write, and format CSV files in Python using csv.reader, csv.DictReader, and...
Comments
Loading commentsā¦