__name__ in Python
As we know that Python does not have a main() function like C and C++. When the interpreter runs the program, code at level 0 indentation(very first line) starts executing. Before executing the code, the interpreter defines a special variable i.e. __name__.
If you are not familiar with __name__ don’t worry this post is for you. Follow the tutorial to understand the role of __name__ in Python.
Also read: Packing and unpacking arguments in Python
Note: __name__ variable is not available in the Python version below 3.x.
__name__ in Python
In Python, __name__ contains the name of the current module. If the same module is executing then the __name__ variable contains the “__main__” otherwise it contains the name of the module imported.
Suppose we have a Python program file name “codespeedy.py”. When we run the file “codespeedy.py” the value of __name__ will be “__main__”. Another file with “tech.py” is made and if we import “codespeedy.py” in “tech.py” the value of __name__ will be module name i.e. “codespeedy”.
For better understanding, let’s see an example. As described above create the first file with the name codespeedy.py.
def display(name): print(name) print("__name__ value=", __name__) print("Displaying Name:") if __name__ == '__main__': display("Vimal Pandey")
Output:
__name__ value= __main__ Displaying Name: Vimal Pandey
Now create the second file tech.py and import the first file codespeedy.py in it.
import codespeedy codespeedy.display("Python Programming")
Output:
__name__ value= codespeedy Displaying Name: Python Programming
When the tech.py is executed then the value of __name__ changed to codespeedy from __main__.
That’s why if__ name__ ==”__main__” is used to prevent the ceratin lines of code from being imported into another program.
Please comment below if you find anything incorrect. If you have any other doubts related to this topic or any other topic comment below your problem. We will definitely help you with an easy solution.
Leave a Reply