smartyfy.mrindigi.com

Python Master Course V2 — 068. Project Organization and Entry Points

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 07 — MODULES AND PACKAGES · LESSON 068 / 200

Project Organization and Entry Points

Estimated study: 60–90 minutes. Prerequisites: functions, collections, control flow and the preceding lesson. Level: intermediate Python.

Course hub

Video lesson

Video not yet available. Reserved for a verified video URL/player; written learning materials are available now.

Learning outcomes

Use main guards and modular structure. After completing this lesson, you should be able to explain the underlying mechanism, run the example, identify a boundary case, and apply the concept in a practical program.

Understand Project Organization and Entry Points

Keep reusable logic separate from starting the program

A project often has two audiences: another Python program importing its functions, and a person launching a command. Imports should make reusable code available without prompting for input, printing reports or starting the application. An entry point performs those effects deliberately. Separating them makes testing easier and prevents surprising behavior when a function is reused in a notebook, another script or a test suite.

Every module has a __name__. When a file is imported normally, that name identifies its module. When Python runs it as the main program, the name is "__main__". The familiar main guard checks this distinction. Function definitions still execute as definitions during import, but their bodies do not run until called. The guard does not stop all top-level code, only the statements inside the guarded block.

Save as app.py
def main():
    print("Application started")
    return 0

if __name__ == "__main__":
    raise SystemExit(main())
Terminal: direct execution
python app.py
Expected output
Application started
Terminal: import from app.py’s directory
python -c "import app; print('Imported without starting')"
Expected output
Imported without starting

Give the package a thin command-line layer

Extend the expensekit package from Lesson 064 with cli.py. Keep total_cents in totals.py, where it accepts an iterable of nonnegative integer cents and returns an integer. The CLI converts command arguments to integers, calls the reusable function and prints a result. argparse is a standard-library command-line parser; it supplies help text and reports invalid arguments without putting that behavior inside the calculation.

expensekit/cli.py
import argparse
from .totals import total_cents

def main(argv=None):
    parser = argparse.ArgumentParser(description="Add expense amounts in cents")
    parser.add_argument("amounts", nargs="*", type=int)
    args = parser.parse_args(argv)
    try:
        result = total_cents(args.amounts)
    except ValueError as error:
        parser.error(str(error))
    print(result)
    return 0
expensekit/__main__.py
from .cli import main

if __name__ == "__main__":
    raise SystemExit(main())
Terminal: run from the package’s parent directory
python -m expensekit 550 225
Expected output
775

The program follows a visible path: parse arguments, validate through the core function, calculate, print, and return an exit status. Returning zero means success. SystemExit carries that status to the operating system. argparse reports an invalid integer or the negative-amount validation error with a nonzero status; its exact usage line includes the invocation name, so treat it as environment-dependent text rather than a fixed output block.

Make command handling testable

The optional argv parameter lets a test call main(["550", "225"]) without changing global command-line state. When argv is None, argparse reads the real command arguments. The core function remains simpler to test because it returns a value without printing. Tests should cover the core calculation separately from CLI output and exit behavior; neither layer alone proves the whole application works.

A clear project layout places reusable modules together, tests in a separate directory and setup/run instructions in a README. Avoid reading files relative to an assumed working directory unless that location is part of the CLI contract. Package resources and user-supplied paths have different ownership. The next packaging capstone adds a distributable project and installed command, building on this same boundary between computation and presentation. See the Python __main__ documentation.

Runnable Python example

Requires Python 3.10+. Save the example as lesson68.py and run python lesson68.py (or python3). If it writes a file, run it in a disposable practice directory.

def main():
    print('Application started')
if __name__ == '__main__':
    main()

Expected output:

Application started

Step-by-step walkthrough

Read each statement in execution order. Identify imported modules, assigned variables, functions and the result passed to print(). Compare the output with the expected output and then change one input. Explain why the behavior changed. When an exception occurs, read the final traceback line and inspect the call that produced it.

Extension example

Refactor the central calculation or operation into a named function with a docstring and type hints. Add a caller that invokes it twice with different inputs. Test both results with assertions; for file operations, also test that the expected file exists and clean up practice files afterward.

Guided project — Project Organization and Entry Points application

Build a package layout with tests and a CLI entry point.

  1. Write a short requirements document specifying input data, output data and expected errors.
  2. Implement one focused function or module for the core behavior.
  3. Write a separate program entry point to collect or construct example input.
  4. Add validation and informative errors where appropriate.
  5. Test a normal case, a boundary case and an invalid case.
  6. Write a README showing how to run and test the program.

Acceptance criteria: clear behavior, no unexplained dependencies, reproducible execution and a documented result. The project is a guided assignment; its implementation must be completed and tested by the learner.

Common mistakes, debugging and best practices

  • Importing a local file with the same name as a standard-library module, causing shadowing.
  • Using broad exception handlers that conceal the real defect.
  • Assuming a path or dependency exists on every computer.
  • Mixing input/output and reusable business logic into one difficult-to-test function.
  • Testing only the happy path rather than edge cases and failures.

Debugging procedure: reproduce the failure with the smallest input; read the traceback; verify assumptions and data types; change one thing; rerun the same test; add a regression test after the fix.

Practice and explained answers

Try each question before opening its answer. Predict code results on paper, then compare them with the explanation.

Optional hint for question 1

Compare statements inside the guarded block with unguarded module-level statements.

1. Does a main guard prevent every statement in a module from running on import?

Answer and reasoning:

No. Only the guarded body is skipped. Imports, assignments and any unguarded calls at module level still execute. Keep expensive or user-facing effects inside explicit functions.

2. What is printed by import app in the first example?

Answer and reasoning:

Nothing. The main function is defined, but its call is inside the guard. Printing occurs only when main is called or the module is launched as the program.

3. Why does the CLI accept argv as a parameter?

Answer and reasoning:

It allows a test or another caller to provide an explicit argument list. Passing None preserves normal command-line behavior. This avoids editing sys.argv globally just to exercise the parser.

4. Where should the negative-amount rule live?

Answer and reasoning:

In total_cents, because it is a rule of the reusable calculation. The CLI catches the resulting ValueError and presents it as an argument error. Other callers receive the same validation behavior without depending on argparse.

5. What should python -m expensekit with no amounts print?

Answer and reasoning:

Expected output
0

nargs=”*” allows an empty list, and total_cents defines the sum of no amounts as zero. If an application requires at least one amount, change the parser contract to nargs=”+” and update tests and documentation together.

Knowledge check

Use the topic-specific practice questions above to check your understanding. Attempt each answer before opening its explanation.

Return to the practice questions ↑

Mastery checkpoint and summary

Demonstrate the concept without copying, explain one failure mode, complete the guided project and write three independent tests. These are suggested mastery checks, not account-synchronized completion records.

Key takeaway: Use main guards and modular structure. Apply it through clear contracts, thoughtful error handling, and repeatable testing.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.