I have just started learning Python and came across the code if __name__ == '__main__':
I have two python modules.
- one.py
- two.py
In one.py:
import two
def func_in_one():
print('function from one.py')
print('Top level in one.py')
if __name__ == '__main__':
func_in_one()
two.func_from_two
In two.py:
print('Top level in two.py')
def func_from_two():
print('function from two.py')
On terminal, when I run python one.py
I see the following output
Top level in two.py
Top level in one.py
function from one.py
function from two.py
From what I understood __name__ == '__main__':
is used to organize the code like setting up the order of calling methods & imported methods we want to.
In that block of code I am first calling func_in_one()
and the zero indention code takes priority.
The function func_in_one()
from my one.py is the first executed statement instead Top level in two.py
gets printed and then comes Top level in one.py
and function from one.py
and at last function from two.py
is printed.
If I am calling func_in_one() and it is in the current module of my .py file, why is the output not
Top level in one.py
function from one.py
Top level in two.py
function from two.py
This is my first time using __name__ == __main__
and it is a bit confusing. Could anyone care to explain the execution pattern here ?