When you start working with other people’s code you will run into the
if __name__ == '__main__' function at the end of the Python code. What does it mean?
def main(): pass if __name__ == '__main__': main()
What this function do is to check whether you run the module (or script) directly, or if you import the module from another one.
What it says is this:
If you run the module directly, execute the function, if you import the module, don’t run it.
Let’s break it out.
Basics on how Python runs a file
Whenever the Python reads a script, it does two actions:
- it sets a few special variables like
- it executes the code found in the script.
What __name__ does When Running a Script
Let’s build a
main_module.py file as an example.
The script will print the
When I execute the code using
python main_module.py in the Terminal, the script will return
What __name__ does When Importing a Script
Now, let’s see what happens when I try to import the module.
I created a
import_main.py python script that the only purpose is to import
If you are not familiar with how import works, all it does is that it executes the script that you import.
When I run python
import_main.py, it runs the
print(__name__) function that we wrote in
This time, however, the Terminal returns the name of the imported module instead of
__main__ as it did earlier.
Wrap-up: if __name__ == ‘__main__’
Coming back to the
main_module.py, let’s make this clearer with a complete example.
def main(): print('The Main() Function Executed') if __name__ == '__main__': main() else: print('The main() function did not execute')
main_module.py will now do is that:
If I execute
The Main() Function Executed, else if I import
The main() function did not execute.
Run the Main() Function From Import_main
Now, If you want, you could run any function available in the main_module.py from import_main.py.
This is it,
if __name__ == '__main__' is useful to import a Module to use the functions inside of it, without running the script.