Modules in Python: Organize Code into Reusable Files

Introduction

In this chapter, you will learn Python modules, a core concept for organizing and reusing code across files. Modules help you split large scripts into clear, maintainable components. Once you understand modules, your projects become cleaner and easier to scale.

Prerequisites

  • Python 3.10+ installed
  • Basic understanding of functions, classes, and file structure
  • Ability to run .py files in terminal or IDE

What Is a Module

A module is simply a Python file (.py) that contains reusable code, such as:

  • variables
  • functions
  • classes

Why modules matter:

  • reduce duplicated code
  • improve readability
  • make teamwork and testing easier

1) Create and Import Your First Module

Suppose you have two files:

  • math_tools.py
  • main.py

math_tools.py:

python
# Add two numbers
def add(a, b):
    return a + b
 
 
# Multiply two numbers
def multiply(a, b):
    return a * b

main.py:

python
# Import module
import math_tools
 
# Call module functions
print(math_tools.add(2, 3))
print(math_tools.multiply(4, 5))

This is the basic module workflow.

2) Different Import Styles

Full Module Import

python
import math_tools
print(math_tools.add(1, 2))

Import Specific Member

python
from math_tools import add
print(add(1, 2))

Import with Alias

python
import math_tools as mt
print(mt.multiply(3, 4))

Import Multiple Members

python
from math_tools import add, multiply
print(add(5, 6))
print(multiply(5, 6))

Tip

Best Practice

For clarity in larger projects, prefer import module_name or explicit named imports over wildcard imports.

3) __name__ == "__main__" Entry Pattern

This pattern lets one file work both as:

  • reusable module
  • directly runnable script
python
# demo_module.py
def greet(name):
    print(f"Hello, {name}")
 
 
if __name__ == "__main__":
    # Run only when this file is executed directly
    greet("Python Learner")

If imported elsewhere, the code in if __name__ == "__main__": will not run.

4) Built-in Modules

Python has many built-in modules ready to use.

Examples:

  • math for math functions
  • random for random values
  • datetime for date and time
  • os for operating-system interactions
python
import math
import random
 
print(math.sqrt(16))          # 4.0
print(random.randint(1, 10))  # random int

5) Real Mini Example: Simple Utility Module

Build a mini utility module for score processing.

score_utils.py:

python
# Return average score
def average(scores):
    return sum(scores) / len(scores)
 
 
# Return grade level
def grade(score):
    if score >= 90:
        return "A"
    if score >= 80:
        return "B"
    if score >= 70:
        return "C"
    return "D"

app.py:

python
import score_utils
 
scores = [95, 82, 76]
avg = score_utils.average(scores)
 
print(f"Average: {avg:.2f}")
print(f"Grade of first score: {score_utils.grade(scores[0])}")

This design keeps business logic reusable and test-friendly.

6) Module Search Path (Beginner Awareness)

When importing, Python searches modules in:

  • current script directory
  • standard library directories
  • environment paths (sys.path)

If module is not found, you get ModuleNotFoundError.

Warning

Do not name your files the same as standard modules (for example random.py, json.py).
It can cause import conflicts and confusing bugs.

Common Beginner Mistakes

Mistake 1: Circular Imports

Module A imports B, and B imports A, causing dependency problems.

Mistake 2: Using from module import *

Wildcard imports reduce readability and may overwrite names unexpectedly.

Mistake 3: Confusing Script Path and Working Directory

Import behavior depends on execution context and project structure.

Surprise Practice Challenge

Build a "Mini Shop Utilities" module:

  1. shop_utils.py with:
    • calc_total(price, qty)
    • calc_discount(total, rate)
    • format_currency(value)
  2. main.py imports module and runs a purchase example
  3. Use if __name__ == "__main__" in main.py
  4. Print readable final bill

If you finish this, you are writing modular code similar to real-world projects.

FAQ

What is the difference between module and package?

A module is a single .py file; a package is a directory containing multiple modules (usually with package structure).

Should every file become a module?

Not necessarily. Split code into modules when reuse and clarity improve.

Is alias import (as) good practice?

Yes, when names are long or there is a standard alias pattern.

Why does import sometimes fail even when file exists?

Usually due to path issues, naming conflicts, or incorrect project structure.