__name__ is a special variable which is created when any module runs standalone or imported. You’ve most likely seen the __name__ variable when you’ve gone through Python code. Below, you see an example code snippet of how it may look.
Whenever we execute any Python file, the Python interpreter first creates some special variables as mentioned below.
- __annotations__
- __builtins__
- __cached__
- __doc__
- __file__
- __loader__
- __name__
- __package__
- __spec__
Whenever we run C, C++, Java, C#, etc. programming language codes, first, the main function code is executed. Since there is no main() function in Python, when a module(file) is executed, Python interpreter creates one special global variable __name__. By default, its value is set to __main__.
Printing all the global variables
To print all the variables which are listed above, create one Python file like example.py. Now, you can write the following code.
Now, save the example.py. When you run this file, you will get all the global variables like in the following image.
Default value of __name__
By default, when we execute a Python module(file), the default value of the __name__ sets to __main__. In the following example, I am printing the default value of __name__.
- print("Default value of the __name__ is : "+__name__)
output
When we import the module, then the value of the __main__ for the module will be the module name. An example is as follows.
I am creating two Python files - example.py and my_module.py file. For both, the code is given below.
my_module.py
- print("Default value of the __name__ is : "+__name__)
example.py
Use of __name__
Now, the biggest question is where we should use the __name__ variable. As we already know, we don't have a main function in Python, but if you want to create a main function, we can create using __name__. You might have seen the following code.
- if __name__ == "__main__":
It is also used to print the module name.
How do Python programmers use the main function?
In the following code, you can see how a Python programmer uses the main function.
- def main():
- print("Hello from main function")
- foo()
- bar()
-
- def foo():
- print("Hello from foo function")
-
- def bar():
- print("Hello from bar function")
-
- if __name__ == '__main__':
- main()
Output
Conclusion
Every Python module has its __name__ defined. If its value is __main__, that means the module is being run standalone by the user and the user can take the appropriate action for that main function.
Thank you. Hope you like this article. We will discuss all the global variables which are listed above in my upcoming article.
If you are new to Python programming, you can find Python articles here.
I have also written some articles which are listed below.