Let's suppose we have a file named first.py which has the following code inside:
if __name__ == "__main__":
If you execute the above script with python first.py we will get as output:
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:
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()
if __name__ == '__main__':
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.
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.