Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for using main function [closed]

Tags:

python

For the best use of:

if __name__ == "__main__" ,

what is the best?

Option 1: Create a class that runs the application and then create an instance of that class like:

class Application():
    #main code goes here


if __name__ == '__main__':
    app = Application()

Option 2. Or put the main code in a main function and then call that function:

def main():
    #do all the main stuff

if __name__ = '__main__':
    main()

How should I proceed?

Edit: ok, I got the subjective and personal aspects in this questions. Also, I´ve found a very interesting article here: https://realpython.com/python-main-function/ Helped a lot

like image 524
Bruno Lemos Avatar asked Jun 29 '26 15:06

Bruno Lemos


1 Answers

If I had to pick, I'd say that the best practice for using the __main__ would be:

class Application():
    #main code goes here

def main():
    app = Application()

if __name__ == '__main__':
    main()

This is pretty subjective but I usually would use the above code because that is how I typically see it formatted in python pre-installed modules (eg. turtledemo - __main__.py)

I hope this helps!

like image 72
Andoo Avatar answered Jul 01 '26 05:07

Andoo