__init__.py Files & Using Third-Party Packages (pip) ππ¦

1οΈβ£ __init__.py Files in Python Packages
An __init__.py file is a special Python file that turns a directory into a package.
β
Why is __init__.py Important?
β Identifies a directory as a package.
β Can execute initialization code when the package is imported.
β Can expose specific modules or functions for easier access.
π Basic __init__.py File (Empty)
If you create a package without __init__.py, it wonβt be recognized as a package in Python versions before 3.3.
πΉ Minimal mypackage structure:
mypackage/
βββ __init__.py # Empty but required
βββ module1.py
βββ module2.py
π __init__.py with Initialization Code
π mypackage/__init__.py
print("mypackage is initialized")
π Output when imported:
import mypackage
# Output: mypackage is initialized
π __init__.py for Direct Imports
Instead of:
from mypackage.module1 import greet
You can expose functions directly in __init__.py:
π mypackage/__init__.py
from .module1 import greet
from .module2 import add
Now, import functions directly:
from mypackage import greet, add
print(greet("Alice")) # β
Hello, Alice!
print(add(5, 3)) # β
8
2οΈβ£ Using Third-Party Packages with pip
Python provides thousands of third-party packages via PyPI (Python Package Index).
πΉ Installing Packages with pip
πΉ Install a package globally:
pip install package_name
πΉ Install a package for a specific project (recommended):
pip install package_name --user
πΉ Common pip Commands
Command Description
pip install package_name Install a package
pip install package_name==1.2.3 Install a specific version
pip list List installed packages
pip show package_name Show package details
pip uninstall package_name Remove a package
β
Example: Installing and Using requests
Install the requests package:
pip install requests
Use it in Python:
import requests
response = requests.get("https://api.github.com")
print(response.status_code) # β
200
πΉ Installing Multiple Packages (requirements.txt)
Create a requirements.txt file:
requests==2.28.0
numpy>=1.21
pandas
Install all packages at once:
pip install -r requirements.txt
3οΈβ£ Summary
Concept Explanation
__init__.py Defines a directory as a Python package
Direct Imports in __init__.py from .module import function
pip install package Install a third-party package
requirements.txt Manage dependencies
Date: 2025-03-24 00:00:00.000000