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

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

    I wouldn't worry about the efficiency of loading the module up front too much. The memory taken up by the module won't be very big (assuming it's modular enough) and the startup cost will be negligible.

    In most cases you want to load the modules at the top of the source file. For somebody reading your code, it makes it much easier to tell what function or object came from what module.

    One good reason to import a module elsewhere in the code is if it's used in a debugging statement.

    For example:

    do_something_with_x(x)
    

    I could debug this with:

    from pprint import pprint
    pprint(x)
    do_something_with_x(x)
    

    Of course, the other reason to import modules elsewhere in the code is if you need to dynamically import them. This is because you pretty much don't have any choice.

    I wouldn't worry about the efficiency of loading the module up front too much. The memory taken up by the module won't be very big (assuming it's modular enough) and the startup cost will be negligible.

提交回复
热议问题