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

后端 未结 20 1693
醉酒成梦
醉酒成梦 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 03:47

    Module importing is quite fast, but not instant. This means that:

    • Putting the imports at the top of the module is fine, because it's a trivial cost that's only paid once.
    • Putting the imports within a function will cause calls to that function to take longer.

    So if you care about efficiency, put the imports at the top. Only move them into a function if your profiling shows that would help (you did profile to see where best to improve performance, right??)


    The best reasons I've seen to perform lazy imports are:

    • Optional library support. If your code has multiple paths that use different libraries, don't break if an optional library is not installed.
    • In the __init__.py of a plugin, which might be imported but not actually used. Examples are Bazaar plugins, which use bzrlib's lazy-loading framework.

提交回复
热议问题