Home >Backend Development >Python Tutorial >What does Python's `if __name__ == '__main__':` statement 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.
When the interpreter reads a source file, it does two things:
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):
If __name__ != '__main__' (imported module):
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")
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:
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!