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

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

    I would like to mention a usecase of mine, very similar to those mentioned by @John Millikin and @V.K. :

    Optional Imports

    I do data analysis with Jupyter Notebook, and I use the same IPython notebook as a template for all analyses. In some occasions, I need to import Tensorflow to do some quick model runs, but sometimes I work in places where tensorflow isn't set up / is slow to import. In those cases, I encapsulate my Tensorflow-dependent operations in a helper function, import tensorflow inside that function, and bind it to a button.

    This way, I could do "restart-and-run-all" without having to wait for the import, or having to resume the rest of the cells when it fails.

提交回复
热议问题