Modules and name
This material is optional. You are not expected to know this for a test and there are no labs or projects using this material.
When python runs a file, it sets a variable called __name__ to "__main__".
This allows python to differentiate between the main file that is being run in a
script and other files that are being imported.
For example, here is a file called my_script.py:
def main():
print("This is inside of my_script's main function!")
print("This is outside of a function!")
if __name__ == "__main__":
print("This is my_script!")
main()
Running the program with
python my_script.py
sets __name__ to "__main__" in my_script.py, so the
if __name__ == "__main__": statement is true and the print statement is
executed.
This is outside of a function!
This is my_script!
This is inside of my_script's main function!
Notice the order of the print statements. Python runs the code from top to
bottom, first defining the function main(), then printing
"This is outside of a function!", then checking if __name__ is equal to
"__main__", and finally calling the main() function.
Now let’s say we have another file called other_script.py that imports
my_script.py:
import my_script
if __name__ == "__main__":
print("This is the other_script!")
my_script.main() ## We call my_script's main function here
Running the program with
python other_script.py
results in the following output:
This is outside of a function!
This is the other_script!
This is inside of my_script's main function!
Notice that the print statement outside of the function in my_script.py is
executed when other_script.py imports my_script.py.
When you import a module (or file) in python, the entire imported file is
evaluated, so the print statement outside of our main function is invoked;
however, when a module is imported, python doesn’t set its __name__ variable
to "__main__", so the if __name__ == "__main__": statement is false and that
block is not executed.
Hopefully you see that having code outside of a defined function or the
if __name__ == "__main__": block is bad practice as it can result in unwanted
code being run or cause larger errors. Defining functions and using the
if __name__ == "__main__": statement are used to protect code that you don’t
want to run when you import the script from another file. This is especially
useful when creating larger multi-file programs, testing specific functions, or
parsing command-line arguments.