Python Packages

Note: Starting with Python 3.3, the __init__.py file is no longer strictly required to create a package. However, including it is still considered good practice to ensure compatibility and to initialize the package if needed.

A package in Python is a way of organizing related modules into a single directory hierarchy. A package contains a special __init__.py file to mark the directory as a package.

Why Use Packages?

Creating a Package

my_package/
├── __init__.py
├── module1.py
└── module2.py

✅ Correct Example 1: Importing an Entire Module from a Package

from my_package import module1
module1.function1()

✅ Correct Example 2: Importing a Specific Function from a Module

from my_package.module2 import function2
function2()

✅ Correct Example 3: Using Aliases for Modules

import my_package.module1 as m1
m1.function1()

✅ Correct Example 4: Importing from a Nested Package

from analytics.statistics import mean
mean.calculate_average()

✅ Correct Example 5: Initializing with __init__.py

# utils/__init__.py
from .tools import greet

# tools.py
def greet():
    print("Hello")

# main.py
from utils import greet
greet()

❌ Wrong Example 1: Importing a module that doesn't exist

from my_package import moduleX

Error: ImportError: cannot import name 'moduleX' from 'my_package'

❌ Wrong Example 2: Missing __init__.py in older Python versions

# Directory without __init__.py
from my_package import module1

Error (in Python < 3.3): ModuleNotFoundError: No module named 'my_package'

❌ Wrong Example 3: Importing a function without specifying the module

from my_package import function1

Error: ImportError: cannot import name 'function1'

❌ Wrong Example 4: Wrong nested package import path

from analytics.mean import average

Error: ModuleNotFoundError: No module named 'analytics.mean'

❌ Wrong Example 5: Forgetting to include the package in PYTHONPATH

from my_package import module1

Error: ModuleNotFoundError: No module named 'my_package'

Exploring a Package

import my_package
print(dir(my_package))

Packages provide structure and clarity to Python applications, especially as they scale.