What is "if __name__ == '__main__'" in Python

Modified: | Tags: Python

This article explains the meaning and usage of if __name__ == '__main__', which is commonly found in Python code.

At first glance, the underscores might seem confusing, but it is simply an if statement that instructs the program to "execute the following code if the value stored in __name__ is the string '__main__'".

Understanding the meaning of __name__ and '__main__' will make it easier to comprehend.

In Python, string literals can be enclosed in either single quotes ' or double quotes ". Thus, if __name__ == "__main__" is equivalent to if __name__ == '__main__'.

What is __name__?

When you import a module, its __name__ attribute stores the module's name as a string (str). You can access it with <module name>.__name__.

import math
import numpy as np

print(math.__name__)
# math

print(np.__name__)
# numpy

The same applies to modules you create.

For example, create a hello module (hello.py) as shown below. A function that outputs __name__ is defined in the module.

def func():
    print('Hello!')
    print('__name__ is', __name__)
source: hello.py

If you import and use the hello module, it looks like this.

import hello

print(hello.__name__)
# hello

hello.func()
# Hello!
# __name__ is hello

You can see that the module name 'hello' is stored in the __name__ of the imported module.

What is '__main__'?

As mentioned above, when a module is imported from another file, its name is stored in __name__.

On the other hand, if you run the file as a script from the command line, __name__ stores the string '__main__'.

For example, create test_module.py and test_main.py to import and use it.

def func():
    print('    This is func() in test_module.py')
    print('    __name__ is', __name__)


if __name__ == '__main__':
    print("Start if __name__ == '__main__'")
    print('call func()')
    func()
import test_module

print('This is test_main.py')
print('test_module.__name__ is', test_module.__name__)

print('---')
print('call test_module.func()')

test_module.func()
source: test_main.py

If you run test_main.py from the command line with the python (or python3, depending on your environment) command, you get the following result:

python3 test_main.py
# This is test_main.py
# test_module.__name__ is test_module
# ---
# call test_module.func()
#     This is func() in test_module.py
#     __name__ is test_module

As in the example above, the module name 'test_module' is stored in the __name__ of the imported module test_module.

On the other hand, if you run test_module.py itself from the command line, you get the following result:

python3 test_module.py
# Start if __name__ == '__main__'
# call func()
#     This is func() in test_module.py
#     __name__ is __main__

The string '__main__' is stored in __name__, and the code following if __name__ == '__main__': is executed.

So, when a module is imported from another file, __name__ stores the module name. When run from the command line using the python (or python3) command, __name__ stores the string '__main__'.

Note that the string '__main__' is also stored in __name__ when the python command is executed as a module using the -m option or in interactive mode.

python3 -m test_module
# Start if __name__ == '__main__'
# call func()
#     This is func() in test_module.py
#     __name__ is __main__

What does if __name__ == '__main__' mean?

In summary, the value stored in __name__ is as follows.

  • When the file (module) is imported from another file:
    • __name__ is set to '<module name>'.
  • When the file itself is run as a script with the python (or python3) command:
    • __name__ is set to '__main__'

Therefore, if __name__ == '__main__' means "execute the following code only if this file is run as a script from the command line". If the file is imported from another file, the code will not be executed.

How to use if __name__ == '__main__'

You can use if __name__ == '__main__' to write test code for a module or to allow the script to be run as a command.

Write the test code for the module

If you want to check the output result of a function within a module, write the test code following if __name__ == '__main__'.

For example, in the case of hello.py above:

def func():
    print('Hello!')
    print('__name__ is', __name__)
source: hello.py

Nothing will happen if you run this file from the command line since it only defines a function.

python3 hello.py

Add if __name__ == '__main__'.

def func():
    print('Hello!')
    print('__name__ is', __name__)


if __name__ == '__main__':
    func()

When this file is run from the command line, the function in the module is executed according to the code after if __name__ == '__main__'.

python3 hello_if_name.py
# Hello!
# __name__ is __main__

If the file is imported from another file, the code following if __name__ == '__main__' will not be executed.

Use the module as a command

If you want to use the module as a command, you can also use if __name__ == '__main__'.

Create a module as follows.

import sys


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


if __name__ == '__main__':
    print(add(int(sys.argv[1]), int(sys.argv[2])))

After if __name__ == '__main__', command line arguments are retrieved with sys.argv and passed to functions in the module.

sys.argv is a list of command line arguments, and the first element sys.argv[0] is the script name. Since they are stored as str, you need to convert them to numbers using int() or float() if you want to treat them as numerical values.

When run from the command line with arguments, the functions in the module can be executed.

python3 add_module.py 100 200
# 300

Of course, it is possible to import and use the module from other files. In this case, the code following if __name__ == '__main__' will not be executed.

import add_module

print(add_module.add(100, 200))
# 300

Note that if you want to use the module as a command, you can prepare another file for that purpose.

import sys
import add_module

print(add_module.add(int(sys.argv[1]), int(sys.argv[2])))

The result is as follows.

python3 add_module_command.py 100 200
# 300

In this case, if __name__ == '__main__' is not necessary.

If you use the argparse module to be able to use it as a command, it might be cleaner to create a separate file.

import argparse
import add_module

parser = argparse.ArgumentParser()
parser.add_argument('a', type=int)
parser.add_argument('b', type=int)

args = parser.parse_args()
print(add_module.add(args.a, args.b))

The result is as follows.

python3 add_module_argparse.py 100 200
# 300

The main() function in Python

In Python, unlike in the C language, the process does not start with the main() function. Even if you define a function named main, it does not automatically start with that function.

The following two codes both have the same result.

With the main() function:

def main():
    print('Hello!')


if __name__ == '__main__':
    main()

Without the main() function:

print('Hello!')

When run from the command line, the result is the same.

python3 hello_main.py
# Hello!

python3 hello_direct.py
# Hello!

By convention, particularly in large programs, the starting function is often named main(). However, this naming convention is for clarity only and has no special meaning in the Python specification, nor is it mandatory.

Related Categories

Related Articles