I am using the accepted answer to this question to get a better understanding of why it should be necessary to use the if __name__=='__main__'
construct in Python. What I understand from the answer is, that if foo.py
is run from the command line using python foo.py
then the variable __name__
is assigned a value of '__main__'
, and so everything in the if __name__=='__main__'
block is executed.
On the other hand, if the module is imported from another script using import foo
then __name__
is assigned a value of "foo"
. Therefore the stuff in the if
block is not executed.
The answer then shows an example using foo2.py
and foo3.py
and suggests comparing the results. The code for foo2
is:
# Suppose this is foo2.py.
def functionA():
print("a1")
from foo2 import functionB
print("a2")
functionB()
print("a3")
def functionB():
print("b")
print("t1")
if __name__ == "__main__":
print("m1")
functionA()
print("m2")
print("t2")
The code for foo3
is:
# Suppose this is foo3.py
def functionA():
print("a1")
from foo3 import functionB
print("a2")
functionB()
print("a3")
def functionB():
print("b")
print("t1")
print("m1")
functionA()
print("m2")
print("t2")
I then ran both using python foo2.py
and python foo3.py
respectively. These are the results that I got:
(base) D:\TEMP\try>python foo2.py
t1
m1
a1
t1
m1
a1
a2
b
a3
m2
t2
a2
b
a3
m2
t2
I am a bit confused on the second one (foo3.py
). When functionB
gets imported I was expecting
t1
m1
a1
t1
m1
a1
t1
m1
a1
... to infinity
since nesting functionB
in functionA
would result in infinite recursion. However python "knows" somehow to avoid this...
What is the logic here? How does this not occur?