in Technology by
What does if __name__ == “__main__”: do in Python?

1 Answer

0 votes
by

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 functionA")
def functionA():
    print("Function A")

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

print("before __name__ guard")
if __name__ == '__main__':
    functionA()
    functionB()
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.py

the 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 foo

The 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

  1. It prints the string "before import" (without quotes).

  2. 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")
  1. It prints the string "before functionA".

  2. It executes the def block, creating a function object, then assigning that function object to a variable called functionA.

  3. It prints the string "before functionB".

  4. It executes the second def block, creating another function object, then assigning it to a variable called functionB.

  5. It prints the string "before __name__ guard".

Only When Your Module Is the Main Program

  1. 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

  1. (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 the if statement.

Always

  1. 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 functionA
before functionB
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 functionA
before functionB
before __name__ guard
after __name__ guard

Related questions

0 votes
    What is the use of if __name__ == "__main__": in python? Ex. import time, thread def myfunction(string, sleeptime, ... 2", 2, lock)) Select the correct answer from above options...
asked Jan 21, 2022 in Education by JackTerrance
0 votes
    If I use a while loop for my below code, it is not giving the desired output, but when i use for loop i am anle ... x += 1 print(Comm) Select the correct answer from above options...
asked Jan 9, 2022 in Education by JackTerrance
0 votes
    What is the best way to open a file as reading/write if it exists, or if it does not, then create it and ... to do the opening part. Select the correct answer from above options...
asked Jan 30, 2022 in Education by JackTerrance
0 votes
    What are you going to do if there is no Functional Spec or any documents related to the system and developer who wrote ... company anymore, but you have a system and need to test?...
asked Oct 17, 2020 in Technology by JackTerrance
0 votes
    What does pip stand for python? a) Pip Installs Python b) Pip Installs Packages c) Preferred Installer Program d) All of the mentioned...
asked Dec 31, 2022 in Technology by JackTerrance
0 votes
    Does Python have a ternary conditional operator?...
asked Jan 9, 2021 in Technology by JackTerrance
0 votes
    Does Dataset API support Python and R. 1. yes 2. No...
asked Oct 22, 2020 in Technology by JackTerrance
0 votes
    I'm trying to open up a PDF as an image using Wand. If I run the code below in Jupyter Notebook ... , JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 21, 2022 in Education by JackTerrance
0 votes
    In Java you can define a new class inline using anonymous inner classes. This is useful when you need ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 11, 2022 in Education by JackTerrance
0 votes
    In Java you can define a new class inline using anonymous inner classes. This is useful when you need ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 11, 2022 in Education by JackTerrance
0 votes
    In Java you can define a new class inline using anonymous inner classes. This is useful when you need ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 11, 2022 in Education by JackTerrance
0 votes
    In Java you can define a new class inline using anonymous inner classes. This is useful when you need ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 11, 2022 in Education by JackTerrance
0 votes
    The awkward scenario I am developing a python package and would like to make use of an external package, ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 13, 2022 in Education by JackTerrance
0 votes
    def main(): for i in xrange(10**8): pass main() This piece of code in Python runs in (Note: The timing is ... sys 0m0.012s Why is this? Select the correct answer from above options...
asked Feb 1, 2022 in Education by JackTerrance
0 votes
    Can someone tell me any string.contains or string.indexof method in Python I want to do if not somestring.contains("boom"): continue Select the correct answer from above options...
asked Jan 20, 2022 in Education by JackTerrance
...