Introduction to the name Variable

if __name__ == '__main__': main While reading or writing Python code you have more than likely come across the __name__ variable before. In this post we are going to be looking in to what it actually does and how you can use it to create modules in Python.

What is it used for?
The  __name__ variable is a special Python variable that gets its value depending on how we execute the containing script.

Someimes when we write a Python script containing functions we may want to use that in other scripts as well, in Python we can import said script as a module in another script.

And so thanks to this special variable, we can decide whether we want to run the script or if we want to import the functions defined in the script.

What values can it contain?
When we run our script, the __name__ variable equals __main__. When you import the script, it will contain the name of the script.

Let's look into these two scenarios in more detail:

Run the script
Suppose we had a script nameScript.py, and it looked like the following: def myFunction: print('The value of __name__ is ' + __name__) def main: myFunction if __name__ == '__main__': main If you run this script the process below is followed:



Before any other code is executed, the __name__ variable is set to __main__. After that, the  main and  myFunction def statements are run. Because the condition evaluates to true, the main function is called. This in turn calls myFunction. Which then prints out the value of  __main__.

Import the script in another script
If we want to re-use myFunction in another script, for example in importScript.py, we can import nameScript.py as a module. The code in importScript.py would look as follows: import nameScript as ns ns.myFunction We then would have two scopes: one of importScript, and the second scope of  nameScript. In the illustration you can see how it differs from the above case:



In importScript.py the  __name__ variable is set to <span style="color:rgb(102,255,102);">__main__. By importing nameScript, Python starts looking for a file by adding <span style="color:rgb(102,255,102);">.py  to the module name. It then runs the code contained in the import file.

But this time is is set to nameScript. Again the def statements for main and myFunction are run. But now the condition evaluates to false and main is not called.

In importScript.py we call myFunction which outputs nameScript. nameScript is known to myFunction when that function was defined.

If you would print <span style="color:rgb(102,255,102);">__name__ in importScript this would output  <span style="color:rgb(102,255,102);">__main__. This is because Python uses the value known in the scope of importScript.

Conclusion
In conclusion, we wen't through how you can use the <span style="color:rgb(102,255,102);">__name__ variable to write modules or run modules on their own. All done by making use of how the values of these variables change depending on where they occur.