Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Python main function Examples

The idea of Python main function is to execute some code only when the Python script is executed directly. The function should not execute when the same script is imported as a Python module in another program.


How to Write a Python main Function?

When we run a python program, it executes all the statements inside it. So, if we have a main() function and we call it in the program directly, it will get executed all the time, even when the script is imported as a module.

But, we want to execute the main function only when the script is executed directly. We have to use an alternative approach to implement the Python main function.

Whenever we execute a Python script, its scope is set to __main__ and it can be retrieved by __name__ variable.

But, when the script is imported as a module, the scope value is set to the name of the python script. We can use the scope name with the if statement to call the main() method.

Let’s look into it with a simple example. The Python script name is main_function.py.

print("Start main_function.py")

print(f'__name__ value is {__name__}')


# main function
def main():
    print('The main function')


if __name__ == '__main__':
    main()

Let’s run this script directly using the Python interpreter.

$ python3.7 main_function.py 
Start main_function.py
__name__ value is __main__
The main function
$ 

We are printing the __name__ variable value, which is __main__. That’s why the if condition returns True and the main() function gets executed.

Python Main Function
Python Main Function

When the Python script is imported as a module

Now, let’s see what happens when we import the script as a Python module in another program. I am creating another Python script with name other_script.py.

import main_function

print('Hello World')

Let’s see what happens when we run this script with the Python interpreter.

$ python3.7 other_script.py 
Start main_function.py
__name__ value is main_function
Hello World
$

The main_function module scope name is main_function. This causes the if condition to return False and the main() method is not executed.


Python main function best practices

  • It is customary to keep the main function name as main(). We can keep any other name too, but it’s better to follow the naming convention.
  • It’s better to keep all the script directly executable code inside the main() function. Because most of the times we don’t want them to execute when the script is imported as a module.

References: