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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With