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

后端 未结 20 2013
醉酒成梦
醉酒成梦 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:57

    Curt makes a good point: the second version is clearer and will fail at load time rather than later, and unexpectedly.

    Normally I don't worry about the efficiency of loading modules, since it's (a) pretty fast, and (b) mostly only happens at startup.

    If you have to load heavyweight modules at unexpected times, it probably makes more sense to load them dynamically with the __import__ function, and be sure to catch ImportError exceptions, and handle them in a reasonable manner.

提交回复
热议问题