“Boilerplate” code in Python?

后端 未结 6 760
终归单人心
终归单人心 2021-02-01 03:07

Google has a Python tutorial, and they describe boilerplate code as \"unfortunate\" and provide this example:

#!/usr/bin/python

# import modules used here -- sy         


        
6条回答
  •  春和景丽
    2021-02-01 03:33

    The reason you use an "if main" check is so you can have a module that runs some part of its code at toplevel (to create the things – constants, functions, or classes – it exports), and some part only when executed as a script (e.g. unit tests for its functionality).

    The reason the latter code should be wrapped in a function is because local variables of the main() block would leak into the module's scope.

    Now, an alternate design could be that a file executed as a script would have to declare a function named, say, __main__(), but that would mean adding a new magic function name to the language, while the __name__ mechanism is already there. (And couldn't be removed, because every module has to have a __name__, and a module executed as a script has to have a "special" name because of how module names are assigned.) Introducing two mechanisms to do the same thing just to get rid of two lines of boilerplate – and usually two lines of boilerplate per application – just doesn't seem worth it.

提交回复
热议问题