When a code is to be executed, the Python interpreter reads the source file and defines a few special variables. If the Python interpreter is running the source file as the main program, it sets the special variable __name__
to the value "__main__"
. However, if example.py
is run as an imported file, then the interpreter will look at the filename of the module, strip off the .py, and assign that string to the module’s __name__
variable.
A module is a file that contains Python definitions and statements. The file name is the same as the module’s name, but appended with the suffix
.py
.
Suppose there is a file named example.py
that has the following code:
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")
If the file example.py
runs as a main program, then the interpreter will assign the hard-coded string "__main__"
to the __name__
variable:
__name__ = "__main__"
However, if example.py
is run as an imported file, then the interpreter will look at the filename of your module (example.py
), strip off the .py, and assign that string to your module’s __name__
variable:
__name__ = "example"
If the file example.py
runs as the main program, the output will be:
before import
before functionA
before functionB
before __name__ guard
Function A
Function B 10.0
after __name__ guard
If the file example.py
runs when imported, the output will be:
before import
before functionA
before functionB
before __name__ guard
after __name__ guard
If the module is the main program, then the interpreter will set __name__
to "__main__"
and call the two functions printing the strings “Function A” and “Function B 10.0”.
If the module is not the main program, then __name__
will be set to “example”, instead of "__main__"
, and the body of the if statement will be skipped over.
Free Resources