Back to Blog
Creating Custom Modules and Multi-File Projects

Creating Custom Modules and Multi-File Projects

November 30, 2026
Reynov Christian

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 as from .storage import load_tasks inside task_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.py from 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.py imports file_b.py and file_b.py also imports file_a.py, Python raises an ImportError. Keep dependencies flowing in one direction (for example, main.py imports storage.py, never the reverse).
  • Running from the wrong working directory: If you run python task_manager_project/main.py from a parent folder, relative file paths like Path("tasks.json") will be saved in that parent folder instead of inside your project.
  • Forgetting the __name__ == "__main__" guard: Leaving test print() or input() 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 a count_summary(tasks: list[str]) -> str function, export it in __init__.py, and display the count in main.py.
  • Standalone Module Test (task_toolkit/formatter.py): Add an if __name__ == "__main__": block at the bottom of formatter.py that prints a sample formatted list when run directly, and verify it does not print when you run python main.py.
  • Refactor an Earlier Project (budget_app/main.py): Take your Personal Expense Tracker from Lesson 11 and split it into csv_store.py, reports.py, and main.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

Comments

Loading comments…

Leave a Comment

0/5000