What if __name__ == “__main__” does:

Python Methods and Functions

Before executing the code, the Python interpreter reads the source file and defines several special / global variables. 
If the python interpreter runs this module (source file) as its main program, it sets the special variable __name__ to "__main__" . If this file is imported from another module, __name__ will be set to the module name. The module name is available as a value for the global variable __name__. 
Module — it is a file containing Python definitions and statements. File name — this is the name of the module with the .py suffix appended. 
When we execute the file as a command for the Python interpreter,

 python script.py 

# Python program to run
# main directly

print " Always executed "

  

if __ name__ = = "__ main __" :

print "Executed when invoked directly"

else :

print "Executed when imported" < / code>

  • All code that is at indent level 0 [ Block 1] is executed. Certain functions and classes are, well, well defined, but none of their code gets executed.
  • Here, as we executed script.py directly, the __name__ variable will be __main__ . So the code in this case if the block [Block 2] will be executed only if this module is the entry point into your program.
  • This way you can check if your script is executed directly or imported than something else by checking the __name__ variable.
  • If the script is being imported by another module at the time, __name__ will be the name of the module.

Why do we need this?

For example, we are developing a script that is intended to be used as a module:

# Python program to run
# function directly

def my_function ()

print "I am inside function"

 
# We can test the function by calling it.
my_function ()

Now if we want to use this module when importing, we have to comment out our call. Instead, it is best to use the following code:

# Python program to use
# main for function call.

if __ name__ = = "__ main__" :

my_function ()

 

import myscripy

 
myscript.my_function ()

Benefits :

  1. Each Python module has __name__ defined, and if it is __main__ it means the module is running is autonomous by the user and we can take action.
  2. If you import this script as a module in another script, __name__ will be set to the name of the script / module.
  3. Python files can act as reusable modules or as standalone programs.
  4. if __name__ == "main": used to execute some code, only if the file was run directly and not imported.

This article is provided by Nirmi Shah . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you'd like to share more information on the topic discussed above.





Tutorials