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.
In Python, the terms .py file and module are often used interchangeably, but they are not exactly the same. Here's a detailed breakdown:
.py
extension containing Python code.python filename.py
..py
file that is intended to be imported and used in another Python program.math
, random
, and os
.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 |
# 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!
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.
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.
sys
, math
).pyc
or shared libraries like .so
(Unix) or .pyd
(Windows)__init__.py
fileSo, saying "import a .py file" would be too narrow and incorrect.
The term “module” comes from modular programming, which promotes breaking a program into logical, manageable, and reusable components. Using “module” reflects this design philosophy.
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 |
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.
import math
print(math.sqrt(16)) # Output: 4.0
print(math.pi) # Output: 3.141592653589793
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!
from math import sqrt, pi
print(sqrt(9)) # Output: 3.0
print(pi) # Output: 3.141592653589793
import math as m
print(m.pow(2, 3)) # Output: 8.0