I had a confusion regarding if __name__ == "__main__": in Python and came across the same question on SO: What does if name == "main": do?
Thanks to the most voted, detailed, and helpful answer by Mr Fooz, my understanding has improved. However, I'm still confused in one of the code blocks in the same answer:
foo3.py:
Note: Instead of the code block, I've put a snapshot because it has line numbers. Through that, I think I can properly explain what my current understanding is and what my confusion is!
From my understanding, upon running python3 foo3.py:
- print
t1(line 14) - print
t2 - call
functionA - print
a1 - invoke
foo3as a module (line 6) - So, print
t1again - print 'm1` again
- call
functionAagain - print
a1again - invoke
foo3as a module again - ...
- ...
So, basically, a neverending t1 ... m1 ... a1 ...:
t1
m1
a1
t1
m1
a1
t1
m1
a1
.
.
.
I was expecting such infinite output because there is no __name__ == "__main__" check in foo3.py and it keeps invoking itself in functionA.
However, when I run this code, I get the following finite output:
t1
m1
a1
t1
m1
a1
a2
b
a3
m2
t2
a2
b
a3
m2
t2
I still don't understand why!? Shouldn't there be an infinite output? Could anyone please explain the program sequence in the above code snippet?
