Wednesday, September 8, 2021

Understanding if __name__== '__main__'


What is __name__ in Python?

__name__ is an entry point or starting point of a python program execution, likewise main() method in C and C++. Every .py file will have this special variable. check the below program.

Program:

#cat name.py
print(__name__)


Here we can clearly notice we didn't initialise "__name__", but we are trying to print it

#python3 name.py
'__main__'


Without initialising the "__name__ " we got output as "__main__" 

Where we use if __name__== '__main__' ?

We will try to understand the below example. We have two python files sample_module.py and sample_test.py and we will try to run the sample_test.py

sample_module.py
-----------------------
def add(a,b):
    return a+b
print(add(10,20))


sample_test.py
------------------
from sample_module import add
print(add(50,50))


python3 sample_test.py
30
100

We ran sample_test.py, in that file we are trying to add two numbers ie 50+50, So we should get 100 as output. But we got 2 values in the output ie 30 and 100

From where we are getting 30 as output? 

In the sample_test.py we are importing sample_module. In that module we are calling the function add(10,20)

So here we need to understand the basics, while importing any file it will execute first, that's why add(10,20) is called and we are getting 30 in the output

__name__ values defers from one file to another, the current file gives "__main__" value and if we import that file to another file then it will give python file name.

sample_test.py
-------------------
import sample_module
print(sample_module.add(50,50))
print(sample_module.__name__)

python3 sample_test.py
100
sample_module

To overcome this we will write a if condition in sample_module.py as below.

sample_module.py
-----------------------
def add(a,b):
    return a+b
if __name__ == "__main__"
    print(add(10,20))

sample_test.py
------------------
from sample_module import add
print(add(50,50))

So now we will try to run sample_test.py

python3 sample_test.py
100

why 30 is not printing in the output? if __name__ == "__main__" condition checks whether the current file is executing or not. So that the condition is failed so it's not printing 30