Python - Use of "__name__" variable

A snippet detailing the use of the "__name__" variable in Python

Python - Use of "__name__" variable

Hey, folks let's look at the usage of "__name__" in this snippet. Let us try to print the variable from a python program called code1.py

print(__name__)

On running this we get,

Python loads a few Environment variables before it starts executing the code that you have given it to execute.  The "__name__" variable is one such special variable. Here we ran the code directly by executing code1.py and therefore python has set the "__name__"  variable to main.

Let us now import the code1.py python module into another python program called code2.py. Now we all know that python runs the complete code when we import a module into another module. Now let's test how the "__name__" variable behaves when the code1.py is imported in code2.py

import code1

code2.py has only the above-mentioned piece of code. So, let us run this and compare it with what we got when we execute code1.py

Look at that!. We now have code1 as the output when we ran code2.py.

INFERENCE

The "__name__" variable is initialised with main if the code is directly run by python. On the contrary when the code is imported and internally run by python; the "__name__" is initialised with the name of the imported module. That is why we got code1 as the output of the print function when it was imported by code2.py.

USECASE

if __name__ == "__main__":
	{
    "Place the code that you want to run if this module is executed directly"
    }
else:
	{
    "Place the code that you want to run if this module is imported"
    }

A check condition using an if statement such as the one mentioned in the above example can be incorporated whenever we want certain things to be done only when the module is executed directly. Whatever code we put inside this check statement will not be executed when this module is imported into another module.

Drop-in your comments if you find this snippet useful. Bye!.

Subscribe to RouteSwitch

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe