__name__ is a special variable that you may have seen it many times in documentation and other places. Use of which may be still a blur while writing your Python programs. Well, Today we’re going to remove that blur with a proper explanation.
Basically, there is a certain variable in Python which gets assigned before any of the calling or definition. In those certain variables, one such variable is __name__ which is a Dunder variable (or double underscore in the name). This Variable before everything happens gets assigned to value ‘__main__’ (a string).
Let’s say, you are currently working on a file called module1.py. Now, whichever callable functions use [eg: print()] in your file, when you run those then that will run directly with Python because you are not importing it and things happen to be already in your current file. And when you switch to another module then modules you switch to become main.
In short, the meaning is, value ‘__main__’ gets assign to special variable __name__ of the file you are switching to. When you switch to another file module2.py, then __name__ of that file becomes ‘__main__’. And the imported modules variable __name__get assigned to its module name.
When you use if __name__ == ‘__main__’ then contents under it, like for example:
if __name__ == '__main__ ':
Above, two functions are for printing work only, in the condition when the file it is on, is running as a standalone file. Now if you try to import this module into another python code, then those two print methods will not run automatically as you import.
When you use contents like a print function without checking whether __name__ is __main__ then regardless of the file running directly or as imported, those contents will get executed or printed. In the Below tutorial, you may become more clear.
__name__ == ‘__main__’ Video
Helpful? Read more python-environments related articles here.