Modules
A module is a Python file containing definitions of functions, classes, and variables. Modules let you organize code into separate, reusable files.
With modules, you can separate code by its purpose — for example, one module for math operations, one module for database connections, and another module for string utilities. Each module can be imported and used in other files without copying the code. This keeps large projects structured and manageable.
Python has a very rich standard library — dozens of built-in modules such as math, os, json, csv, random, and datetime. You can also create your own modules, even package them into a package (a collection of modules in a folder) to share with other users through PyPI. The if __name__ == "__main__" condition allows a file to serve a dual purpose: as an imported module and as a program that runs directly.
Code Example
# Ways to import a module
import math
from math import sqrt, pi
import datetime as dt
print(math.sqrt(25)) # 5.0
print(sqrt(16)) # 4.0
print(pi) # 3.141592653589793
# Creating a module: save as mymath.py
# --- mymath.py ---
def square(x):
return x ** 2
if __name__ == "__main__":
print("Module run directly")
# --- another file ---
from mymath import square
print(square(7)) # 49
Code Explanation
- Importing a module:
import mathimports the entire module, so its functions are called withmath.sqrt().from math import sqrt, piimports only thesqrtfunction and thepiconstant — they can be called directly without themath.prefix. - Alias:
import datetime as dtgives the aliasdtso it is shorter to write. - Creating a module: The
mymath.pyfile just needs to be placed in the same folder as the file that imports it. - if __name__ == "__main__": This block is only executed when the file is run directly (
python mymath.py), not when it is imported from another module. - Selective import:
from mymath import squareimports thesquarefunction to be used directly.
Everyday Example
A developer builds a student grade processing application. He separates the code into several modules to keep it tidy and easy to maintain.
# --- calculate.py ---
def average(score_list):
return sum(score_list) / len(score_list)
def highest_score(score_list):
return max(score_list)
# --- main.py ---
from calculate import average, highest_score
student_scores = [80, 90, 75, 88, 92]
print(f"Average: {average(student_scores)}")
print(f"Highest: {highest_score(student_scores)}")
Summary
Modules are how Python organizes code into reusable units. The standard library provides many ready-to-use modules, and you can create your own modules for your projects. Use modules to keep code structured, easy to maintain, and easy to share.