Use of if __name__ == '__main__' : Explained, When to use, How to use ?

Post a Comment

If I guess, you may have seen the checking the __name__ much time in documentation and other places. Use of which is still may be a blur while writing your Python programs. Well, I wish to remove that blur with proper explanation.

Basically, there is 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 under 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, whatever callable things like (print()) your file has when you run those then that will said to be 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 file then file you switches to becomes 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__. the file name currently working becomes main.(i just repeated that again, for understanding).

When you use if __name__ == '__main__' then contents under it, like for example:

if __name__ == '__main__ ':    
        print(sys.version)
        print("hello")

Above, two contents of printing work only in condition when file it is on is running as a standalone file and not as the file which is imported into another file.

When you use contents like print function without checking whether __name__ is __main__ then regardless of file running directly or as imported, those contents will get executed or printed. In Below tutorial, you may become more clear.




Y Aakash
Hello World, I Dwell with Creative Sketching, Coding, Finance & Blogging by putting my Views and Work.

Related Posts

Post a Comment