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

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

    Just to complete Moe's answer and the original question:

    When we have to deal with circular dependences we can do some "tricks". Assuming we're working with modules a.py and b.py that contain x() and b y(), respectively. Then:

    1. We can move one of the from imports at the bottom of the module.
    2. We can move one of the from imports inside the function or method that is actually requiring the import (this isn't always possible, as you may use it from several places).
    3. We can change one of the two from imports to be an import that looks like: import a

    So, to conclude. If you aren't dealing with circular dependencies and doing some kind of trick to avoid them, then it's better to put all your imports at the top because of the reasons already explained in other answers to this question. And please, when doing this "tricks" include a comment, it's always welcome! :)

提交回复
热议问题