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

TOP OF THREAD FULL DISCUSSION
re: Assume you have two scripts, script_1.py and script_2.py, and you want to import code from script_1.py into script_2.py. If you don't add the if _...
 

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

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 script_1.py

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 script_2.py. Hope this makes sense.

code of conduct - report abuse