Modules & Packages

3 min read

Write Clean, Reusable, and Scalable Code

As your Python programs grow, managing all that code in a single file becomes a nightmare. That’s where modules and packages come in. They help you organize your code into manageable, reusable chunks β€” making collaboration, debugging, and scaling way easier.

🧩 What Are Modules? #

A module is simply a Python file (.py) containing functions, classes, or variables that you can import and reuse in other Python scripts.

Example:

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

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

You can then import and use this module elsewhere:

import math_utils

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

πŸ“‚ What Are Packages? #

A package is a folder containing multiple modules and an __init__.py file (can be empty), letting Python know it’s a package.

library/
    __init__.py
    books.py
    members.py

You can import modules from packages like:

from library import books
from library.members import MemberClass

πŸ”„ Import Styles #

  • Basic import:
import math_utils
print(math_utils.add(2, 2))
  • Import specific functions:
from math_utils import add
print(add(2, 2))
  • Import with alias:
import math_utils as mu
print(mu.add(2, 2))

🧹 Benefits of Modules & Packages #

BenefitDescription
ReusabilityWrite once, reuse anywhere
MaintainabilityFix bugs and add features in one place
Namespace ManagementAvoid naming conflicts
CollaborationMultiple developers can work on different parts

πŸ›  Organizing Larger Projects #

  • Keep related functions/classes in dedicated modules.
  • Group related modules into packages.
  • Use meaningful names.
  • Avoid very large files β€” split code logically.

🧠 Real-World Use Case: Library Book Management App #

Scenario: #

Build a simple library system with:

  • books.py module to manage book info
  • members.py module to manage member data
  • main.py to run the application and import the above modules

Sample books.py #

books = []

def add_book(title, author):
    books.append({"title": title, "author": author})
    print(f"Book '{title}' added.")

def list_books():
    for book in books:
        print(f"{book['title']} by {book['author']}")

Sample members.py #

members = []

def add_member(name):
    members.append(name)
    print(f"Member '{name}' added.")

def list_members():
    for member in members:
        print(member)

Sample main.py #

import books
import members

def main():
    while True:
        print("\n--- Library Menu ---")
        print("1. Add Book")
        print("2. List Books")
        print("3. Add Member")
        print("4. List Members")
        print("5. Exit")
        choice = input("Choose an option: ")

        if choice == '1':
            title = input("Book title: ")
            author = input("Author: ")
            books.add_book(title, author)
        elif choice == '2':
            books.list_books()
        elif choice == '3':
            name = input("Member name: ")
            members.add_member(name)
        elif choice == '4':
            members.list_members()
        elif choice == '5':
            print("Goodbye!")
            break
        else:
            print("Invalid choice, try again.")

if __name__ == "__main__":
    main()

πŸ”‘ Key Takeaways #

ConceptSummary
ModulePython file with reusable code
PackageFolder of modules with __init__.py
Import stylesimport, from ... import, aliases
Project structureOrganize code logically into modules/packages
Real-world useBuild scalable apps like the library system

πŸ”š Wrap Up #

Modules and packages are your best friends as your projects grow. They keep your code neat, reusable, and easy to maintain β€” no more digging through monolithic scripts.


Object-Oriented Programming (OOP) in Python
Learn how to model real-world entities with classes, inheritance, and encapsulation β€” with a Vehicle Rental System example.

Ready for that one? Just say so!

Updated on June 9, 2025