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

标签 python import location

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

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/

相关文章:

Python 3 lambda错误: The truth value of a Series is ambiguous

python - 将 os.system 的输出打印到屏幕上并根据它采取行动

python - 在 Python 中从 csv 文件生成字符串集

在 SAS 中导入 Access DB 文件但失败

MySQL:从 CSV 中获取列标题名称

visual-studio-2010 - 在 VS2010 中更改解决方案项的位置

python - 如何将 lambda 函数应用于多列

mysql - 导入文本包含逗号 (,) 的 SQL 文件

android - 使用gps而不使用互联网连接在android中获取地址的纬度和经度

javascript - 如何在 Javascript/Angularjs 中检测用户来自哪里的 url?