What are Python modules and packages, and how are they different?

Python modules and packages are ways to organize and reuse code, but they serve different purposes. Here’s a detailed breakdown of each and how they differ:


What is a Python Module?

  • A module is a single file of Python code that contains definitions and statements such as functions, classes, and variables.
  • The file must have a .py extension.
  • Modules make it easier to organize and reuse code by importing it into other scripts.

Example of a Module:

File: math_utils.py

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

def subtract(a, b):
    return a - b

You can use this module in another script:

import math_utils

result = math_utils.add(3, 5)
print(result)  # Output: 8

What is a Python Package?

  • A package is a directory that contains multiple modules and a special __init__.py file.
  • The __init__.py file (can be empty) marks the directory as a package and allows it to be imported like a module.
  • Packages help organize related modules into a single namespace.

Structure of a Package:

math_package/
    __init__.py
    addition.py
    subtraction.py

addition.py:

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

subtraction.py:

def subtract(a, b):
    return a - b

Use the package:

from math_package.addition import add
from math_package.subtraction import subtract

print(add(3, 5))        # Output: 8
print(subtract(10, 4))  # Output: 6

Key Differences Between Modules and Packages

FeatureModulePackage
DefinitionA single Python file (.py).A directory containing multiple modules.
PurposeOrganize code into reusable files.Group related modules into a namespace.
File StructureA single .py file.A directory with an __init__.py file.
ImportImport the .py file directly.Import modules from the package.
Exampleimport my_modulefrom my_package import my_module

How They Work Together

You can combine packages and modules to structure large projects effectively. For example:

my_project/
    __init__.py
    data_processing/
        __init__.py
        clean.py
        analyze.py
    visualization/
        __init__.py
        plot.py
        export.py

Usage:

from my_project.data_processing.clean import clean_data
from my_project.visualization.plot import create_plot

Summary:

  • A module is a single .py file containing Python code.
  • A package is a collection of modules grouped into a directory with an __init__.py file.
  • Modules are ideal for smaller, independent functionalities, while packages are better for organizing related functionality across multiple files.