What’s if __name__ == '__main__': if the kivy can run the application without this line of code?

Asked

Viewed 229 times

3

In the kivy documentation shows that pro app working is required

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

But I try to remove the if condition; and the app ran anyway; someone explains why, please!

  • 1

    @Andersoncarloswoss I thought I had, but I didn’t. The search is kind of boring when it’s a code snippet. I followed your vote.

1 answer

5


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

When starting a module, some variables are set automatically. A __name__ is one of them.

The condition

__name__ == "__main__"

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 special when called directly (or that simply has a differentiated behavior within the context in which it runs).

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.