Using if __name__ == '__main__'
The '__name__' variable
Let us try to take the example of the 'my_py_library.py' that we created in the previous section.
Here we will try to print a special variable called '__name__' by executing the library file itself.
The code is as below :
Code Output : When we directly executed the library file, the value of the '__name__' variable can be observed as __main__.
Now lets try to import the library from another python file, as shown below :
Here we are also trying to print the '__name__' variable from this file as well.
Code Output :
Something strange has happend here. Now the '__name__' variable for the library file is printing as its filename and the '__name__' variable for the python file called is now '__main__'.
This is because, 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.
This feature can be used to guard the execution part of files. Thus allowing execution to run only if the files are executed individually or specifically, but if they are imported as part of some other python file, their individual processes will not execute.
This can be done by checking for the '__name__' variable inside the file to be '__main__' and keep any execution inside the block only if the check passes.
Refer below modified code for the library file, this time it has a checker to check if the __name__ variable is '__main__' :
Code Output : Now when we try to execute this file individually we get.
Now we will try importing the above library file with a modified version of the main file which also has the checker for variable '__name__' implemented. Code is shown below :
Code Output :
As can be observed now that none of the library's executables are now printed as they were never executed since all further execution was guarded by the checked in the library file.