patternpythonCritical
What does if __name__ == "__main__": do?
Viewed 0 times
__main__whatdoes__name__
Problem
What does this do, and why should one include the
If you are trying to close a question where someone should be using this idiom and isn't, consider closing as a duplicate of Why is Python running my module when I import it, and how do I stop it? instead. For questions where someone simply hasn't called any functions, or incorrectly expects a function named
if statement?if __name__ == "__main__":
print("Hello, World!")
If you are trying to close a question where someone should be using this idiom and isn't, consider closing as a duplicate of Why is Python running my module when I import it, and how do I stop it? instead. For questions where someone simply hasn't called any functions, or incorrectly expects a function named
main to be used as an entry point automatically, use Why doesn't the main() function run when I start a Python script? Where does the script start running?.Solution
Short Answer
It's boilerplate code that protects users from accidentally invoking the script when they didn't intend to. Here are some common problems when the guard is omitted from a script:
-
If you import the guardless script in another script (e.g.
-
If you have a custom class in the guardless script and save it to a pickle file, then unpickling it in another script will trigger an import of the guardless script, with the same problems outlined in the previous bullet.
Long Answer
To better understand why and how this matters, we need to take a step back to understand how Python initializes scripts and how this interacts with its module import mechanism.
Whenever the Python interpreter reads a source file, it does two things:
-
it sets a few special variables like
-
it executes all of the code found in the file.
Let's see how this works and how it relates to your question about the
Code Sample
Let's use a slightly different code sample to explore how imports and scripts work. Suppose the following is in a file called
Special Variables
When the Python interpreter reads a source file, it first defines a few special variables. In this case, we care about the
When Your Module Is the Main Program
If you are running your module (the source file) as the main program, e.g.
the interpreter will assign the hard-coded string
When Your Module Is Imported By Another
On the other hand, suppose some other module is the main program and it imports your module. This means there's a statement like this in the main program, or in some other module the main program imports:
The interpreter will search for your
Executing the Module's Code
After the special variables are set up, the interpreter executes all the code in the module, one statement at a time. You may want to open another window on the side with the code sample so you can follow along with this explanation.
Always
-
It prints the string
-
It loads the
-
It prints the string
-
It executes the
-
It prints the string
-
It executes the second
-
It prints the string
Only When Your Module Is the Main Program
Only When Your Module Is Imported by Another
Always
Summary
In summary, here's what'd be printed in the two cases:
Why Does It Work This Wa
It's boilerplate code that protects users from accidentally invoking the script when they didn't intend to. Here are some common problems when the guard is omitted from a script:
-
If you import the guardless script in another script (e.g.
import my_script_without_a_name_eq_main_guard), then the latter script will trigger the former to run at import time and using the second script's command line arguments. This is almost always a mistake.-
If you have a custom class in the guardless script and save it to a pickle file, then unpickling it in another script will trigger an import of the guardless script, with the same problems outlined in the previous bullet.
Long Answer
To better understand why and how this matters, we need to take a step back to understand how Python initializes scripts and how this interacts with its module import mechanism.
Whenever the Python interpreter reads a source file, it does two things:
-
it sets a few special variables like
__name__, and then-
it executes all of the code found in the file.
Let's see how this works and how it relates to your question about the
__name__ checks we always see in Python scripts.Code Sample
Let's use a slightly different code sample to explore how imports and scripts work. Suppose the following is in a file called
foo.py.# Suppose this is foo.py.
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")Special Variables
When the Python interpreter reads a source file, it first defines a few special variables. In this case, we care about the
__name__ variable.When Your Module Is the Main Program
If you are running your module (the source file) as the main program, e.g.
python foo.pythe interpreter will assign the hard-coded string
"__main__" to the __name__ variable, i.e.# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__"When Your Module Is Imported By Another
On the other hand, suppose some other module is the main program and it imports your module. This means there's a statement like this in the main program, or in some other module the main program imports:
# Suppose this is in some other main program.
import fooThe interpreter will search for your
foo.py file (along with searching for a few other variants), and prior to executing that module, it will assign the name "foo" from the import statement to the __name__ variable, i.e.# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"Executing the Module's Code
After the special variables are set up, the interpreter executes all the code in the module, one statement at a time. You may want to open another window on the side with the code sample so you can follow along with this explanation.
Always
-
It prints the string
"before import" (without quotes).-
It loads the
math module and assigns it to a variable called math. This is equivalent to replacing import math with the following (note that __import__ is a low-level function in Python that takes a string and triggers the actual import):# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")-
It prints the string
"before function_a".-
It executes the
def block, creating a function object, then assigning that function object to a variable called function_a.-
It prints the string
"before function_b".-
It executes the second
def block, creating another function object, then assigning it to a variable called function_b.-
It prints the string
"before __name__ guard".Only When Your Module Is the Main Program
- If your module is the main program, then it will see that
__name__was indeed set to"__main__"and it calls the two functions, printing the strings"Function A"and"Function B 10.0".
Only When Your Module Is Imported by Another
- (instead) If your module is not the main program but was imported by another one, then
__name__will be"foo", not"__main__", and it'll skip the body of theifstatement.
Always
- It will print the string
"after __name__ guard"in both situations.
Summary
In summary, here's what'd be printed in the two cases:
# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
Why Does It Work This Wa
Code Snippets
# Suppose this is foo.py.
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")python foo.py# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__"# Suppose this is in some other main program.
import foo# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"Context
Stack Overflow Q#419163, score: 9046
Revisions (0)
No revisions yet.