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

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

    It's a tradeoff, that only the programmer can decide to make.

    Case 1 saves some memory and startup time by not importing the datetime module (and doing whatever initialization it might require) until needed. Note that doing the import 'only when called' also means doing it 'every time when called', so each call after the first one is still incurring the additional overhead of doing the import.

    Case 2 save some execution time and latency by importing datetime beforehand so that not_often_called() will return more quickly when it is called, and also by not incurring the overhead of an import on every call.

    Besides efficiency, it's easier to see module dependencies up front if the import statements are ... up front. Hiding them down in the code can make it more difficult to easily find what modules something depends on.

    Personally I generally follow the PEP except for things like unit tests and such that I don't want always loaded because I know they aren't going to be used except for test code.

提交回复
热议问题