if __name__ == ‘__main__’ in Python

You are on the process of building a module with the basic math operations add, subtract, multiply, divide called basic_operations saved in the basic_operations.py file.

To guarantee everything is fine, you make some tests.

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

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

def divide(a, b):
    return a / b

print(add(10, 2)) 
print(subtract(10,2))
print(multiply(10,2))
print(divide(10,2))

After running the code:

python3 basic_operations.py

The output is:

12
8
20
5.0

The output for those tests are what we expected.

Our code is right and ready to share.

Let’s import the new module run it in the Python console.

Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import basic_operations
12
8
20
5.0
>>> 

When the module is imported our tests are displayed on the screen even though we didn’t do anything besides importing basic_operations.

To fix that we use if __name__ == '__main__' in the basic_operations.py file like this:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

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

def divide(a, b):
    return a / b

if __name__ == '__main__':
    print(add(10, 2)) 
    print(subtract(10,2))
    print(multiply(10,2))
    print(divide(10,2))

Running the code directly on the terminal will continue to display the tests, but when you import it like a module, the tests won’t show and you can use the functions the way you intended.

Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import basic_operations
>>> basic_operations.multiply(10,2)
20
>>>

Now that you know how to use the if __name__ == '__main__', let’s understand how it works.

The condition tells when the interpreter is treating the code as a module or as a program itself being executed directly.

Python has this native variable called __name__.

This variable represents the name of the module which is the name of the .py file.

Create a file my_program.py with the following and execute it.

print(__name__)

The output will be:

__main__

This tells us that when a program is executed directly, the variable __name__ is defined as __main__.

But when it is imported as a module, the value of __name__ is the name of the module.

Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import my_program
my_program
>>>

This is how the Python interpreter differentiates the behavior of an imported module and a program executed directly on the terminal.