What does if __name__ == "__main__": do in Python?
Whenever a Python interpreter see a python source file, it does two things:
1. set a few special variables including '__name__' in this case
2. execute all the code found in the source file
Let me be specific, if write a python source file, you can run it as the main program and also you can import it as a module just like what you do with python standard libraries. So this is where "if __name__ == "__main__": " kicks in.
For intance,
# this is the code of foo.py
print("foo.py")
def foo():
print("Helo, this is the function foo.py!")
if __name__ == "__main__":
foo()
print("end of the file foo.py")
# after execution of file foo.py
foo.py
Helo, this is the function foo.py!
end of the file foo.py
If run this foo.py file as the main program, like python foo.py, python interpreter will follow the two steps above:
1. it sets the special variable __name__ to '__main__'
2. it executes all the code in the foo.py source file
Here is what is really happening for the foo.py if run it as the main program:
1. set __name__ to '__main__'
2. print "foo.py" without parentheses
3. create a function object and assign it to the name "foo"
4. check the condition __name__ == "__main__", which is True in this case, then run the function foo() and print "Helo, this is the function foo.py!" without parentheses.
5. print "end of the file foo.py" without parentheses
What happens if we import it into another file?
For instance,
# this is another_file.py with only one statement
import foo
# after execution of file another_file.py
foo.py
end of the file foo.py
Here is what is really happening for the another_file.py if we run it:
1. it sets the special variable __name__ to "foo"
2. it executes all the code in this file which in this case is the import foo statement
3. it then executes all the code from the foo module as the following:
1. print "foo.py" without parentheses
2. create a function object and assign it to the name "foo"
3. check the condition __name__ == "__main__", which is False in this case, then it will not execute the code inside the if statement.
4. print "end of the file foo.py" without parentheses
Comments
Post a Comment