Python Modules
Modules
As programs grow, keeping all the code in one file quickly becomes unmanageable. A module solves this by letting you split code into separate files and reuse it wherever it is needed.
What Is a Module?
A module is a file that groups related Python code together. Think of it as a reusable toolbox: it can contain functions, variables, and classes, and any program can import it to use those tools.
In practice, any Python file with a .py extension is a module. The module's name is the file name without .py — the file utils.py is the module utils.
Why Use Modules?
- Organization — related code lives together (for example, all date helpers in one file).
- Reusability — write a function once and use it in many programs.
- Maintainability — fixing a bug in one module fixes it everywhere it is used.
- Namespaces — each module has its own names, so
utils.welcomeandemail.welcomedo not clash.
Creating Your Own Module
To create a module, write Python code in a file and save it with a .py extension.
Example: Create a File Named utils.py
# utils.py
def welcome(user):
return f"Welcome to the system, {user}!"
Using a Module With import
Use the import statement to load a module into another Python file. For simple imports, the module file should be in the same folder as the file that imports it.
# main.py
import utils
message = utils.welcome("Aarav")
print(message)
Run main.py:
python main.py
Expected output:
Welcome to the system, Aarav!
When you use a member of an imported module, always use the format:
module_name.member_name
The prefix utils. tells Python exactly where welcome comes from.
What Happens When You Import a Module
- Python searches for
utils.py— first in the script's folder, then in the standard library and installed packages. - It runs the module's code once, creating its functions and variables.
- It stores the module in memory, so importing it again elsewhere does not re-run it.
Variables Inside a Module
Modules can also store variables — such as lists, dictionaries, and constants — in addition to functions.
Example: Updated utils.py
# utils.py
def welcome(user):
return f"Welcome to the system, {user}!"
config = {
"app": "BlogApp",
"version": "1.0",
"debug": True
}
Accessing Module Variables
import utils
print(utils.config["version"])
Expected output:
1.0
Storing settings in one module means every part of a program reads the same values.
Naming Modules
- Use a meaningful name that describes the module's contents.
- The file must end with
.py. - Follow variable naming rules: use lowercase letters, numbers, and underscores (for example,
string_helpers.py). Hyphens and spaces are not allowed, becauseimport my-utilsis invalid syntax. - Do not use Python keywords as names.
- Do not reuse the name of a standard-library module. Naming your own file
math.py,random.py, orjson.pycan hide the real module and cause confusing errors such asAttributeError: module 'random' has no attribute 'randint'.
Using an Alias With as
If a module name is long or conflicts with another name, rename it during import with as:
import utils as u
print(u.config["app"])
Expected output:
BlogApp
Aliases are common for popular libraries — for example, import numpy as np and import pandas as pd.
Built-in Modules (The Standard Library)
Python ships with a large standard library of ready-made modules for common tasks. They are installed with Python, so you can import them without downloading anything.
| Module | Purpose |
|---|---|
math | Mathematical functions |
random | Random numbers and choices |
datetime | Dates and times |
os | Interacting with the operating system |
json | Reading and writing JSON data |
re | Regular expressions |
Example: Using the datetime Module
import datetime
current_time = datetime.datetime.now()
print(current_time)
Example output (your date and time will differ):
2026-10-01 14:35:12.481937
datetime.datetime.now() means: inside the datetime module, use the datetime class, and call its now() method.
Exploring a Module With dir()
The built-in dir() function lists the names defined inside a module.
import math
print(dir(math))
Example output (shortened):
['__doc__', '__loader__', '__name__', ..., 'ceil', 'cos', 'e', 'factorial', 'floor', 'pi', 'sqrt', ...]
dir() works for both built-in modules and your own modules. Names surrounded by double underscores are special attributes that Python creates automatically.
Importing Specific Members With from
If you need only certain parts of a module, import them directly with from.
Example Module
# utils.py
def calculate_total(a, b):
return a + b
site = {
"name": "GoCourse",
"category": "Education"
}
Import Only What You Need
from utils import site
print(site["name"])
Expected output:
GoCourse
With from module import name, you use the name directly, without the module prefix — site, not utils.site.
You can import several names at once:
from utils import site, calculate_total
print(calculate_total(40, 60))
Expected output:
100
import vs from ... import
| Style | Usage | Advantage |
|---|---|---|
import utils | utils.site | Clear where each name comes from; avoids name clashes |
from utils import site | site | Shorter code when you use a name often |
Avoid
from module import *. It imports every public name from a module, which makes it unclear where names come from and can silently overwrite your own variables.
Running a Module Directly: if __name__ == "__main__":
Every module has a special variable called __name__:
- When a file is run directly (
python utils.py), its__name__is"__main__". - When a file is imported, its
__name__is the module name ("utils").
This lets a module include test or demo code that runs only when the file is executed directly — not when it is imported.
# utils.py
def welcome(user):
return f"Welcome to the system, {user}!"
if __name__ == "__main__":
print(welcome("Tester"))
- Running
python utils.pyprintsWelcome to the system, Tester!. - Running
import utilsfrom another file prints nothing; it only makeswelcome()available.
Third-Party Modules
Beyond the standard library, thousands of modules and packages are published by the Python community on the Python Package Index (PyPI). Install them with pip:
pip install requests
After installation, import them like any other module:
import requests
A folder of related modules is called a package. Frameworks such as Django and Flask are packages.
Common Mistakes
| Mistake | Problem |
|---|---|
ModuleNotFoundError: No module named 'utils' | The file is not in the same folder, or the name is misspelled |
Naming your file after a standard module (random.py) | Your file hides the real module |
Using a name without the module prefix after import utils | NameError; write utils.welcome() |
Using from module import * | Unclear origins of names and possible overwrites |
Including .py in the import (import utils.py) | ModuleNotFoundError; use import utils |
Related Concepts
- Python Functions — the main contents of most modules
- Python Datetime, Python Math, and Python JSON — commonly used standard-library modules
- Python Classes and Objects — classes are also often shared through modules