Python Packages
A Python package is a collection of Python files, or modules, that are organized into a directory hierarchy to provide specific functionality. A package allows for a structured way to manage code and enables the reuse of modules across different projects. Packages often contain multiple modules, sub-packages, and an optional __init__.py file to indicate that the directory is a package.
Create a Python Package
1. Structure of a Package
A typical package structure looks like this:
Example
my_package/ __init__.py module1.py module2.py
- __init__.py: File is an important part of Python packages. It is used to mark a directory as a Python package. It can be empty or contain initialization code for the package.
- module1.py and module2.py: These are the modules within the package.
2.Creating a package
- Create a directory named my_package.
- Add the following files.
__init__.py (optional)
print("my_package initialized")
module1.py
# my_package/module1.py def greet(name): return f"Hello, {name}!"
module2.py
# my_package/module2.py def add(a, b): return a + b
Using the Package
If you want to import the entire package and use its modules.
Example
# Importing a specific module from my_package import module1, module2 print(module1.greet("Rocky")) # Hello, Rocky! print(module2.add(6, 3)) # 9 # Importing specific functions from my_package.module1 import greet from my_package.module2 import add print(greet("Babu")) # Hello, Babu! print(add(9, 4)) # 13
Sub Packages
A sub-package is a package within another package. For example:
Example
my_package/ __init__.py module1.py sub_package/ __init__.py module3.py
Usage
from my_package.sub_package import module3
Installing Packages
Python provides a package manager called pip to install packages from the bundle of software to be installed
Package Installing Method
pip install package_name
Examples of Packages
pip install matplotlib pip install pandas pip install numpy pip install scikit-learn pip install scipy
Advantages of Python Packages
- Modularity: Organize related functionality in separate files.
- Reusability: Easily reuse modules and sub-packages in other projects.
- Maintainability: Easier to update and debug code in smaller, logical components.
- Namespace Management: Prevents name conflicts between modules with the same name in different packages.