Question presented to candidate:
"You see if __name__ == "__main__": at the bottom of almost every Python script. What does that line actually check, and what would break if you deleted it?"
What a strong answer should cover:
- Every module has a global
__name__. The interpreter sets it to"__main__"for the module it was started with (python file.py,python -m pkg.mod,python -c), and to the module's import name (for example"greet") when the file is imported. - So the guard runs its block only when the file is executed as the program, not when another module imports it; the rest of the file (functions, classes, constants) still runs on import.
- Why it matters: importing a module should have no side effects β tests, tools and other modules can import the functions without starting the script.
- Practical cases:
multiprocessingwith the spawn or forkserver start methods re-imports the main module in each child, so unguarded start-up code runs again; a script that imports itself runs twice as two modules. - The idiomatic shape: put the work in
def main(argv=None) -> int, and end withif __name__ == "__main__": raise SystemExit(main()); a package uses__main__.pyforpython -m pkg.
Code / implementation expected: Optional β a module with a main() function and the guard, and what prints on import versus on run.