Script and Module Entry Points

Separate definitions from the action that starts a program so that importing a tool for testing does not accidentally run it.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Recognize top-level execution
  2. Keep an import safe to try
  3. Put reusable calculation in an importable function
  4. Test the normal forms separately

Recognize top-level execution

Python executes top-level statements when a module is first successfully imported in a process under its usual module name. That work can include setting constants, defining functions, and evaluating imports. In an ordinary direct script run, Python sets __name__ to "__main__". Code inside a conditional branch checking that value runs as the entry action of a script.

Keep an import safe to try

A reporting module can expose a function that returns a string from a supplied list. A separate main() reads the filename and prints that string. Put main() under the entry-point check. A test can then import the report function without reading the current directory or emitting output as a side effect.[1][2]

Put reusable calculation in an importable function

A small program can expose its calculation to tests while keeping reading and printing in its entry point. This example formats a measurement under a known scale without opening a file at import time.

def format_measurement(millimeters):
    return f"{millimeters / 1000:.2f} m"
def main():
    raw = input("Millimeters: ")
    print(format_measurement(int(raw)))
if __name__ == "__main__":
    main()

Executing the saved file reaches main(). If you enter 1500, its calculated output is 1.50 m after the prompt. Importing the file as a module defines both functions while the final condition evaluates false. Another module can call format_measurement(1500) directly. It can then compare the returned string without capturing a prompt or simulating keyboard input. The example deliberately keeps conversion inside the command boundary. A library function receiving a count still needs its own documented input contract.

Test the normal forms separately

A script can succeed when invoked directly and fail after packaging because it assumes a resource is in the current directory. Test the installed command from a different directory when that use is supported. A second test can import the reusable component and confirm that it does not print or request input. See working directories and module resources for the source of that difference.

If two commands share the same calculation, they can define separate entry points calling one helper. That preserves each command's argument rules and success or error outputs. It also avoids putting CLI behavior into the code imported by libraries.

References

  1. Python Software Foundation, Python Language Reference: Execution Model ↩
  2. Python Software Foundation, Python Language Reference: Expressions ↩