Spex3
    

Python Packages: Creating & Importing 📦🐍


    

    

A package in Python is a way to organize multiple related modules into a directory structure. Packages help maintain modularity and reusability in large projects.

1️⃣ What is a Package?
🔹 A module is a single .py file containing Python code.
🔹 A package is a directory containing multiple modules and an __init__.py file.
🔹 Packages help group related modules together, just like folders organize files.

2️⃣ Creating a Python Package

✅ Step 1: Create a Package Directory
Let's create a package named mypackage. The directory structure:


mypackage/
│── __init__.py # Makes it a package
│── module1.py # First module
│── module2.py # Second module

✅ Step 2: Add Code to the Modules

📌 mypackage/module1.py

def greet(name):
return f"Hello, {name}!"
📌 mypackage/module2.py

def add(a, b):
return a + b

✅ Step 3: Add __init__.py (Package Identifier)
📌 The __init__.py file tells Python that this is a package.

📌 mypackage/__init__.py

from .module1 import greet
from .module2 import add

print("mypackage is initialized")
🔹 This allows importing greet and add directly from mypackage.

3️⃣ Importing a Package

✅ Importing the Entire Package

import mypackage

print(mypackage.greet("Alice")) # ✅ Hello, Alice!
print(mypackage.add(5, 3)) # ✅ 8
🔹 The __init__.py file makes functions available directly under mypackage.

✅ Importing Specific Modules

from mypackage import module1, module2

print(module1.greet("Bob")) # ✅ Hello, Bob!
print(module2.add(10, 2)) # ✅ 12
✅ Importing Specific Functions

from mypackage.module1 import greet
from mypackage.module2 import add

print(greet("Charlie")) # ✅ Hello, Charlie!
print(add(7, 8)) # ✅ 15

4️⃣ Installing and Using Custom Packages

✅ Installing a Package Locally (pip install .)
If you want to distribute your package, create a setup.py file:

📌 setup.py

from setuptools import setup

setup(
name="mypackage",
version="1.0",
packages=["mypackage"],
)
Then, install it using:


pip install .

✅ Now, you can import it just like any installed package:


import mypackage

5️⃣ Summary

Concept Description
Module A single .py file containing functions/classes.
Package A folder containing multiple modules and __init__.py.
Import Entire Package import mypackage
Import a Module from mypackage import module1
Import a Function from mypackage.module1 import greet


    Date: 2025-03-24 00:00:00.000000