re: What's the use of if __name__ == '__main__': in Python? VIEW POST

re: Assume you have two scripts, and, and you want to import code from into If you don't add the if _...

If you don't add the if __name__ == '__main__': condition in, then all of its code will be executed when importing it

This statement is not quite right, when importing a script into another script, it will not get executed, it will be imported big difference you still have to call its functions.

However if script_1 is imported in script_2 as you described, and script_1 is calling functions at the bottom of the script then yes I agree it will execute all its code but you are still calling it, if you import script_1 and all you have is functions nothing will get executed, just wanted to clear that bit which is very important. Even if you have a main, and you call functions they will get executed regardless.

I've created a gist to demontrate this. python

Note on my example both scripts have mains, but because I am calling script_1 only its main gets called along with any other functions called explicitly in both scripts. However note that script_2 doesn't call its main because I am not running python Hope this makes sense.

code of conduct - report abuse