What is if __name__ == "__main__" in Python?


Let's suppose we have a file named first.py which has the following code inside:

print('Hello')

if __name__ == "__main__":
    print('Bye')

If you execute the above script with python first.py we will get as output:

Hello
Bye 

We get Hello because we have a print('Hello') function inside first.py, and we also get Bye because the if-conditional is evaluated to True.  In other words, the special variable __name__ is equal to the string "__main__".

We also have another file named second.py:

import first

print('Hi')

When we execute python second.py we get this:
Hello
Hi

So, Bye is missing this time. Hello was printed out because when you import a file from another file, the code of that imported file is executed entirely. However, the value of the variable __name__ this time is not "__main__" but "first" and that is the culprit.

So, when a file is executed directly, the __name__ variable of that file is equal to "__main__"; when a file is executed indirectly (i.e., through an import) the __name__ variable is equal to the name of the imported file (first in this case).

As programmers, we make use of that detail when we want to control when a block of code is to be executed. We wrap that code which we don't want to be executed inside an if __name__ == "__main__" block as you saw above.

Here is a more real-world scenario:

from flask import Flask

app = Flask()
@app.route('/')
def home():
    return 'Hello!'
    
if __name__ == '__main__':
    app.run()

The code above constructs a simple Flask web app. The very last line starts the app. We only want to start the app when the above file is executed directly. There might be scenarios when we want to use a particular object (e.g., the app variable) of the above script from other scripts. Importing the above script from other scripts would allow us to use that variable, but app.run() would be executed also if it was not inside the if-conditional statement. So, that if-conditional makes it possible to not start the Flask app in some unwanted scenarios.

Recommended Course

Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.