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

FULL DISCUSSION
 

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 __name__ == '__main__': condition in script_1.py, then all of its code will be executed when importing it in script_2.py.

Including if __name__ == '__main__': in script_1.py will allow you to import its code without execution.
It also indicates the starting point of the script when executing script_1.py on its own.

 

Hey Luca. Thanks for taking the time to help me out.

Nice explanation.

It also indicates the starting point of the script when executing script_1.py on its own.

I had actually thought of saying it like this, but then I doubted if it was really very correct since it kinda implies that it has to be there because it's the starting point of the execution. If I was a complete beginner, I'd take that to mean that a program without that part wouldn't run since the script doesn't have a starting point to execute from.

Here's what I mean. Consider this code for example:

def hello():
  print("hello!")

hello()

The code works just fine without the if __name__ == '__main__':. What's the starting point of the script when executing that code on its own?

Maybe I'm overthinking it? 😅

 

Hey Kinyanjui, you're absolutely right, the line does not have to be there.

If you want to use your script in two ways, execute it on its own and import it in another script, that's when you need to include if __name__ == '__main__':. Otherwise you don't need it.

 

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