python - 处理仅由某些 Python 类使用的导入的最佳方法
问题描述
我正在制作一个 Python 包,在一个模块中,我有几个 python 类,但其中只有一个使用特定的包(tensorflow),它是使用文件中的extras_require
选项安装的setup.py
,因为它是一个严重的依赖项,并且它用于项目的很小一部分。
假设我在同一个模块中有类MyClassRegular和MyClassTF,只有第二个需要 tensorflow,我正在使用以下文件的顶层导入包:
try:
import tensorflow as tf
except ModuleNotFoundError:
logging.error("Tensorflow not found, pip install tensorflow to use MyClassTF")
所以这带来了两个问题:
- 如果作为用户,我正在导入 MyClassRegular,它将对我什至不需要或不关心的包发出警告,因为我正在使用与 tensorflow 无关的功能
- 如果出于某种原因,我安装了 tensorflow,它可能会开始发出警告消息,例如 cuda 版本不正确,或者没有找到 GPU 等,这又与 MyClassRegular 无关。
所以想到的是在 MyClassTF 中导入包,我知道这可能会以某种方式违反PEP 8,但我没有看到更好的方法来处理它。因此,尝试使用此选项,我遇到的问题是,如果我在init上导入模块,则类方法无法识别它:
class MyClassTF:
def __init__(self):
try:
import tensorflow as tf
except ModuleNotFoundError:
logging.error("Tensorflow not found, pip install tensorflow to use MyClassTF")
def train(self):
print(tf.__version__) # <--- tensorflow it's not recognized here
def predict(self):
print(tf.__version__) # <--- Again, not recognized
我可以将 tensorflow 分配给这样的变量,但感觉不对:
class MyClassTF:
def __init__(self):
try:
import tensorflow as tf
self.tf = tf
except ModuleNotFoundError:
logging.error("Tensorflow not found, pip install tensorflow")
那么,处理这个问题的最佳pythonic方法是什么?
编辑: MyClassRegular 和 MyClassTF 都使用导入到顶部__init__.py
文件中
__all__ = ["MyClassRegular", "MyClassTF"]
解决方案
另一种方式,如果你想延迟发出警告,直到类被实际使用(我认为这是你想要达到的)是什么
try:
import tensorflow as tf
except ImportError:
# Allow the ImportError to pass silently and just assign tf to None
tf = None
class MyTF:
def __init__(self):
if tf is None:
warnings.warn('pip install tensorflow to use this class')
或类似的规定。无需在方法体本身中进行导入,或将 tensorflow 模块分配给实例属性,这是可行的,但非常不寻常。上述模式更为常见。
推荐阅读
- iis - 在 Wix 工具集中创建网站时如何设置 IIS AppPool 身份的权限?
- python-3.x - 删除文本文件中比例值不相关的行
- c# - 初始化 Web API 时如何调用方法?
- android - 如何使用 AOSP 证书签署 Android 应用程序
- openssl - 如何创建可由 OpenSSL 命令行工具解析的单行 x509 证书
- apache-spark - 有没有办法一次加入两个以上的数据集?
- postgresql - postgresql 中给定时间段的日期范围
- php - 具有相等索引的拆分数组
- arrays - 如何根据多个选项选择某个数组?
- ruby - Ruby如何用自定义顺序替换字符串中的字符?