Yes, The entire script is executed.
The reason we have a main guard is to enable your program to be used both as a standalone script ( in which case the __name__
variable is defined as "__main__"
) or imported as a module from another python script. In this case, we don't want any code to be run, we just want definitions of the code to be available to whoever loaded us.
One typical use of the __main__
guard is to run unit tests if the python file is run on its own. For example let us imagine we have file mymodule.py
:
def my_function(foo):
"""This function will add 54 to foo.
The following two lines are 'doctests' and can be run
automatically to show that the module's function work as expected.
>>> my_function(6)
60
"""
return foo + 54
if __name__ == "__main__":
import doctest
doctest.testmod() # this will run all doctests in this file
If we now run this on the command line, the tests will be run to check that the module works as expected.
Now, from another file, or from the command line, we can import mymodule.py
:
>>> import mymodule # Note that the tests will not be run when importing
>>> mymodule.my_function(3)
57
And the tests will not run because the __name__
variable will not be __main__
when the script is imported.
You can test this with a simple file (test.py
):
➤ cat test.py
#!/usr/bin/env python
print("my name is: ", __name__)
➤ python test.py
my name is: __main__
➤ python
Python 3.3.1 (default, Apr 6 2013, 19:11:39)
[GCC 4.8.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
my name is: test
>>>