What is a Module?
A module is a file containing Python code (functions, classes, variables). Modules help organize code, avoid repetition, and make programs easier to maintain. You can import modules to use their code in other files.
Creating a Module
Any Python file can be a module. Create a file called math_utils.py:
# math_utils.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
PI = 3.14159
Importing Modules
Import Entire Module
import math_utils
result = math_utils.add(5, 3)
print(result) # 8
Import Specific Items
from math_utils import add, multiply
result = add(5, 3)
product = multiply(4, 2)
Import with Alias
import math_utils as mu
result = mu.add(5, 3)
# Or for specific functions
from math_utils import add as addition
Import All (Not Recommended)
from math_utils import *
# Can use functions directly
result = add(5, 3)
# But pollutes namespace - avoid this!
Built-in Modules
Python comes with many built-in modules:
# Math module
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
# Random module
import random
number = random.randint(1, 10)
choice = random.choice(['a', 'b', 'c'])
# Datetime module
from datetime import datetime, date
now = datetime.now()
today = date.today()
# OS module
import os
current_dir = os.getcwd()
files = os.listdir('.')
Module Search Path
Python searches for modules in these locations:
import sys
print(sys.path) # List of directories Python searches
# Current directory
# PYTHONPATH environment variable
# Standard library directories
# Site-packages (installed packages)
The __name__ Variable
Use __name__ to detect if module is run directly:
# my_module.py
def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
# Code here only runs when file is executed directly
print("This module was run directly")
print(greet("World"))
else:
# Code here runs when module is imported
print("This module was imported")
Module Attributes
Access module information:
import math
# Module name
print(math.__name__) # "math"
# Module file location
print(math.__file__) # Path to math module
# Module documentation
print(math.__doc__) # Module docstring
# List all attributes
print(dir(math)) # All functions/variables in math
Reloading Modules
Reload a module after changes (useful in interactive sessions):
import importlib
import my_module
# Make changes to my_module.py, then:
importlib.reload(my_module)
Common Built-in Modules
math: Mathematical functionsrandom: Random number generationdatetime: Date and time operationsos: Operating system interfacesys: System-specific parametersjson: JSON data handlingcsv: CSV file operationsre: Regular expressionscollections: Specialized data structuresitertools: Iterator functions
Best Practices
- Use specific imports:
from module import functionwhen possible - Avoid import *: Pollutes namespace and makes code unclear
- Organize imports: Standard library, third-party, local imports
- Use aliases: For long module names or to avoid conflicts
- Document modules: Add docstrings at the top of module files
Common Mistakes
- Circular imports: Module A imports B, B imports A
- Name conflicts: Imported names shadow local variables
- Missing __init__.py: Required for packages (directories of modules)
Next Steps
Learn about packages to organize multiple modules, or explore Python's standard library for built-in modules.