How to start a Python code correctly

1

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 was the right way. Anyway, follow some doubts

  • What does ____init___ mean?
  • Why use ____init___ ?
  • How much to use and when not to use?
asked by anonymous 21.04.2018 / 04:09

1 answer

1

Do you mean this test?

if __name__ == "__main__":
    # faz algo

What this test determines is whether the execution is happening in the main scope , that is, it is the script that was directly executed from the command line (or 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 run directly. (Because a pure module only defines functions and classes, it normally does nothing even if it runs directly.)

So there is no "right" or "wrong", it may be an interesting practice to encapsulate the 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 .

    
21.04.2018 / 05:00