Python DISCUSSION

What does if __name__ == '__main__' do in a Python script, and when is it really required?

Started by yuseff __name__ variablemain guardPython importmodule executionmultiprocessing
4 replies 248 views 5 participants
Latest activity · 30 Sep 2026

What does if __name__ == '__main__' do in a Python script, and when is it really required?

yuseff Python Forum
#1

I split my data-logger script into two files. logger.py opens the serial port and starts logging at the bottom of the file; plot.py does import logger to reuse one parsing function. Now running plot.py opens the serial port and starts logging, which I did not want.

Tutorials put such code under if __name__ == "__main__": without explaining much. What is __name__, who sets it, and are there cases where leaving the guard out causes real failures rather than just unwanted output?

Community replies 4

Re: What does if __name__ == '__main__' do in a Python script, and when is it really required?

#2

Importing a module executes the whole file from top to bottom. def and class are statements that create functions and classes when they run, and every other top-level statement runs too, including the code that opens your port.

Before executing a file, Python sets the module-level variable __name__. For the file you start directly with python logger.py it is the string "__main__". For a file loaded through import logger it is the module name, "logger". So the guard means "only when this file is the entry point of the program". Put the port-opening code under it, and import logger from plot.py will only define the functions.

Re: What does if __name__ == '__main__' do in a Python script, and when is it really required?

#3

The recommended shape is to put the script logic in a function and keep the guard to two lines: def main(): ... and then if __name__ == "__main__": main().

Besides tidiness, variables assigned inside main() are locals rather than module globals, so helper functions cannot depend on them by accident. Other files and tests can call logger.main() deliberately. If main returns an exit status, use sys.exit(main()). And importing the same module from several places does not run it several times: modules are cached in sys.modules, so top-level code runs on the first import only.

Re: What does if __name__ == '__main__' do in a Python script, and when is it really required?

#4

The case with real failures is multiprocessing. With the "spawn" start method, which is the default on Windows and macOS, each worker process starts a fresh interpreter and imports your main script to find the function it should run. If the code that creates the Pool or Process sits at top level without the guard, every child executes it again and tries to start children of its own.

Python detects this and raises a RuntimeError about starting a new process before the current one has finished its bootstrapping phase. With the "fork" method long used on Linux the unguarded script happens to work, which is how code ends up running on one machine and failing on another.

Re: What does if __name__ == '__main__' do in a Python script, and when is it really required?

#5

Two related details. python -m package.module also runs that module with __name__ set to "__main__" while keeping package-relative imports working, and a package can be made runnable by adding a __main__.py file.

There is also a trap: if logger.py is running as the main script and another module does import logger, the file is loaded a second time as a separate module named logger. You then have two copies of every global and class in it, which shows up as isinstance checks failing or settings that do not stick. Keep the entry script thin and put shared code in modules that are only ever imported.

TEP COMMUNITY