Skip to content

What does if __name__ == "__main__" do?

It's good practice to apply this in your scripts. Find out why and how this works.


It is boilerplate code that protects users from accidentally invoking a script when they didn鈥檛 intend to, and it鈥檚 good practice apply it. This makes a difference for these two use cases:

  • We run it as the main program with python filename.py
  • We import the file in another file with import filename

In the latter case usually we only want to import the module and then later in the code execute some functions or use a class from this file. This is where the if __name__ == "__main__" statement comes into play and works as a guard.

Let鈥檚 find out why and how this works.

Special variable

When the Python interpreter reads a source file, it does two things:

  • First, it sets a few special variables like __name__
  • Then it executes all of the code it finds in the file

Let鈥檚 have a look at the following example where we correctly use the if __name__ == "__main__" statement:

# This is foo.py

def functionA():
    print("Function A")

if __name__ == "__main__":
    print("Running foo")
    functionA()

Case 1: Run it as the main program with python foo.py.

The Python interpreter will assign the hard-coded string "__main__" to the __name__ variable, thus the code in the if statement is executed:

$ python foo.py
Running foo
Function A

Case 2: Import foo in another module.

The interpreter will assign "foo" to the __name__ variable in the foo module. Thus, the code in the if statement is not executed, and functionA will not run.

# This is bar.py
import foo

if __name__ == "__main__":
    print("Running bar")
$ python bar.py
Running bar

Without the if __name__ == "__main__" in foo.py, the output would be the following:

$ python bar.py
Running foo
Function A
Running bar

Usually this is not what we want. So if you want to run code in a file, it鈥檚 good practice to wrap all of this code into a if __name__ == "__main__" statement.

More Resources:

StackOverflow answer to the question


FREE VS Code / PyCharm Extensions I Use

鉁 Write cleaner code with Sourcery, instant refactoring suggestions: Link*

* This is an affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 馃檹