ALL MODULESmodule_13.py

Mini-Project: Building a Modular Application

~45 minTheoryLive CodingDemoChallengeQuiz
theory.md

10. Clean Software Architecture, Packaging & Mini-Projects

10.1Clean Layered Architecture

When software applications grow large, placing all code into a single giant file becomes unmaintainable. Professional developers organize code into three distinct layers (Layered Architecture):

  1. Domain/Model Layer: Contains core business data objects and business rules (e.g. User, Product, Order).
  2. Service/Logic Layer: Processes workflows and data operations (e.g. OrderService, PaymentGateway).
  3. Interface/Presentation Layer: Handles user interaction (e.g. Command Line Interface, Web API endpoints).
ANALOGY TIME
Think of a restaurant! The menu and waiter are the Interface layer, the chef in the kitchen is the Service layer, and the raw ingredients and recipes are the Domain layer. Separating responsibilities keeps the restaurant running smoothly!

10.2Module Packaging & Import Resolution System

  • Module: A single Python file (utils.py).
  • Package: A folder containing Python files and a special file named __init__.py.
  • Import Resolution (`sys.path`): When you write import my_module, Python searches through folders listed in a system list called sys.path. It checks the current directory first, followed by installed packages.

10.3Entry Point Guard (if __name__ == "__main__":)

Every Python file has a built-in variable named __name__:

  • If you run the file directly (python app.py), Python sets __name__ = "__main__".
  • If another file imports your file (import app), Python sets __name__ = "app".

Using if __name__ == "__main__": at the bottom of your file ensures that setup script code runs ONLY when the file is executed directly as the main application, NOT when it is imported as a module elsewhere!

10.4CLI Argument Parsing (argparse module)

Command-line programs accept flags and arguments passed in the terminal (e.g. python script.py --verbose --count 5). Python's built-in argparse module provides a professional framework to parse these arguments and auto-generate help messages.

10.5Code Demo 1: CLI Argument Parsing Framework

Build a clean command-line interface tool:

PYTHON

10.6Code Demo 2: Modular Architecture Pattern

Demonstrating clean separation between domain logic and service handlers:

PYTHON
GOTCHA 1

Circular imports: Module A imports Module B, while Module B imports Module A. This raises an ImportError or AttributeError during initialization. Resolve by refactoring shared code into a third module.

GOTCHA 2

Running code with side-effects (like calling print() or modifying files) at top-level module scope without wrapping in if __name__ == '__main__':. These side-effects run unexpectedly upon import!

GOTCHA 3

Confusing relative imports (from .utils import helper) with absolute imports. Relative imports only work inside packages.

GOTCHA 4

Naming a local script json.py, random.py, or test.py, which breaks standard library imports.

WHERE THIS SHOWS UP IN REAL CODE

Professional software engineering is about organizing thousands of lines of code across multiple files, modules, and packages. Understanding imports, package entry points, and modular architecture is critical for real-world development.

TRY THIS YOURSELF

Modify Demo 2 to add a print statement showing the value of __name__ when executed.

live_coding — Modular Task Management Engine Architecture

Notice how separating model, service, and controller makes code clean and testable.

Project Plan (Click nodes to edit)

1. Define Data2. Write Functions3. Main Loop4. Test App
Python not loaded yet.
demo — Demonstrate modular code architecture, module import resolution, sys.path, and main entry point guards.

Demonstrate modular code architecture, module import resolution, sys.path, and main entry point guards.

challenge_1

Let's refactor calculations into a modular function pipeline!

Steps to Complete:

  1. Write validate_input(val) returning True if val > 0.
  2. Write calculate_tax(val) returning val * 0.10.
  3. Write process_order(val) calling validate_input and returning calculate_tax.
  4. Call process_order(100) and print Tax: 10.0.

Expected Output:

TEXT
Python not loaded yet.
challenge_2

Let's build an Inventory management class!

Steps to Complete:

  1. Create class Inventory with self.items = {}.
  2. Add add_stock(name, qty) and get_stock(name).
  3. Add 'Laptops' (+50) and print Laptops in Stock: 50.

Expected Output:

TEXT
Python not loaded yet.
challenge_3

Let's write a main entry point guard script!

Steps to Complete:

  1. Write bootstrap(). function printing Application Bootstrapped Successfully.
  2. Call bootstrap() inside an if __name__ == '__main__': block.

Expected Output:

TEXT
Python not loaded yet.
quiz — 7 questions
30s question timers are paused. Start individually or all together.
# question 1

What is the value of the built-in `__name__` variable when a Python script is executed directly from the terminal (`python app.py`)?

# question 2

What is the primary purpose of the `if __name__ == '__main__':` guard statement?

# question 3

What is a circular import in Python?

# question 4

What is recorded in `sys.path`?

# question 5

What is the purpose of an `__init__.py` file inside a directory?

# question 6

What is the difference between `import analytics` and `from analytics import calculate`?

# question 7

Which layer in a modular application architecture should handle raw user CLI inputs and print formatting?

discussion

# comments · mini-project

  • @priya · 2h ago

    The typewriter hero is such a nice touch.

    • @alex · 1h ago

      Totally agree! Made it super engaging.

  • @sam · 1d ago

    Finally a course where I can run code without leaving the page.