Pages

Wednesday 28 January 2015

Python_Programming :: What Does if __name__ == '__main__' means ??

So, friends today i'm gonna explain what actually the code in the picture below do in python programming ..

This piece of code is very much important in one particular situation to check whether you directly run your program or it's being imported as a module consider the pictures below

I have created a python program named 'independent.py' as you can see if __name__ == '__main__' then python interpreter will print "I am running as a Independent program!" else it will run as "I am running as a module!"

Lets check what result python interpreter gives when we print __name__ in the shell

as you can see __name__  == '__main__'
so when we run independent.py we will see "I am running as a Independent program!"


Let's check another case when i will create another python program named imported.py in which i will import independent.py

Now i'm gonna run this python program and see what this program will give result! 


And output is "I am running as a module"
This is quite usefull in one particular case when your if statement is something like this 

if __name__ == '__main__': main()

In this case if you are running it as a main program then your main function will execute and if u just wanna use functions of this independent.py programs in some different program i.e. imported.py then main() function of the imported program will not get executed and you will only get access to other functions except main().

I guess now it's quite clear :D
Thanks for giving your valuable time on reading this post :)
Happy Programming ! (Y)