Logo OnlineCBT
PYTHON Tutorial
PYTHON · LESSON 18

Modules, Packages and Imports

Split a program into reusable files, import names safely, and understand how Python locates modules.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive
Updated: 26 Jul 2026

Lesson 18: Modules, Packages and Imports

1. Introduction to Code Organization and Reusability

As software projects scale from small scripts into enterprise systems, maintaining all logic inside a single file becomes impossible. Code becomes messy, hard to test, and prone to naming conflicts. Professional software engineering requires breaking programs down into smaller, logically organized, reusable components.

In Python, this modular architecture is achieved through Modules and Packages. Modules allow developers to group related functions, classes, and variables into separate files, which can then be imported and orchestrated across an entire application.


2. What is a Python Module?

A Module is simply a text file containing Python code ending with a .py extension. The module name is the name of the file without the extension.

1. Creating and Importing a Custom Module

Suppose we create a file named formatter_utils.py inside our workspace:

FORMATTER_UTILS.PY (MODULE FILE)
# Custom Module: formatter_utils.py

def clean_and_title(text: str) -> str:
    """Removes outer whitespace and capitalizes words."""
    return text.strip().title()

def format_currency(amount: float) -> str:
    """Formats float into a dollar string with commas."""
    return f"${amount:,.2f}"

MODULE_VERSION = "1.0.0"
MODULE DEFINITION
Saved as 'formatter_utils.py' in the current working directory.

2. Import Variants in Python

Python provides several ways to import and access code defined in external modules:

  • Full Module Import
  • import formatter_utils
  • formatter_utils.clean_and_title("py")
  • Module Import with Alias
  • import formatter_utils as fmt
  • fmt.format_currency(100)
  • Specific Member Import
  • from formatter_utils import format_currency
  • format_currency(100) (Direct name)
  • Multiple Specific Imports
  • from formatter_utils import clean_and_title, MODULE_VERSION
  • Direct name access for both members
Import Syntax Variant Code Example Namespace Access Pattern
Avoid Wildcard Imports (`from module import *`): Importing everything using an asterisk pollutes the local namespace, overwrites existing variable names silently, and makes code debugging extremely difficult. Always import names explicitly!
MAIN_IMPORT_DEMO.PY
# Simulating usage of custom module imports
import formatter_utils as fmt
from formatter_utils import MODULE_VERSION

raw_name = "   python enterprise system  "
price = 1250000.75

cleaned_name = fmt.clean_and_title(raw_name)
formatted_price = fmt.format_currency(price)

print(f"Module Version : {MODULE_VERSION}")
print(f"Cleaned Title  : {cleaned_name}")
print(f"Formatted Price: {formatted_price}")
OUTPUT
Module Version : 1.0.0
Cleaned Title  : Python Enterprise System
Formatted Price: $1,250,000.75

3. The Special Variable `__name__` and `if __name__ == "__main__":`

Whenever Python executes a source file, it automatically sets special built-in dunder (double underscore) variables before running any code. One of the most critical dunder variables is __name__.

How `__name__` Works:

  • If a Python file is run **directly** (e.g., python app.py in the terminal), Python sets __name__ = "__main__".
  • If a Python file is **imported** as a module into another script (e.g., import app), Python sets __name__ to the file's module name (e.g., __name__ = "app").
Why `if __name__ == "__main__":` is Essential: This boilerplate block allows a file to act as BOTH an executable standalone script AND an importable module. Code inside the if __name__ == "__main__": block executes ONLY when the file is run directly, preventing test/demo code from executing automatically when imported elsewhere!
MODULE_WITH_MAIN_GUARD.PY
def calculate_tax(amount, rate=0.18):
    return amount * rate

# Test suite executed ONLY when file is run directly!
if __name__ == "__main__":
    print("--- Running Internal Standalone Test Suite ---")
    sample_tax = calculate_tax(100.0)
    print(f"Test Tax Calculation: ${sample_tax:.2f}")
    print(f"Internal __name__ Value: '{__name__}'")
OUTPUT (When run directly)
--- Running Internal Standalone Test Suite ---
Test Tax Calculation: $18.00
Internal __name__ Value: '__main__'

4. What is a Python Package?

While a module is a single .py file, a Package is a directory containing multiple modules and a special initialization file named __init__.py. Packages allow hierarchical structuring of large application codebases using dot notation (e.g., import app.services.payment).

1. Enterprise Package Directory Layout

my_enterprise_app/              <-- Root Project Directory
│
├── main.py                     <-- Main Execution Entry Point
│
└── ecommerce/                  <-- Package Directory
    ├── __init__.py             <-- Marks directory as a Package
    ├── billing.py              <-- Sub-module
    ├── inventory.py            <-- Sub-module
    └── shipping.py             <-- Sub-module
    

2. Role of the `__init__.py` File

  • In Python 3.3+, __init__.py is technically optional (creating implicit namespace packages), but keeping it is an industry best practice.
  • It executes automatically whenever the package or any of its sub-modules are imported.
  • It can expose package-level APIs, initialize shared state, or define __all__ export lists.

5. Exploring Python's Standard Library

Python follows a "Batteries Included" philosophy. It includes a massive standard library of pre-built modules ready for immediate import without installing external tools:

  • math: Advanced mathematical functions and constants.
  • sys: System-specific parameters and CLI argument parsing (sys.argv, sys.path).
  • os / pathlib: Operating system interfaces, environment variables, and file path manipulation.
  • random: Pseudorandom number generators and sequence shufflers.
  • datetime: Date and time parsing, formatting, and arithmetic operations.
STANDARD_LIBRARY_DEMO.PY
import sys
import random
from datetime import datetime

# Standard library module usage
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
random_session_id = random.randint(100000, 999999)

print(f"System Execution Time: {current_time}")
print(f"Generated Session ID : {random_session_id}")
print(f"Python Runtime Engine: {sys.version.split()[0]}")
OUTPUT
System Execution Time: 2026-07-26 15:14:19
Generated Session ID : 849201
Python Runtime Engine: 3.12.0

6. Integrating Imported Modules with `match-case` Structural Pattern Matching

Building scalable applications involves importing custom service modules and routing operational requests using match-case pattern matching dispatchers.

MATCH_CASE_MODULE_DISPATCHER.PY
# Simulating importing a custom billing module
class MockBillingModule:
    @staticmethod
    def charge_card(card_no, amount):
        return f"CARD_OK: Charged ${amount:.2f} to ****-{card_no[-4:]}"
        
    @staticmethod
    def process_upi(vpa, amount):
        return f"UPI_OK: Transferred ${amount:.2f} to {vpa}"

billing_svc = MockBillingModule()

def route_payment_request(request_payload):
    """Routes incoming payload commands to module services using match-case."""
    match request_payload:
        case ["PAY", "CARD", card_num, amount] if len(card_num) == 16:
            return billing_svc.charge_card(card_num, amount)
            
        case ["PAY", "CARD", _, _]:
            return "ERROR: Invalid Card Number digits!"
            
        case ["PAY", "UPI", vpa_id, amount] if "@" in vpa_id:
            return billing_svc.process_upi(vpa_id, amount)
            
        case ["STATUS"]:
            return "SERVICE_STATUS: All payment gateways operational."
            
        case _:
            return "ERROR: Unknown module request command payload."

# Testing module routing
print(route_payment_request(["PAY", "CARD", "1234567890123456", 199.99]))
print(route_payment_request(["PAY", "UPI", "merchant@upi", 50.00]))
print(route_payment_request(["STATUS"]))
OUTPUT
CARD_OK: Charged $199.99 to ****-3456
UPI_OK: Transferred $50.00 to merchant@upi
SERVICE_STATUS: All payment gateways operational.

7. Frequently Asked Interview Questions with Answers

Q1: What is the difference between a Python Module and a Python Package?
Answer: A Module is a single Python file ending in .py that contains executable code, functions, or classes. A Package is a directory containing multiple sub-modules and an __init__.py file that allows importing modules hierarchically using dot notation.
Q2: Why is the `if __name__ == "__main__":` idiom used in Python scripts?
Answer: Python assigns __name__ = "__main__" when a script is executed directly from the command line, but sets __name__ to the file's module name when imported. Checking if __name__ == "__main__": ensures that test suites or execution logic run ONLY when the file is executed directly, preventing unexpected execution when imported elsewhere.
Q3: How does Python locate imported modules, and what is `sys.path`?
Answer: When an import statement executes, Python searches directories listed in sys.path in order:
  1. The directory containing the input script (current directory).
  2. Standard library directories.
  3. Third-party site-packages directories.
Q4: Why should wildcard imports (`from module import *`) be avoided in production code?
Answer: Wildcard imports pollute the local namespace, making it unclear where specific functions or variables originated. They can also silently overwrite existing local functions or variables, leading to subtle bugs.
Q5: What is the role of `__init__.py` in a Python package directory?
Answer: The __init__.py file marks a directory as an importable Python package. It executes automatically when the package is imported, allowing package-level initialization, setting module aliases, and controlling exported symbols via __all__.

8. Homework & Practical Assignments

Task 1: Custom String Processing Utility Module

Create a custom module file named str_utils.py inside your lesson_18 folder:

  • Define function sanitize_text(text: str) -> str that strips whitespace and converts to lowercase.
  • Define function mask_sensitive(text: str, visible_suffix_len: int = 4) -> str that masks characters with * except for the trailing suffix.
  • Add an if __name__ == "__main__": block containing test calls for both functions.
  • Create a separate script main_task1.py that imports str_utils and calls its functions.

Task 2: Modular Functional Data Pipeline

Create a script named pipeline_task2.py:

  • Import functools.reduce and random standard library modules.
  • Generate a list of 10 random floating-point transaction amounts between 10.0 and 500.0.
  • Use filter() with a lambda to keep amounts >= 100.0.
  • Use reduce() with a lambda to calculate the total sum of filtered amounts.
  • Print results formatted as currency strings.

Task 3: Master Capstone Project — Modular Enterprise ERP System (`enterprise_erp_os.py`)

Project Goal: Build a complete, modular, interactive terminal script named enterprise_erp_os.py integrating **ALL concepts learned across Lessons 1 through 18**.

Project Architectural Requirements Specification:

  1. Modular Import Architecture & Main Guard (Lesson 18):
    • Import standard library modules (sys, datetime, random).
    • Import custom helper functions from your str_utils.py module created in Task 1.
    • Wrap the main application execution logic inside an if __name__ == "__main__": guard block.
  2. Functional Tools & Anonymous Lambdas (Lesson 17):
    • Use map() with lambda functions to apply tax transformations to transaction arrays.
    • Sort record dictionaries using sorted() with custom tuple lambda keys.
  3. Advanced Parameters, Arguments & Scope (Lesson 16):
    • Write a logger function accepting *args and **kwargs to record audit entries into a global audit log.
    • Use safe default parameters (options=None) to avoid mutable default parameter bugs.
  4. Modular Functions & Return Values (Lesson 15):
    • Structure logic into pure functions with type hints, docstrings, and early return Guard Clauses.
  5. Indefinite & Definite Loops (Lessons 13-14):
    • Run the interactive CLI interface inside a continuous while True menu loop.
    • Iterate through output records using for loops with enumerate().
  6. Pattern Matching Command Dispatcher (Lesson 12):
    • Process incoming user CLI command tokens inside a match-case block:
      • case ["USER", "ADD", raw_name, email] → Clean inputs using imported str_utils functions and register user.
      • case ["TRANSACT", *amounts_str] → Map tokens to floats, compute taxed totals using map(), and store.
      • case ["AUDIT"] → Print global system audit history log.
      • case ["EXIT" | "QUIT"] → Terminate session safely using a sentinel flag.
      • case _ → Output command error message.
  7. Conditionals, Strings, Formatting & Math Foundations (Lessons 1-11):
    • Evaluate authorization permissions using if-elif-else conditional trees.
    • Format tabular outputs using f-strings with field alignment specifiers (:<15, :>10) and currency formatting (:,.2f).

9. File & Workspace Directory Structure

Standard Course Workspace Layout:

Ensure all exercise files are stored inside their corresponding lesson directories:

python_mastery_course/
│
├── lesson_01/ ... lesson_17/
│
└── lesson_18/
    ├── formatter_utils.py
    ├── main_import_demo.py
    ├── module_with_main_guard.py
    ├── standard_library_demo.py
    ├── match_case_module_dispatcher.py
    ├── str_utils.py               <-- (Task 1 Module)
    ├── main_task1.py              <-- (Task 1 Main Script)
    ├── pipeline_task2.py          <-- (Task 2)
    └── enterprise_erp_os.py       <-- (Task 3: Master Review Capstone)
        

10. What We Will Learn Next

Next Up: Lesson 19 — Virtual Environments, pip and Dependencies

Now that you master modularizing code across files and importing standard libraries, we will explore managing third-party packages and isolated software environments.

In the next lesson, we will cover:

  • Understanding the Python Package Index (PyPI) ecosystem.
  • Installing, upgrading, and removing third-party libraries using pip.
  • Creating isolated Virtual Environments using venv (e.g., python -m venv .venv).
  • Activating and deactivating virtual environments across Windows, macOS, and Linux.
  • Managing project dependencies using requirements.txt files (pip freeze > requirements.txt).

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat