gpt4 book ai didi

python - 在 Python 中导入模块 - 推荐位置

转载 作者:行者123 更新时间:2023-11-28 20:23:29 26 4
gpt4 key购买 nike

这是一个关于良好的 python 编码和定位的问题。

我有一个有点大的代码,我使用了很多外部模块/包/函数。目前,我将所有这些都加载到代码的最顶部,因为这就是我看到的方式。这很麻烦,例如,当我需要注释掉一段代码以进行测试时,因为那时我需要上去查找该 block 正在使用的模块并将它们也注释掉。我知道我必须做这最后一部分,但我这样做是为了保持一致性,因为我不喜欢导入我不会使用的东西。

如果导入的模块在使用它们的 block 上方列出,这个过程会更容易,代码也会更容易理解,至少对我而言。

我的问题是,是否建议在代码开头导入所有模块,还是我应该根据需要在整个代码中导入?

最佳答案

官方推荐开头导入,见PEP8 :

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

Imports should be grouped in the following order:

  • standard library imports
  • related third party imports
  • local application/library specific imports
  • You should put a blank line between each group of imports.

Put any relevant __all__ specification after the imports.

关于python - 在 Python 中导入模块 - 推荐位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20411014/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com