I have a lot of simple scripts that calculate some stuff or so. They consist of just a single module.
Should I write main methods for them and call them with the if __name__ construct, or just dump it all right in there?
What are the advantages of either method?
Well, if you do this:
Then
import your_modulewill execute your code. On the contrary, with this:The import won’t run the code, but targeting the interpreter at that file will.
If the only way the script is ever going to run is by manual interpreter opening, there’s absolutely no difference.
This becomes important when you have a library (or reusing the definitions in the script).
Adding code to a library outside a definition, or outside the protection of
if __name__runs the code when importing, letting you initialize stuff that the library needs.Maybe you want your library to also have some runnable functionality. Maybe testing, or maybe something like Python’s SimpleHTTPServer (it comes with some classes, but you can also run the module and it will start a server). You can have that dual behaviour with the
if __name__clause.Tools like
epydocimport the module to access the docstrings, so running the code when you just want to generate HTML documentation is not really the intent.