Lesson 40 of 70 – Python Packages
57%

Python Packages

A package in Python is a way of organizing related modules into a directory structure. Packages help developers organize large Python applications into smaller and manageable parts.

Note: A module is generally a single .py file, while a package is a directory that can contain multiple related modules and subpackages.
What is a Python Package?

A Python package is a directory containing related Python modules. It provides a structured way to organize code.

For example:

school/
    students.py
    teachers.py
    courses.py

Here, school can be used as a package containing related modules.

Why Use Packages?
  • Packages organize large projects.
  • They group related modules together.
  • They make code easier to maintain.
  • They improve code reusability.
  • They help avoid naming conflicts.
  • They allow applications to be divided into logical components.
Package Structure

A simple Python project can have the following structure:

myproject/
│
├── main.py
│
└── calculator/
    ├── __init__.py
    ├── addition.py
    └── subtraction.py

The calculator directory contains related modules.

The __init__.py File

Traditionally, a file named __init__.py is placed inside a package directory.

calculator/
    __init__.py
    addition.py
    subtraction.py

It can contain package initialization code or be empty. Modern Python also supports namespace packages that do not require __init__.py, but regular packages commonly use it.

Creating a Package

Suppose we create a package called calculator.

calculator/
    __init__.py
    operations.py

Inside operations.py:

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

def multiply(a, b):
    return a * b

The calculator directory can now organize these calculator-related functions.

Importing a Module from a Package

We can import a module from a package using dot notation.

from calculator import operations

print(operations.add(10, 20))
print(operations.multiply(5, 4))
Output:
30
20
Importing Specific Functions

We can import specific functions from a module inside a package.

from calculator.operations import add

print(add(15, 25))
Output:
40
Import Multiple Functions
from calculator.operations import add, multiply

print(add(5, 10))
print(multiply(5, 10))
Output:
15
50
Using a Package Alias

A module imported from a package can be given an alias using the as keyword.

import calculator.operations as op

print(op.add(10, 5))
Output:
15
Multiple Modules in a Package

A package can contain many modules.

school/
    __init__.py
    students.py
    teachers.py
    courses.py
    exams.py

Each module can handle a different part of the school application.

Example: Student Package

Project structure:

student/
    __init__.py
    profile.py
    marks.py

profile.py

def show_profile():
    print("Student Profile")

marks.py

def show_marks():
    print("Student Marks")
Using the Student Package

We can import the modules from the student package.

from student.profile import show_profile
from student.marks import show_marks

show_profile()
show_marks()
Output:
Student Profile
Student Marks
Nested Packages

A package can contain another package. Such a structure is useful for large applications.

company/
    __init__.py
    employees/
        __init__.py
        staff.py
    accounts/
        __init__.py
        salary.py

Here, employees and accounts are subpackages inside the company package.

Importing from a Subpackage

We can import modules from nested packages using dot notation.

from company.employees import staff

Or import a specific function:

from company.accounts.salary import calculate_salary

The exact import depends on how the package and modules are organized.

Standard Library Packages

Python's standard library contains many modules and packages that can be imported without separately installing them.

Examples include:

  • os
  • json
  • datetime
  • urllib
  • email
  • xml
Third-Party Packages

Third-party packages are created and distributed by developers and organizations outside Python's standard library.

Examples include:

  • NumPy
  • Pandas
  • Requests
  • Flask
  • Django

Many third-party packages can be installed using PIP.

Package and PIP

PIP is a package installer for Python. It is commonly used to install packages from the Python Package Index and other package sources.

For example:

pip install requests

After installation, the package can be imported in a Python program.

import requests
Package Installation Example

For example, the requests package can be installed with:

pip install requests

Then it can be used in Python:

import requests

response = requests.get("https://example.com")

print(response.status_code)

The package provides functionality for making HTTP requests.

Package Namespace

Packages provide a namespace for their modules. This helps organize names and reduces the chance of conflicts between unrelated modules.

For example:

school.students
company.students

Both can have a module named students, while their full names identify their different package locations.

Package Structure Example
myproject/
│
├── main.py
│
├── users/
│   ├── __init__.py
│   ├── login.py
│   └── profile.py
│
└── products/
    ├── __init__.py
    ├── product.py
    └── price.py

This structure separates user-related code from product-related code.

Package Initialization

The __init__.py file can contain initialization code for a regular package.

For example:

print("Calculator package loaded")

When the package is imported in a context that executes this initializer, the statement can run.

Note: Keep package initialization simple. Avoid unnecessary work when a package is imported.
Package Best Practices
  • Group related modules together.
  • Use meaningful package names.
  • Keep modules focused on related functionality.
  • Avoid unnecessary circular imports.
  • Keep package initialization lightweight.
  • Use clear import statements.
  • Document important packages and modules.
Module vs Package
Module Package
Usually a single Python file. A directory structure for organizing modules.
Usually has a .py extension. Can contain multiple modules and subpackages.
Contains reusable code. Organizes related reusable code.
Example: calculator.py Example: calculator/
Package Example in a Real Project

A web application can be organized into packages such as:

mywebsite/
│
├── main.py
│
├── users/
│   ├── login.py
│   └── profile.py
│
├── products/
│   ├── product.py
│   └── category.py
│
└── database/
    ├── connection.py
    └── queries.py

This makes the project easier to understand and maintain as it grows.

Key Points
  • A package organizes related Python modules.
  • A module is generally a single Python file.
  • Packages can contain multiple modules.
  • Packages can also contain subpackages.
  • __init__.py is commonly used in regular packages.
  • Modules can be imported using package and module names.
  • PIP can be used to install many third-party packages.
  • Packages help organize large Python applications.
  • Meaningful package structures make projects easier to maintain.

🧠 Quick Quiz

Question: What is the main purpose of a Python package?