Python Packages
Python packages are a way to organize and structure code by
grouping related modules into directories. A package is
essentially a folder that contains an __init__.py file and one or
more Python files (modules).
Key Components of a Python Package
Module: A single Python file containing reusable code (e.g.,
math.py).
Package: A directory containing modules and a special
__init__.py file.
Sub-Packages: Packages nested within other packages for
deeper organization.
How to create and access packages in python
1. Create a Directory: Make a directory for your package.
This will serve as the root folder.
2. Add Modules: Add Python files (modules) to the directory,
each representing specific functionality.
3. Include __init__.py: Add an __init__.py file (can be empty)
to the directory to mark it as a package.
4. Add Sub packages (Optional): Create subdirectories with
their own __init__.py files for sub packages.
5. Import Modules: Use dot notation to import, e.g., from
mypackage.module1 import greet.
Example :
In this example, we are creating a Math Operation Package to
organize Python code into a structured package with two sub-
packages: basic (for addition and subtraction) and advanced
(for multiplication and division). Each operation is
implemented in separate modules, allowing for modular,
reusable and maintainable code.
math_operations/__init__.py:
This __init__.py file initializes the main package by importing
and exposing the calculate function and operations (add,
subtract, multiply, divide) from the respective sub-packages for
easier access.
# Initialize the main package
from .calculate import calculate
from .basic import add, subtract
from .advanced import multiply, divide
math_operations/calculator.py:
This calculate file is a simple placeholder that prints
“Performing calculation…”, serving as a basic demonstration or
utility within the package.
def calculate():
print("Performing calculation...")
math_operations/basic/__init__.py:
This __init__.py file initializes the basic sub-package by
importing and exposing the add and subtract functions from
their respective modules (add.py and sub.py). This makes these
functions accessible when the basic sub-package is imported.
# Export functions from the basic sub-package
from .add import add
from .sub import subtract
math_operations/basic/add.py:
def add(a, b):
return a + b
math_operations/basic/sub.py:
def subtract(a, b):
return a - b
In the same way we can create the sub package advanced with
multiply and divide modules.
from math_operations import calculate, add, subtract
# Using the placeholder calculate function
calculate()
# Perform basic operations
print("Addition:", add(5, 3))
print("Subtraction:", subtract(10, 4))
Output:
6
8