Skip to main content

If __name__ == “__main__” Usage in Python

In our previous Python tutorial, we have explained about *Args and **Kwargs in Python. In this tutorial, we will explain about __name__ in Python.

We mostly see the __name__ variable like below code when gone through the Python code. This is a special variable in Python that used to create modules.

if __name__ == '__main__':    
	main()

When we run Python script, the __name__ variable is always equals __main__ for that script.

So question arises, why and when we need to use this special variable in our code. Sometimes we write a script with functions that might be useful in other scripts as well. In Python, we can import that script as a module in another script.

With __name__ special variable, we can decide whether we want to run the script or want to import the functions defined in the script.

So let’s see the scenarios of using the __name__ variable in our code:

Scenario 1: Execude If __name__ Equals __main__

Here we have Python script script_1.py and define functions and caling within __name__ condition.

script_1.py:

def some_fun():
    print("I am handling a lot of functions!!!")


def main():
    some_fun()

if __name__ == '__main__':
     main()

When run above code, the __name__ variable is set to __main__. It is checking for __main__ in if condition. The if condition will be true here, the main() and then some_fun() statements will be called and print message .

Scenario 2: Importing Script AS Module

If we want to re-use some_fun() in another script, for example script_2.py, we can import script_1.py as a module.

script_2.py:

import script_1 as scr

scr.some_fun()

Here we have two scope. In script_2.py, the __name__ variable is set to __main__. We have imported script_1.py as module and called some_fun() from module. When we run the above code, the def statement for main() and some_fun() will be run. But the condition will evaluate to false and main is not called.

As we have called some_fun() in script_2.py which output script_1.py because it is known to that function when the function was defined.

Conclusion

In this tutorial, we have explained how you can use the __name__ variable in different scenarios to write code. Hope you have enjoyed this tutorial and try same at your end. Cheers!