gpt4 book ai didi

python - Python 脚本中 'import' 的放置

转载 作者:太空宇宙 更新时间:2023-11-03 15:21:39 25 4
gpt4 key购买 nike

这是关于“导入”命令的放置(一个一般性问题 - 很难找到类似的问题)

Give somefunction 需要 a,并且 somefunction 位于单独的文件中。我看到了三种可能的选择。如果我要在函数中导入某些内容,哪种做法更好?或者还有其他选择吗?

## main command lines
import a # choice 1: import in a main command line
import file.somefunction

somefunction()

## function command lines in a separate file
import a # choice 2: import ahead of function

def somefunction():
import a # choice 3: import within function

最佳答案

一般指南 PEP 8 :

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

也就是说,人们有时会在极少数情况下将导入放入函数中,在这种情况下,只有在发生特定函数调用时才应该导入模块(通常是当模块并不总是可用时,或者为了避免循环导入,或者如果进口产生费用并且需要延期)。例如,请参阅 server adapters for the itty micro-webframework .

另一种做法是,对于仅在主部分中使用的模块,将一些导入放在 if __name__ == '__main__' 之后。当有人导入当前模块时,这可以防止不必要的子导入。

关于python - Python 脚本中 'import' 的放置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43484743/

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