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

twitter logo github logo ・1 min read

So I'm doing this series and I want to make it as beginner-friendly to Python newbies as possible. I just wrote a piece of code and I want to explain what each line does, but I just can't figure out how to explain if __name__ == '__main__': simply. I mean, I use it all the time but I'm having a hard time explaining it in a way that someone who's just getting into Python would understand. The explanations I'm getting online aren't helping so... someone please #explainlikeimfive 😄

twitter logo DISCUSS (11)
markdown guide
 

The main reason is because importing a module runs it. However, a module's __name__ attribute is only set to "__main__" if it was executed directly, instead of imported.

Thus, you can write a module to run by itself, but also import it without having it try to run as if it were the main script.

Consistency is important besides, so we just conventionally use the if __name__ == '__main__': syntax, even if we don't think we'll need it. There are exceptions, but you should default to using it until you have a reason not to.

 

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.

 

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.

 

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.

 

Unlike the C family of languages, where program execution starts with the main() function... Python allows code that isn't in a function or class at all. If you import a module containing such code, it will be executed. If this isn't desirable, for example because it's intended to only get used when the module is run directly, putting the code behind a if __name__ == '__main__': guard does exactly that!

 

Quite simply stated, if you are importing code from another module—and that module contains the code snippet

if __name__==‘__main__’: #code goes here

—if you execute your (first) program/script, all of the code from that other (second) module/program/script, minus/without the code in that particular

if __name__==‘__main__’: #code goes here

section, will be parsed and executed.



To further clarify, all of the code in the other/second program’s

if __name__==‘__main__’: #code goes here

section (from that first line of that section, parsing downwards) shall not be “seen”/executed when executing the first program.


Ergo, it is primarily utilized for testing- or debugging-based purposes specifically involving code imports/importing, as above-mentioned.


However, note this: if you execute that second program’s code/the second program itself, all of the code inside that second program—including its

if __name__==‘__main__’: #code goes here

section—will, indeed, be “seen,” or executed. Such an example would be a “print” statement, such as print(“Neat-o”).


That was a fantastic question—I hope my explanation clarifies it for you! 😊

 

Broadly speaking, it is the entry point of a python script or program and is comparable to the void main() of C++ or public static void main() of java.

Specifically, the __name__ built-in makes your module "know" whether its directly executing as a script/program or being imported as a module in another module. When its directly run, the built-in has a value of "__main__" and thus the following condition will hold true:

if __name__ == "__main__":
    pass # do something

But if your module is being imported into another module, the above won't be executed and your module won't do anything (assuming everything else in your module are just functions and classes, and no directly executing code). But if you don't place the above if condition, then whatever is inside that block (# do something) will run each time irrespective of whether your module is executed directly or being imported.

Personally, I prefer to wrap the entire logic inside a main() function as a standard boilerplate while creating a runnable module. It looks more neat and readable:

def main():
    # do something

if __name__ == "__main__":
    main()
 

Personally, I prefer to wrap the entire logic inside a main() function as a standard boilerplate while creating a runnable module. It looks more neat and readable

I agree that it is more neat, but more than that:

  1. It is faster
  2. It doesn't pollute the global namespace

For example, this foo function will work only if it the file is executed directly, but not if it is imported (bad, confusing and inconsistent):

def foo():
    for i in range(N):
        yield i

if __name__ == '__main__':
    N = 5
 

The way I think about it, is as a main method like in c++. Unless you have another 'main' on another module and import it somewhere else in that case main will not execute. So is safe to assume that you should only have one main entry point in your whole program.

I think the best way to explain it to a beginner would be to write some script without using main, and another script with using main running it and seeing the execution results in the console. At least that's how I learn stuff lol.

Here's an overcomplicated answer on SO.

stackoverflow.com/q/419163/1013828

 

I found this stackoverflow answer quite helpful. You might wanna check out as well

stackoverflow.com/questions/419163...

Classic DEV Post from Jun 6

What programming best practice do you disagree with?

Discussion about an unusual interview question

Kinyanjui Wangonya profile image
👨🏾‍💻

dev.to is where software developers stay in the loop and avoid career stagnation.

Sign up (for free)