Member-only story
if __name__ == “__main__” in Python Explained Simply
If you just started learning Python, you’ve probably come across something like this:
# stuffif __name__ == "__main__":
# do stuff
This article will attempt to explain as simply as possible what is happening here, and the situations where if __name__ == "__main__"
is required. Note that there are 2 underscore characters in front and behind name
and main
.
Long story short, this line of code allows us to ensure that we don’t accidentally run some code that we don’t intend to run. But let’s take a deeper dive into how this works exactly:
The Special __name__ Variable
The __name__
variable is set to a string variable "__main__"
when we run our Python script normally. Let’s say we have 1 Python script first.py
first.py
print(__name__)
If we run first.py
, like this:
python first.py # for windows
pytohn3 first.py # for MacOS
We get this output:
__main__
Essentially, the __name__
variable in the Python script that we run first.py
is set to the string value "__main__"
. However, this behaviour differs when there are multiple Python…