Should I use a main() method in a simple Python script?

后端 未结 5 2170
Happy的楠姐
Happy的楠姐 2020-12-24 06:52

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

5条回答
  •  梦谈多话
    2020-12-24 07:08

    Well, if you do this:

    # your code
    

    Then import your_module will execute your code. On the contrary, with this:

    if __name__ == '__main__':
        # your code
    

    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).

    1. 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.

    2. 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.

    3. Tools like epydoc import the module to access the docstrings, so running the code when you just want to generate HTML documentation is not really the intent.

提交回复
热议问题