What is Python __name__?
Overview
In this article, we shall learn about Python \_\_name__ . \_\_name__ is a special variable in Python that stores the name of the python module/script currently being executed. It was introduced in version 3.0 of Python. If the current script/module is in execution then the Python \_\_name__ variable is assigned the value \_\_main__. Otherwise, the name of the script or module in execution is stored in the \_\_name__ variable.
What is __name__ Variable in Python?
Unlike many other programming languages, Python does not have a main() function. When the interpreter has to begin executing a Python script, the code present at level0 of indentation is executed. The interpreter must first define some special variables, one of which is \_\_name__.
If the file of source code is in execution as the main program, the interpreter assigns the value \_\_main__ to the Python \_\_name__ variable. Otherwise, that is, if the code in execution has been imported from some other script/module, the name of the module is set as the value of the \_\_name__ variable.
Since the Python \_\_name__ variable is inbuilt and yields the name of the module currently in execution, we can use it for determining whether it is the current file that is being executed, or some other imported module, possibly in combination with current file’s code, for example in an if statement, etc.
Using __name__ == __main__
Say we command the Python interpreter to start executing a Python file, say “pythonScript.py”. Assume the following are the code contents of our Python script:
All the code at level 0 indentation is executed. Output
Since we directly executed the pythonScript.py file, the Python variable \_\_name__ is set to value \_\_main__. The code in the else block runs only if the code in execution is imported. Hence, one may verify whether directly one’s script is executing or some imported script/module.
Printing the Value of __name__ in Python
Let's print the value of the __name__ variable at each stage of execution to help you understand it better.
Example: The python code file pythonScript.py is described below :
Output:
Examples of Using __name__ in Python
The following code block prints the name of the currently executing script, which is __main__:
Output
The following code block prints the data type of the \_\_name__ variable:
Output
The following code block depicts the behavior of Python \_\_name__ in imported modules: myModule.py:
main.py:
Output
Learn More
You may want to have a look at many cool Python articles here
Conclusion
- \_\_name__ is a special variable in Python that stores the name of the python module/script currently being executed.
- Since the \_\_name__ variable is inbuilt and yields the name of the module currently in execution, we can use it for determining whether or not it is the current file that is being executed.