Spex3
    

__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