Why __main__ checking is important

Posted by Afsal on 29-Dec-2023

Hi Pythonistas!

Today we are going to find why __name__ == ”__main__” checking is important. We can see this code mainly in standalone scripts. Most of us follow this standard without knowing the purpose of that code. Today, check why it is important.

We have script called without_main_check.py

Code

def hello_world():
    print("hello world")

hello_world()

When we run this code we get “hello world” as the output

We have another script with_main_check.py

Code

def hello_world():
    print("Hello world")

if __name__== "__main__":
    hello_wolrd()

When we run this code we get “hello world” as the output.

Both the script works the same if run this script as standalone. The difference happens when we are importing the module. Let us import these in interpreter and see the result

>>>
>>> import without_main_check
hello world
>>> import with_main_check
>>>

We can see that when we import the module without a main check the hello_world function gets executed. But in the second case the function is not getting executed. So the main check is important in your code even if you're planning this as a stand alone script.

I hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in