What does if __name__ == “__main__” mean?

Madhu Shree Aravindan
Nerd For Tech
Published in
2 min readDec 20, 2023

We all have come across if __name__ == ‘__main __’: in python codes found online. Ever wondered what it means…

Whenever the Python interpreter reads the source file, it sets a special variable “__name__” to “__main__”.

Source File

Whenever it reads an imported file, it sets the variable “__name__” to the name of the file.

File_One.py
File_Two.py

Now that we have understood the meaning of the variable “__name__”. Let’s see what if __name__ == ‘__main__’: means and its significance.

File_One.py
File_Two.py

As we can see File_One.py has produced the output we expected but File_Two.py did not.

File_Two.py should have produced this

But, instead, it has produced the output of File_One.py and File_Two.py This has happened because Python executes all the code present in both the source file and the imported file.

To avoid it we are using the __name__ variable.

File_One.py
File_Two.py

I hope this explanation provides a clear understanding of why we use if __name__ == ‘__main__’:

--

--