Report this

What is the reason for this report?

Python main function

Published on August 3, 2022
Python main function

Python main function is executed only when it’s being executed as a python program. As you know, we can also import a python program as a module, in that case python main method should not execute.

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

print("Hello")

print("__name__ value: ", __name__)


def main():
    print("python main function")


if __name__ == '__main__':
    main()
  • When a python program is executed, python interpreter starts executing code inside it. It also sets few implicit variable values, one of them is __name__ whose value is set as __main__.

  • For python main function, we have to define a function and then use if __name__ == '__main__' condition to execute this function.

  • If the python source file is imported as module, python interpreter sets the __name__ value to module name, so the if condition will return false and main method will not be executed.

  • Python provides us flexibility to keep any name for main method, however it’s best practice to name it as main() method. Below code is perfectly fine, however not recommended.

    def main1():
        print("python main function")
    
    
    if __name__ == '__main__':
        main1()
    

Below image shows the output when python_main_function.py is executed as source file. python main function, python if name main

Python main function as module

Now let’s use above python source file as a module and import in another program. python_import.py

import python_main_function

print("Done")

Now when above program is executed, below output is produced. python main method, python if main

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

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author

Pankaj Kumar
Pankaj Kumar
Author
See author profile

Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev

Category:
Tags:
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Was this helpful?

The best site with the best information I’ve ever found! Thousands of thanks!

- Sensation Person

Well Done Pankaj, very well explained. So far this is the best one from desi !!!

- Srinivas

Very good explanation , keep it up

- Hari Haran

Very well explained .

- RandomGoogler

Nice document. It will be helpful for a lot of beginners. Thanks

- Kiran

Still relevant. Thanks for the simple but elegant breakdown. I needed that and truly appreciate it.

- Eric Webb

Thanks so much for this breakdown. It was super clear and helpful for a begginer like myself.

- Nahuel Tamasso

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.