How to Use the if __name__ == “__main__” Statement in Python

09/11/2021

Contents

In this article, you will learn how to use the if __name__ == “__main__” statement in Python.

The if __name__ == “__main__” Statement

The if __name__ == “__main__” statement in Python is used to check whether the current script is being run as the main program or whether it is being imported as a module into another program. This statement is commonly used in Python scripts to ensure that certain code is only executed when the script is run directly, and not when it is imported as a module.

Here’s an example of how to use the if __name__ == “__main__” statement in Python:

# module.py
def some_function():
    print("Hello, World!")

if __name__ == "__main__":
    some_function()

In this example, the some_function() function will only be executed if the module.py script is run directly, and not if it is imported as a module into another program. If module.py is imported as a module into another program, the some_function() function will not be executed.

To run the some_function() function, you can execute the module.py script directly from the command line or an IDE:

python module.py

This will execute the some_function() function and print “Hello, World!” to the console.

Alternatively, if you import the module.py script as a module into another program, the some_function() function will not be executed:

# main.py
import module

# some code that uses module.some_function()...

In this case, the some_function() function will not be executed when main.py is run, but it can be called from main.py using module.some_function().