How to start Python code correctly

Asked

Viewed 82 times

0

I’m still learning Python and once I saw a guy starting a Python code with something ____init___, with a if ___init___ ... == True. I asked him why he started the code in such a way, he told me that this was the right way. Anyway, follow some doubts

  • What does it mean ____init___?
  • Why use ____init___?
  • How much to use and when not to use?
  • 1

    You can check the answer given and make sure you’re asking the right question? __init__ and __name__ are completely different things.

1 answer

2

You mean this test?

if __name__ == "__main__":
    # faz algo

What this test determines is whether the execution is happening on main scope, i.e., it is the script that was directly executed from the command line (or from the graphical menu).

This test is useful when you want the script to be imported with a module (in which case the above test will return False) but can also be executed directly. (As a pure module only defines functions and classes, it usually does nothing even if it runs directly.)

So there is no "right" or "wrong", it can be an interesting practice to encapsulate code this way so that a script is "modularized" easily, but a script that will always run directly in the foreseeable future does not need this.

Browser other questions tagged

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