Home >Backend Development >Python Tutorial >What does Python's `if __name__ == '__main__':` statement do?

What does Python's `if __name__ == '__main__':` statement do?

Barbara Streisand
Barbara StreisandOriginal
2025-01-01 14:53:14854browse

What does Python's `if __name__ ==

What does if __name__ == "__main__": do?

The __name__ guard is a common Python idiom that protects users from accidentally invoking a script when they didn't intend to. Omitting this guard can lead to unexpected behavior if you import the script in another script or serialize it as a pickle.

How it Works

When the interpreter reads a source file, it does two things:

  • Sets special variables like __name__
  • Executes the code found in the file

If you run your module as the main program, __name__ is set to "__main__". Otherwise, when you import the module, __name__ is set to the module's name.

The __name__ guard works as follows:

  • If __name__ == '__main__' (main program):

    • Execute the code within the guard body (usually functions).
  • If __name__ != '__main__' (imported module):

    • Skip the code within the guard body.

Code Sample

Let's examine the following code:

print("before import")
import math

print("before function_a")
def function_a():
    print("Function A")

print("before function_b")
def function_b():
    print("Function B {}".format(math.sqrt(100)))

print("before __name__ guard")
if __name__ == '__main__':
    function_a()
    function_b()
print("after __name__ guard")
  • Importing: math is imported without the guard, which is not ideal.
  • Main Program: If the code is run as the main program, it will print "Function A" and "Function B 10.0" within the __name__ guard.
  • Imported Module: If the code is imported as a regular module, the guard will be skipped, and the functions will not be executed.

Why Use it?

This idiom allows you to write .py files that can be used both as independent modules and as scripts that run as the main program. Some examples of its usefulness:

  • Library with Demo Mode: A library with a script mode for unit testing or running demos.
  • Unit Testing: Testing frameworks may import .py files as modules, requiring the __name__ guard to prevent script execution.
  • API Exposure: A module that provides an API for advanced users while running as an independent program.
  • Versatile Code: It's elegant to run a script by importing its module, and the __name__ guard facilitates this.

To summarize, the if __name__ == '__main__' guard can be omitted but is recommended for versatility, error protection, and to prevent unexpected behavior when importing or serializing code.

The above is the detailed content of What does Python's `if __name__ == '__main__':` statement do?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn