Python - Packages
What are Python Packages?
A package in Python is a way of structuring Python’s module namespace by using “dotted module names”. It is essentially a directory that contains a special __init__.py file and can contain multiple modules and sub-packages.
Why Use Packages?
- Organize related modules together
- Encourages modular design
- Improves code readability and maintainability
- Enables scalable application structures
Structure of a Package
my_package/
├── __init__.py
├── module1.py
└── module2.py Creating a Package
Simply create a folder and add an __init__.py file inside it. This file can be empty or execute initialization code.
Using a Package
# my_package/module1.py
def add(a, b):
return a + b # main.py
from my_package import module1
print(module1.add(2, 3)) Importing from Packages
You can import specific modules or functions from a package:
import my_package.module1from my_package import module1from my_package.module1 import add
Sub-packages
Packages can contain sub-packages, which are just directories with their own __init__.py file.
Installing External Packages
Python provides a package manager called pip to install external packages from PyPI.
pip install requests Using an Installed Package
import requests
response = requests.get("https://example.com")
print(response.status_code) Best Practices
- Use meaningful names for packages
- Keep your
__init__.pyclean and minimal - Structure large apps using nested packages
Conclusion
Python packages are a fundamental tool for organizing code in larger projects. Whether you're creating your own or using third-party packages, understanding how they work enables cleaner, more scalable development.