Python main function
Main function is the entry point of any program. But python interpreter executes the source file code sequentially and doesn’t call any method if it’s not part of the code. But if it’s directly part of the code then it will be executed when the file is imported as a module.
That’s why there is a special technique to define main method in python program, so that it gets executed only when the program is run directly and not executed when imported as a module. Let’s see how to define python main function in a simple program.
python_main_function.py
1 2 3 4 5 6 7 8 |
print("Hello") print("__name__ value: ", __name__) def main(): print("python main function") if __name__ == '__main__': main() |
Below image shows the output when python_main_function.py
is executed as source file.
Python main function as module
Now let’s use above python source file as a module and import in another program.
python_import.py
1 2 3 4 |
import python_main_function print("Done") |
Now when above program is executed, below output is produced.
1 2 3 4 5 |
Hello __name__ value: python_main_function Done |
Notice that first two lines are getting printed from python_main_function.py
source file. Notice the value of __name__
is different and hence main method is not executed.
Notice that python program statements are executed line by line, so it’s important to define the main() method first before the if condition to execute main method. Otherwise you will get error as NameError: name 'main' is not defined
.
That’s all about python main function.
Reference: Python Docs