liveBook · Manning

Entry point

As explained in The Quick Python Book, Fourth Edition

A main function, or controlling function, is a conventionally designated function that coordinates a program's execution and serves as its controlling entry point.

An entry point is a conventionally designated function that coordinates a program's execution. In a small Python script, define a controlling function named main and call it. section 11.1

Listing 11.1 File script1.py
def main():                                  #1
    print("this is our first test script file")
main()                                       #2

A minimal entry point defines main first, then invokes it at the bottom of the file. section 11.1

As a script grows, keep the entry point separate from reusable functions such as num2words. Guard the call with if __name__ == '__main__' so the file can also be imported as a module for testing, debugging, or reuse. section 11.3

A script that is also a module

Place reusable functions above the entry-point guard, then call main only when the file runs as a script. This keeps importing from triggering the program's controlling behavior. section 11.3

The same pattern scales to packages: a main function can coordinate functionality supplied by separate cleaning, processing, and exception modules. section 18.6

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains definition, invocation, placement, and the import-safe name guard without descending into runtime implementation details.
Examples
Uses a minimal main script, a number-to-words command-line program, an import-safe module, and a package refactoring exercise.
What it assumes
Assumes general Python programming knowledge and teaches the script-to-module organization pattern through small examples.
What you can do after
Build it from scratch by defining a main function, invoking it, and guarding the call for safe importing.
How it connects
Connects controlling functions with scripts, modules, packages, importing, testing, and debugging.

Also explained in

Compare how 10 books explain entry point →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.