我正在开发一个大型 Python 程序,它根据命令行选项使用大量模块,特别是 numpy。我们最近发现需要在一个小的嵌入式模块上运行它,它排除了 numpy 的使用。从我们的角度来看,这很容易(只是不要使用有问题的命令行选项。)
但是,以下PEP 8 ,我们的import numpy在每个可能需要它的模块的开头,程序会因为没有安装numpy而崩溃。直接的解决方案是将 import numpy 从文件顶部移动到需要它的函数。问题是,“这有多糟糕”?
(另一种解决方案是将 import numpy 包装在 try .. except 中。这样更好吗?)
请您参考如下方法:
这是检查模块是否已安装并根据它创建代码分支的最佳实践模式。
# GOOD
import pkg_resources
try:
pkg_resources.get_distribution('numpy')
except pkg_resources.DistributionNotFound:
HAS_NUMPY = False
else:
HAS_NUMPY = True
# You can also import numpy here unless you want to import it inside the function
在每个对 numpy 具有软依赖性的模块导入中执行此操作。 More information in Plone CMS coding conventions .
