UNIT 5: Modules & Packages
Module 5: Modules and Packages
📖 Module Overview
In Python, modules and packages are fundamental concepts for organizing and
structuring code, promoting reusability and maintainability.
This module presents the fundamental concepts in creating, declaring and organizing
modules and packages in Python Programming.
Modules and packages are Python's primary tools for organizing code into reusable units.
A module is a single file, while a package is a collection of modules within a directory. Both are
used to create modular, maintainable, and scalable applications.
Modules and packages are fundamental to organizing code in Python. They allow
developers to break down large, complex projects into smaller, more manageable files, fostering
code reuse and preventing namespace conflicts. This system scales from small personal scripts to
vast application frameworks.
A deeper understanding involves advanced concepts such as virtual environments,
absolute vs. relative imports, and namespace packages.
🎯 Learning Outcomes
At the end of the lesson, the students are expected to:
1. Create your own module.
2. Use Module in another file via the import statement.
3. Organize several modules into packages.
UNIT 5: Modules & Packages
📚 Core Content
Modules and packages are Python's primary tools for organizing code into reusable units.
A module is a single file, while a package is a collection of modules within a directory. Both are
used to create modular, maintainable, and scalable applications.
Before we can start importing modules and their components, we
have to make sure that the mypackages folder can be found by
the Python interpreter. One good way to ensure that that is always
the case is by adding it to the PYTHONPATH environment variable.
UNIT 5: Modules & Packages
Modules
A Python module is a single file (.py extension) that contains Python code, which can include:
Functions
Classes
Variables
Runnable code
Key features
UNIT 5: Modules & Packages
Encapsulation: A module defines a logical boundary, encapsulating related functions and data
to prevent naming conflicts with other parts of your code.
Namespace: Each module has its own private namespace. To access a module's contents, you
import the module and use the dot ( . ) operator, such as module_name.function_name() .
Reusability: Code written in a module can be reused across different scripts and programs by
simply importing the file.
How to use modules
1. Create a module: Save your code in a file, for example, my_module.py .
python
# my_module.pydef greet(name):
return f"Hello, {name}!"
class MyClass:
def __init__(self, value):
[Link] = value
2. Import the module: In another file, use the import statement.
# my_module.pydef greet(name):
return f"Hello, {name}!"
class MyClass:
def __init__(self, value):
[Link] = value
3. Use from ... import : You can also import specific components directly into
your namespace
python
# [Link]
from my_module import greet
UNIT 5: Modules & Packages
message = greet("Python")
print(message) # Output: Hello, Python!
Modules: The building blocks
A Python module is a single .py file containing code like functions, classes, and
variables. When you import a module, you load its code into your current script, creating a
distinct namespace that keeps its contents separate from your code's main scope.
Built-in Modules
Python includes a comprehensive "standard library" of built-in
modules that provide powerful functionality without needing a separate
installation.
Import the entire module:
python
import math
print([Link](25)) # Access content using `module_name.item_name`
Import specific items:
python
from math import pi, sqrt
print(pi) # No need for the `math.` prefix
UNIT 5: Modules & Packages
Standard library
These modules come with every Python installation and are always available
for import. The first answer provided a good overview of these,
including os , sys , math , and datetime . You don't need to install them
using pip .
Example
Import and use the platform module:
import platform
x = [Link]()
print(x)
UNIT 5: Modules & Packages
Here are some of the most commonly used built-in modules, grouped by
function:
Core programming and system utilities
sys : Interacts with the Python interpreter, providing access to system-
specific parameters and functions, such as command-line arguments and
interpreter version.
os : Provides an interface for interacting with the operating system, allowing
you to perform tasks like file and directory manipulation, and accessing
environment variables.
collections : Contains specialized container datatypes
like OrderedDict and defaultdict that offer alternatives to Python's general-
purpose containers.
itertools : Offers functions for creating and manipulating iterators for efficient
looping.
UNIT 5: Modules & Packages
shutil : Provides a higher-level interface for file operations, such as copying
and moving files and directories.
json : Encodes and decodes data using the JSON format, which is common for
web applications.
pickle : Implements Python object serialization and deserialization, allowing
you to save and load Python objects to files.
Mathematics
math : Provides access to standard mathematical functions and constants for
floating-point numbers, including trigonometric functions, logarithms, and pi.
random : Generates pseudo-random numbers and provides functions for
selecting random items from sequences.
statistics : Provides mathematical statistics functions for numerical data.
decimal : Offers fixed-point and floating-point arithmetic with user-definable
precision, providing more accuracy than standard float objects.
Dates, time, and calendaring
datetime : Offers classes for manipulating dates and times in both simple and
complex ways.
time : Provides functions for working with time, including the ability to pause
script execution.
calendar : Contains functions for working with calendar-related tasks
UNIT 5: Modules & Packages
******************************************************************************
***********
Third-party libraries
Third-party libraries must be installed separately from the Python Package
Index (PyPI) using a package manager like pip . They are created and
contributed by the global Python developer community and cover a vast
range of functionalities, from web development to machine learning.
Here are some popular third-party Python libraries, grouped by category:
Web development
Django: A high-level web framework that encourages rapid development
and clean, pragmatic design.
Flask: A lightweight web framework that keeps the core simple but
extensible.
Requests: A powerful and elegant HTTP library for making web requests.
Data science and machine learning
NumPy: A fundamental package for numerical computing, especially for
working with multi-dimensional arrays.
Pandas: A library for data manipulation and analysis, offering powerful data
structures like DataFrames.
Matplotlib: A comprehensive 2D plotting library for creating static,
animated, and interactive visualizations.
Scikit-learn: A machine learning library for predictive data analysis.
TensorFlow: An open-source library for high-performance numerical
computation, especially deep learning.
Automation and scripting
Scrapy: A fast, high-level web-crawling and screen-scraping framework.
UNIT 5: Modules & Packages
Pillow: An image processing library that adds image manipulation
capabilities.
Fabric: A command-line tool for streamlining the use of SSH for application
deployment or system administration.
Graphical user interfaces (GUI)
PyQt/PySide: Cross-platform GUI toolkits that are Python bindings for the Qt
application framework.
Tkinter: The standard GUI toolkit for Python. Although part of the standard
library, it is often discussed alongside other GUI libraries.
Create a custom module: Any .py file with Python code can be a module.
For example, a file [Link] with def say_hello(): ... can be imported into
another script simply by using import greetings .
The __name__ variable: A special variable, __name__ , helps a module detect
if it is being run directly or being imported. When executed as a
script, __name__ is set to '__main__' . This allows you to include code that only
runs when the file is executed directly.
python
# [Link]
def say_hello():
print("Hello from the greetings module!")
if __name__ == '__main__':
say_hello()
Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py
Re-naming a Module
UNIT 5: Modules & Packages
You can create an alias when you import a module, by using the as keyword:
Example
Create an alias for mymodule called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)
***********************************************************
*********Creating a Python module in Visual Studio Code is
straightforward, as a module is simply a Python file ( .py ). The key steps
involve organizing your project, creating files, and managing dependencies
using a virtual environment.
Here is a step-by-step guide:
Step 1: Set up a project folder
First, create a dedicated folder for your project and open it in VS Code.
1. On your computer, create a new folder named my_project .
2. Open VS Code.
3. Go to File > Open Folder and select the my_project folder.
UNIT 5: Modules & Packages
Step 2: Create a virtual environment (recommended)
Using a virtual environment is a best practice to isolate your project's
dependencies.
1. Open the Command Palette by pressing Ctrl+Shift+P (Windows/Linux)
or Cmd+Shift+P (macOS).
2. Type Python: Create Environment and select the command.
3. Choose Venv from the options. VS Code will then create a .venv folder in your
project directory and activate it.
UNIT 5: Modules & Packages
Step 3: Create your first module
Your first module can be a simple Python file.
1. In the VS Code File Explorer, click the "New File" icon next to your project
folder name.
2. Name the file my_module.py and press Enter .
3. Add some code to your new module. For example, a function:
UNIT 5: Modules & Packages
Activity(Modules)
Create a simple product list (key-value) with 5 items and
there should be a category (if tools, all products will be tools).
Example
Product 1 - Product code = 001
Product name = Coffee Mug
Product color = yellow
Product availability = True
Make sure that you use the import to display item details.
Use input for retrieving product details. Also consider to
display messages if choices will be out of the scope, like
“Invalid Product” or “No such product from the list”.
ACTIVITY on MODULE/LAB EXERCISES:
1. Group your selves into 3 to 4 members only.
a) Identify your members and role
i. Owner of the device/computer/laptop
ii. Member/s - programmer, in-charge on
documentation, preparation of
report/presentation
2. Prepare or set-up your computer, your VS Code.
Install as necessary if you don’t have it. Capture the
preparation or setting up via video.
UNIT 5: Modules & Packages
3. Perform the creation of your first module activity
above.
******************************************************************************
************