Modules in Python

A module is a file containing Python code (functions, classes, variables) that you can reuse in other Python programs using the import statement. This helps you organize code logically and encourages reusability.

Module vs .py File

In Python, the terms .py file and module are often used interchangeably, but they are not exactly the same. Here's a detailed breakdown:

What is a .py File?

What is a Module?

Summary Table

Aspect .py File Module
Definition Any file ending with .py A .py file imported into another Python file
Purpose May act as a standalone script Provides reusable functionality
Usage python script.py import script
Common Content Executable code, utilities, main function Functions, classes, constants

Example

# my_utils.py
def greet(name):
    return f"Hello, {name}!"

You can run this file directly, or import it like this:

import my_utils

print(my_utils.greet("John"))  # Output: Hello, John!

Why Is It Called a "Module"?

Python uses the term module instead of just saying “import a .py file” because the concept of a module is broader and more meaningful in programming.

1. Conceptual Clarity

A module represents a reusable, independent unit of code. It's a building block that encapsulates functionality — such as functions, classes, or constants — which can be used in multiple programs. The term highlights what the code does, not just where it lives.

2. Not Just .py Files

So, saying "import a .py file" would be too narrow and incorrect.

3. Based on Modular Programming Principles

The term “module” comes from modular programming, which promotes breaking a program into logical, manageable, and reusable components. Using “module” reflects this design philosophy.

Comparison Table

Term Meaning Why Not Used
.py file A file containing Python code Describes file type, not purpose or behavior
Script A file intended to be executed directly Not focused on reusability or importing
Library Collection of modules or functionality Too broad; refers to collections rather than a single unit
Module ✅ A reusable unit of code that can be imported Best represents both concept and purpose

Analogy

Think of a .py file as a document, while a module is like a chapter in a textbook — it has a specific topic, can be referenced by other chapters, and contributes to the larger structure.

Why Use Modules?

Using Built-in Modules

import math

print(math.sqrt(16))  # Output: 4.0
print(math.pi)        # Output: 3.141592653589793

Creating and Using Your Own Module

Suppose you create a file named my_utils.py:

# my_utils.py
def greet(name):
    return f"Hello, {name}!"

Then use it in another Python file:

import my_utils

print(my_utils.greet("John"))  # Output: Hello, John!

Importing Specific Functions

from math import sqrt, pi

print(sqrt(9))  # Output: 3.0
print(pi)       # Output: 3.141592653589793

Renaming Modules (Alias)

import math as m

print(m.pow(2, 3))  # Output: 8.0