Modules

Learn about Python modules, what they are, why we use them, and how to create your own modules.

Ali Berro

By Ali Berro

6 min read Section 1
From: Python Fundamentals: From Zero to Hero

Modules

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py added. Modules allow you to organize your code into logical, reusable units.

What is a Module?

A module is simply a Python file that contains:

  • Functions
  • Classes
  • Variables
  • Executable code

When you import a module, Python executes the module’s code and makes its contents available for use.

Why Use Modules?

Modules provide several benefits:

  1. Code Organization: Break large programs into manageable pieces
  2. Reusability: Write code once and use it in multiple programs
  3. Namespace Management: Avoid naming conflicts by organizing code into separate namespaces
  4. Maintainability: Easier to maintain and update code when it’s organized into modules

Creating a Module

To create a module, simply create a Python file with a .py extension:

math_utils.py
# math_utils.py - A simple module
def add(a, b):
"""Add two numbers."""
return a + b
def multiply(a, b):
"""Multiply two numbers."""
return a * b
def power(base, exponent):
"""Raise base to the power of exponent."""
return base ** exponent
PI = 3.14159
E = 2.71828

This file (math_utils.py) is now a module that can be imported into other Python programs.

Built-in Modules

Python comes with a large standard library of built-in modules. Some commonly used ones include:

  • math - Mathematical functions
  • random - Random number generation
  • datetime - Date and time operations
  • os - Operating system interface
  • sys - System-specific parameters
  • json - JSON encoder and decoder
  • re - Regular expressions
  • collections - Specialized container datatypes

Using Built-in Modules

using-builtin-modules.py
import math
import random
import datetime
# Using math module
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.factorial(5)) # 120
# Using random module
print(random.randint(1, 10)) # Random integer between 1 and 10
print(random.choice(['a', 'b', 'c'])) # Random choice from list
# Using datetime module
now = datetime.datetime.now()
print(now) # Current date and time

Module Search Path

When you import a module, Python searches for it in the following order:

  1. Current directory - The directory containing the script
  2. PYTHONPATH - Directories listed in the PYTHONPATH environment variable
  3. Standard library - Built-in modules
  4. Site-packages - Third-party packages installation directory

You can view the search path using sys.path:

module-search-path.py
import sys
for path in sys.path:
print(path)

Module Attributes

Every module has special attributes that provide information about it:

module-attributes.py
import math
print(math.__name__) # 'math' - Module name
print(math.__file__) # Path to module file
print(dir(math)) # List of names in module

__name__ Attribute

The __name__ attribute is particularly useful. When a module is run directly, __name__ is set to '__main__'. When imported, it’s set to the module’s name.

name-attribute.py
# my_module.py
def greet():
print("Hello from my_module!")
if __name__ == '__main__':
print("Running as main program")
greet()
else:
print("Imported as a module")

This allows you to write code that behaves differently when run directly vs. when imported.

Module Documentation

You can document your module using a docstring at the top of the file:

documented-module.py
"""
Math Utilities Module
This module provides basic mathematical operations
including addition, multiplication, and power functions.
"""
def add(a, b):
"""Add two numbers."""
return a + b
def multiply(a, b):
"""Multiply two numbers."""
return a * b

Organizing Code in Modules

Example: Calculator Module

calculator.py
"""
Calculator Module
Provides basic arithmetic operations.
"""
def add(a, b):
"""Add two numbers."""
return a + b
def subtract(a, b):
"""Subtract b from a."""
return a - b
def multiply(a, b):
"""Multiply two numbers."""
return a * b
def divide(a, b):
"""Divide a by b."""
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def power(a, b):
"""Raise a to the power of b."""
return a ** b

Module Execution

When Python imports a module, it executes all the code in the module file. This means:

  • Function and class definitions are executed
  • Module-level code runs immediately
  • Variables are initialized
execution-example.py
# example_module.py
print("Module is being imported!")
def my_function():
print("Function called")
# This runs when module is imported
my_variable = "Initialized"
# This also runs
print(f"Variable value: {my_variable}")

When you import this module, you’ll see the print statements execute.

Reloading Modules

By default, Python imports a module only once. If you modify a module, you need to reload it. Use importlib.reload():

reload-module.py
import importlib
import my_module
# Modify my_module.py, then reload
importlib.reload(my_module)

Note

In most cases, you should restart your Python interpreter instead of reloading modules. Reloading is mainly useful during development.

Best Practices

  1. Use descriptive names: Module names should be clear and descriptive
  2. Keep modules focused: Each module should have a single, well-defined purpose
  3. Document your modules: Include docstrings explaining what the module does
  4. Avoid circular imports: Don’t create modules that import each other
  5. Use if __name__ == '__main__': For code that should only run when executed directly

Exercises

Exercise 1: Using Built-in Modules

Import the math module and use it to calculate the square root of 16, the value of pi, and the factorial of 5. Print each result on a separate line.

Using Built-in Modules

Checks: 0 times
Answer:
import math
print(math.sqrt(16))
print(math.pi)
print(math.factorial(5))

Exercise 2: Using random Module

Import the random module and generate 5 random integers between 1 and 100 (inclusive). Print each number on a separate line.

Using random Module

Checks: 0 times
Answer:
import random
for i in range(5):
print(random.randint(1, 100))

Exercise 3: Module Attributes

Import the math module and print its __name__ attribute. Then use dir() to get all names in the module and print the first 5 names.

Module Attributes

Checks: 0 times
Answer:
import math
print(math.__name__)
names = dir(math)
print(names[:5])

Course Progress

Section 56 of 61

Back to Course