Should import statements always be at the top of a module?

后端 未结 20 2015
醉酒成梦
醉酒成梦 2020-11-22 02:56

PEP 08 states:

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.<

20条回答
  •  没有蜡笔的小新
    2020-11-22 03:43

    Module initialization only occurs once - on the first import. If the module in question is from the standard library, then you will likely import it from other modules in your program as well. For a module as prevalent as datetime, it is also likely a dependency for a slew of other standard libraries. The import statement would cost very little then since the module intialization would have happened already. All it is doing at this point is binding the existing module object to the local scope.

    Couple that information with the argument for readability and I would say that it is best to have the import statement at module scope.

提交回复
热议问题