Since there is no main() function in Python, when the command to run a python program is given to the interpreter, the code that is at level 0 indentation is to be executed. However, before doing that, it will define a few special variables. __name__ is one such special variable. If the source file is executed as the main program, the interpreter sets the __name__ variable to have a value “__main__”. If this file is being imported from another module, __name__ will be set to the module’s name.
Module in Python is nothing but a program that can be included(imported) in other programs, so that the functions and operations defined in the module can be reused in the program that you are writing.
Consider below example
# myModule.py def printsomething(): print "Hello!. Welcome!" printsomething() # Program import the above module #cat myProgram.py import myModule myModule.printsomething() # Program Output $python myProgram.py Hello!. Welcome! Hello!. Welcome!
In the above output, one is coming from the “printsomething()” inside “myModule.py” and the second is coming from the line “myModule.printsomething()” inside myProgram.py. This is because when python encounters the import statement, it executes it, so that the functions and other attributes are then available to the current program where you are importing it.
Below change will cause printsomething() to be executed only when myModule.py is executed directly (ie: python myModule.py).
#cat myModule.py def printsomething(): print "Hello!. Welcome!" if __name__ == "__main__": printsomething() # Program output $python myProgram.py Hello!. Welcome!
The line if
__name__ == "__main__": tells the program that the code inside this if statement should only be executed if the program is executed as a standalone program. It will not be executed if the program is imported as a module. __name__ is by default set to the value of __main__ in python. But when the module is imported, __name__ variable now has the value of “myModule”. Any program in python that is imported as a module will have __name__ variable set to the name of the module. In all other cases it will be the default value of __main__
>>> >>> print __name__ __main__ >>> >>> import myModule >>> print myModule.__name__ myModule >>> >>>