What Are Python Modules and Packages? See Examples

In Python, modules and packages help you organize code logically.

  • Module: A single Python file (.py) containing functions, classes, or variables
  • Package: A collection of modules inside a directory with an __init__.py file

Using modules and packages allows you to reuse code, structure large projects, and avoid naming conflicts.


Why Modules and Packages Are Important

  • Promote code reuse and modularity
  • Improve maintainability of large projects
  • Allow separation of concerns
  • Enable sharing and distribution of code

Example:

# math_utils.py (module)
def add(a, b):
    return a + b

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

# main.py
import math_utils
print(math_utils.add(5, 3))  # Output: 8

Creating a Python Package

A package is a directory containing multiple modules and an __init__.py file.

my_package/
    __init__.py
    math_utils.py
    string_utils.py

Example: Using a Package

from my_package.math_utils import add
from my_package.string_utils import capitalize_words

print(add(10, 5))
print(capitalize_words("hello python"))

Example 1: Real-World Scenario – Organizing Project Code

Suppose you are building a web application:

web_app/
    __init__.py
    routes.py      # Handles HTTP routes
    models.py      # Database models
    utils.py       # Utility functions
  • Each module focuses on a single responsibility
  • Makes the project maintainable and scalable

Example 2: Installing and Using External Modules

Python has a rich ecosystem of external modules via pip.

# Install requests module
# pip install requests

import requests

response = requests.get("https://api.github.com")
print(response.status_code)

Example 3: Namespaces and Avoiding Conflicts

# Module math_utils.py
def add(a, b):
    return a + b

# Module custom_math.py
def add(a, b):
    return a + b + 1  # custom logic

import math_utils
import custom_math

print(math_utils.add(2, 3))   # 5
print(custom_math.add(2, 3))  # 6
  • Modules help prevent name conflicts and provide clear namespaces

Best Practices

✔ Organize related code in modules and packages
✔ Keep module names descriptive and lowercase
✔ Avoid circular imports
✔ Use __all__ in packages to control exported modules


Conclusion

Python modules and packages are essential for writing reusable, organized, and scalable code. They help manage complexity in large projects and promote clean, maintainable software development practices.


References

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *