Monday, July 24, 2017

What does python interpreter deduce while executing - If __name__ == “__main__”: ?

Unlike other programming language there is no main() function that runs automatically when you execute a python program. The python interpreter execute all the codes found it in source file and during execution it defines few special variable.
Take an example for below code:
'''
File Name: Sample1.py
Author:ppmishra
'''
def add(i,j):
    return i+j
if __name__ == "__main__":
    print "I am running as :",__name__
    print "The sum of 2, 3 is:",add(2,3)
else:
    print "I am imported to another module. My Module Name is:",__name__
When the above source file (named as Sample1.py) gets executed, python interpreter running this as main program and set special variable name as “__name__” to a value “__main__”. After successful execution the output will be as below:
I am running as : __main__
The sum of 2, 3 is: 5
You can see the else part is not executed for Sample1.py.
So when does special variable “__name__” set to different value other than “__main__”? Well, if the file is being imported from another module then “__name__” set to module’s name.  
Let’s import our above file ‘Sample1.py’ in to different file, say ‘Sample2.py’.
'''
File Name: Sample2.py
Author:ppmishra
'''
import Sample1
def multi(i,j):
    return i*j
if __name__ == "__main__":
    print "I am not imported to any module and I am :{0}.I do multiplication of 2,3 whose result is:{1}".format(__name__,multi(2,3))
else:
    print "I am imported and I am:",__name__
When the above code is executed, python interpreter first execute line 1 , i.e. import Sample1 set “__name__” to module name , in this case Sample1. However when interpreter starts executing 4th line of Sample2.py it sets the value of “__name__” to “__main__”.
After successful execution the final output of Sample2.py  will be:
I am imported to another module.My Module Name is: Sample1

I am not imported to any module and I am :__main__.I do multiplication of 2,3 whose result is:6

No comments:

Post a Comment