What is the purpose of if __name__ == '__main__': if kivy can run the application without this line of code? [duplicate]

3

In the kivy documentation it shows that pro app works is needed

 if __name__ == '__main__':
    MyApp().run()

But I try to remove the if condition; and the app performed anyway; Somebody explain to me why, please!

    
asked by anonymous 02.03.2018 / 15:30

1 answer

5

It is important to remember that in addition to being able to execute a module directly, Python has the import directive to add other modules in the same application.

When you start a module, some variables are set automatically. __name__ is one of them.

The condition

__name__ == "__main__"

This is only true when your module runs directly ( main means "main").

This allows you to have a module that serves both import, providing your methods to the main application, but that performs something especially when called directly (or that simply behaves differently within the context in which it is executed).

In your specific case, removing the condition made no difference to the test because you only tested the direct call.

To better understand, make two modules, each with its own functions, and a simple "print" at the beginning of both, and at first give a import in the second. Run the first one. Then put if on both as a condition for print and run the first one again. Adding a print __name__ to the modules is also interesting to see the difference.

    
02.03.2018 / 15:40