这是关于“导入”命令的放置 (一个一般性问题 - 很难找到类似的问题)
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 :
也就是说,人们有时会在极少数情况下将导入放入函数中,在这种情况下,只有在发生特定函数调用时才应该导入模块(通常是当模块并不总是可用时,或者为了避免循环导入,或者如果进口产生费用并且需要延期)。例如,请参阅 server adapters for the itty micro-webframework .Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
另一种做法是,对于仅在主部分中使用的模块,将一些导入放在 if __name__ == '__main__'
之后。当有人导入当前模块时,这可以防止不必要的子导入。
关于python - Python 脚本中 'import' 的放置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43484743/