Python: if __name__ == ‘__main__’

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:

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 file as an example.

The script will print the __name__ variable.

When I execute the code using python 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 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, 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, 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 will now do is that:

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

This is it, if __name__ == '__main__' is useful to import a Module to use the functions inside of it, without running the script.