DEV Community

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

Kelvin Wangonya on August 03, 2019

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 expla...
Collapse
 
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.

Collapse
 
thefern profile image
Fernando B 🚀 • Edited

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.

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

Collapse
 
wangonya profile image
Kelvin Wangonya

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? 😅

Collapse
 
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
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode
Collapse
 
orenovadia profile image
orenovadia

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
Enter fullscreen mode Exit fullscreen mode
Collapse
 
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.

stackoverflow.com/q/419163/1013828

Collapse
 
linehammer profile image
linehammer

By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves. Consider the following code for better understanding if name == "main", it checks if a module is being imported or not.

print "program started"
if name == "main":
print "This is from main module"
else:
print "This is from imported module"

net-informations.com/python/iq/mai...

Collapse
 
shamimahossai13 profile image
Shamima Hossain

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

stackoverflow.com/questions/419163...