DEV Community

Kinyanjui Wangonya
Kinyanjui Wangonya

Posted on

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

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 πŸ˜„

Discussion (11)

codemouse92 profile image
Jason C. McDonald

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.

ioan profile image
Luca Ionescu • Edited

Assume you have two scripts, and, and you want to import code from into

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

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

thefern profile image
Fernando B πŸš€ • Edited

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.

wangonya profile image
Kinyanjui Wangonya Author

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

Nice explanation.

It also indicates the starting point of the script when executing 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():


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? πŸ˜…

ioan profile image
Luca Ionescu • Edited

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.

wrldwzrd89 profile image
Eric Ahnell

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!

king profile image
πŸ‘‘ • Edited

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! 😊

prahladyeri profile image
Prahlad Yeri • Edited

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__":
orenovadia profile image

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
thefern profile image
Fernando B πŸš€

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.

shamimahossai13 profile image
Shamima Hossain

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