How “If __name__ == ‘__main__' ’” Works?
Raju Nekadi
Posted on April 29, 2024
Solving the mystery of If __name__ == '__main__'.
Let's assume you have a python script first.py
# first.py
print('Hola from first.py')
if __name__ == '__main__':
print('Hola first module __name__:' __name__')
# output
# Hola from first.py
# Hola first module __name__: __main__
If we run first.py using the command Python
python first.py, the __name__ variable for first.py will automatically become __main__.
# second.py
print('Hola from second.py')
if __name__ == '__main__':
print('Hola second module __name__:' __name__')
# output
# Hola from second.py
# Hola second module __name__: __main__
Similarly, if we run second.py using the command python second.py, the __name__ variable for second.py will automatically become __main__
What if we have 2.py files
#second.py
def hola_second():
print('hola_second__name__:',__name__)
# first.py
from second import hola_second
hola_second()
def hola_first():
print('hola_first__name__:',__name__)
# python first.py
# hola_second__name__: second
# hola_first__name__: __main__
And in first.py, we import a function from second.py. And in this function in second.py, we print __name__. And we run first.py directly using python first.py (note that second.py is not run directly)
Since we run first.py directly, only __name__ in first.py will be '__main__'. The __name__ imported from second.py will be 'second' instead of '__main__'.
Now what does adding if __name__ == ‘__main__’ do
# second.py
def hola_second():
print('from second.py:', __name__)
if __name__ == '__main__':
print('I am second')
# first.py
from second import hola_second
hola_second()
Notice that I am second is no longer printed.
And this is because of the if __name__ == '__main__' statement we’ve put in second.py. Whatever is inside this if block will only run if we run the Python script directly.
In this case, print('I am second') will only run if we run second.py directly, meaning that we use the command python second.py.
Conclusion
if __name__ == ‘__main__’ is used as conditional statement to allow only run code that we want to run.
Some Final Words
If this blog was helpful and you wish to show a little support, you could:
1. 👍 300 times for this story
2. Follow me on LinkedIn: https://www.linkedin.com/in/raju-n-203b2115/
These actions really really really help me out, and are much appreciated!
Posted on April 29, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.