/  Technology   /  What does if __name__ == “__main__”: do in Python?
What does if __name__ == “__main__”: do in Python

What does if __name__ == “__main__”: do in Python?

 

While going through many Python scripts online, we often find if__name__==”__main__”: statement. In this article, let us know what exactly this statement means.

 

__name__ is a special attribute that belongs to the list of attributes in dir().

 

Example:

dir()

Output:

 

The __name__ attribute defines the name of the class or the current module or the script from which it gets invoked. When we run a Python script or import our code as a module, the Python interpreter automatically adds this value to it.

 

When we execute a file/ source code script directly, the Python interpreter by default reads the script and assigns the string __main__ to the __name__ keyword and not the name of the file.

Example:

print(f'The __name__ from script_1 is "{__name__}")

Output:

 

 

Whereas when a script gets imported to another script and when we execute the second script, the __name__ of script_1 gets assigned to the name of the module itself, here script_1 and not to __main__ and the name of the script_2 gets assigned to __main__.

Example:

import script_1
print(f'The __name__ from script_2 is "{__name__}"')

Output:

 

 

A module is a file containing Python definitions and statements. The file name is the module name suffixed with .py. The Module’s name is available as a value to the global variable __name__

 

We use the if-statement to run blocks of code only if our program is the main program executed. This allows our program to be executable by itself, but friendly to other Python modules who may want to import some functionality without having to run the code.

Example:

def mul(a, b):
   return a*b


if __name__ == "__main__":
   print(mul(6, 3))

Output:

 

As the script was executed directly, the __name__ keyword was assigned to __main__, and the block of code under the if __name__ == “__main__” condition was executed.

 

Leave a comment