Python - Use of "__name__" variable

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

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


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 and therefore python has set the "__name__"  variable to main.

Let us now import the python module into another python program called 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 is imported in

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

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


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


if __name__ == "__main__":
    "Place the code that you want to run if this module is executed directly"
    "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!.