Comprehensive Guide to Python Modules and Usage
Comprehensive Guide to Python Modules and Usage
Key points:
Modules exist to help programmers organize their code logically and avoid
code duplication. Instead of rewriting the same functions or classes across
multiple programs, you place them into a module once and reuse them by
importing the module wherever needed.
From the perspective of the file system, a module is just a .py file. However,
there are some structural conventions to keep in mind:
# math_utils.py
PI = 3.14159
def circle_area(radius):
return PI * radius * radius
class Calculator:
def multiply(self, a, b):
return a * b
These practices make your code easier to understand and integrate well with
the Python ecosystem.
Python comes bundled with a rich collection of modules called the standard
library. These modules provide functionalities like file I/O, system calls, text
processing, mathematics, internet protocols, and more — all without needing
separate installation.
Because these modules come pre-installed, you can rely on their availability in
any standard Python environment.
Once installed, they can be imported and used just like standard modules.
For example:
my_project/
│
├── data_utils/
│ ├── __init__.py
│ ├── file_reader.py
│ └── file_writer.py
│
└── main.py
Aspect Explanation
What is a module? A .py file containing Python code (functions, classes, etc.)
Naming convention Lowercase letters with underscores, avoid keywords and clashes
Third-party modules External modules installed via package managers like pip
Module vs package Module = single file; package = folder with multiple modules
By mastering modules, you lay a solid foundation for writing clean, modular,
and scalable Python applications. Modules are the building blocks that make
programming in Python efficient and enjoyable.
The math module offers a rich set of mathematical functions and constants
that extend Python’s built-in operators. It's useful when you need precise
mathematical computations beyond simple arithmetic.
Commonly used functions and constants:
Example usage:
import math
radius = 5
area = math.pi * math.pow(radius, 2)
print(f"Area of a circle with radius {radius}: {area}")
angle_degrees = 45
angle_radians = math.radians(angle_degrees) # Convert
degrees to radians
sin_val = math.sin(angle_radians)
print(f"Sine of {angle_degrees} degrees: {sin_val}")
This example calculates the area of a circle and the sine of a 45-degree angle
by importing the entire math module.
The sys module provides access to variables and functions that interact
closely with the Python interpreter. It is particularly helpful for managing
command-line arguments, exiting a program, and inspecting Python runtime
environment details.
Key features:
Example usage:
import sys
if len(sys.argv) > 1:
print("Script arguments:", sys.argv[1:])
else:
print("No command-line arguments were passed.")
THE OS MODULE
Example usage:
import os
This example obtains the current folder, lists its content, creates a new
directory if it doesn't exist, and prints an important environment variable.
Common functionalities:
import random
sampled_numbers = random.sample(numbers, 3)
print("Random sample of 3 numbers:", sampled_numbers)
This shows various ways to generate random numbers, shuffle lists, and
select random elements.
It’s important to know the different ways to import these modules depending
on your coding style and requirements:
import math
print(math.sqrt(16))
Example
Module Purpose Key Features
Import
getcwd() , listdir() ,
os OS-level functionality import os
environment vars
import module_name
This imports the entire module and requires qualification of all functions or
objects by using the module’s name as a prefix.
Example:
import math
print(math.sqrt(9)) # Output: 3.0
Pros:
Example:
Pros:
Caution: Avoid importing too many symbols directly into the namespace, as
this can cause name clashes.
This form imports all public names from a module into the current
namespace:
When you import a module, Python searches for the module file in a specific
order. The places Python looks include:
Example:
import sys
print(sys.path)
If you want to add your own directory for module searching at runtime, you
can append it explicitly:
import sys
sys.path.append('/path/to/my/modules')
import my_custom_module
Example:
import my_module
from importlib import reload
def main():
print("Module executed directly")
if __name__ == "__main__":
main()
• Docstrings: Include a module-level docstring at the top describing the
module’s purpose and usage.
Example:
# greetings.py
def hello(name):
"""Return a greeting."""
return f"Hello, {name}!"
def goodbye(name):
"""Return a farewell."""
return f"Goodbye, {name}!"
You can then import and use your module in another script:
import greetings
Organizing modules:
from math
Import specific Frequent use of a few
import pi, Direct access, e.g., pi
objects items
sqrt