What is if __name__ == "__main__"?

In Python, the __name__ attribute is a special built-in variable that holds the name of the current module or script. When the Python interpreter runs a script or module, it assigns the value __main__ to the __name__ variable if the script is being executed as the main program.

The condition if __name__ == '__main__': is commonly used to differentiate between whether a script is being run as the main program or if it's being imported as a module into another script. This allows you to include code that should only run when the script is executed directly and not when it's imported as a module.

Detailed explanation with an example:

Suppose you have two Python files: main_script.py and module_example.py.

Contents of module_example.py:
def say_hello(): print("Hello from module_example!") print("__name__ in module_example:", __name__) if __name__ == '__main__': print("This code is executed only when module_example.py is run directly.") say_hello()
Contents of main_script.py:
import module_example print("__name__ in main_script:", __name__) module_example.say_hello()

When you run module_example.py directly, you'll see the output:

__name__ in module_example: __main__ This code is executed only when module_example.py is run directly. Hello from module_example!

When you run main_script.py, you'll see the output:

__name__ in module_example: module_example __name__ in main_script: __main__ Hello from module_example!

Notice that when you run module_example.py directly, the condition if __name__ == '__main__': is true, and the code block under it is executed. However, when you import module_example in main_script.py, the condition is false because __name__ is set to module_example, and the code block under it is not executed.

Conclusion

The __name__ == '__main__' is a common Python idiom used to check if a script is being executed as the main program or imported as a module. It allows you to include code that should only run when the script is executed directly.