首页 > 解决方案 > 处理仅由某些 Python 类使用的导入的最佳方法

问题描述

我正在制作一个 Python 包,在一个模块中,我有几个 python 类,但其中只有一个使用特定的包(tensorflow),它是使用文件中的extras_require选项安装的setup.py,因为它是一个严重的依赖项,并且它用于项目的很小一部分。

假设我在同一个模块中有类MyClassRegularMyClassTF,只有第二个需要 tensorflow,我正在使用以下文件的顶层导入包:

try:
    import tensorflow as tf
except ModuleNotFoundError:
    logging.error("Tensorflow not found, pip install tensorflow to use MyClassTF") 

所以这带来了两个问题:

所以想到的是在 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"]

标签: pythonpython-importpython-class

解决方案


另一种方式,如果你想延迟发出警告,直到类被实际使用(我认为这是你想要达到的)是什么

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 模块分配给实例属性,这是可行的,但非常不寻常。上述模式更为常见。


推荐阅读