【发布时间】:2021-09-10 03:47:11
【问题描述】:
我正在制作一个 Python 包,在一个模块内,我有几个 Python 类,但其中只有一个使用特定包(tensorflow),它是使用setup.py 文件中的extras_require 选项安装的,因为这是一个严重的依赖,它只用于项目的一小部分。
假设我在同一个模块中有类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")
那么,处理这个问题的最佳 Python 方法是什么?
编辑: MyClassRegular 和 MyClassTF 都使用
导入到顶部的__init__.py 文件中
__all__ = ["MyClassRegular", "MyClassTF"]
【问题讨论】:
-
将类分离到不同的文件不是一种选择吗?
-
我想将它们放在一起,因为它们与同一组功能相关
标签: python python-import python-class