if __name__ == ‘__main__’: What does it mean (Python)

Share this post

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():

if __name__ == '__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:

Subscribe to my Newsletter

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 __name__;
  • 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 __name__ variable.

When I execute the code using python main_module.py in the Terminal, the script will return __main__.

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 main_module.py.

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 main_module.py.

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__':
    print('The main() function did not execute')

What the main_module.py will now do is that:

If I execute main_module.py, print The Main() Function Executed, else if I import main_module.py print 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.

4.8/5 - (6 votes)