如何在Python类中组织导入?

时间:2016-03-16 15:25:17

标签: python class import

假设我有一个Python类ABC;我想将一些非默认模块导入到我的项目中,但我不确定运行我的代码的用户是否安装了它们。为了检查,我在try和catch块中的类中包含了我的导入,如下所示:

class ABC:
    _canRun = True
    try:
        import XYZ
    except Exception:
        _canRun = False


    def test_function(self):
        if self._canRun:
            import XYZ
            #do stuff using XYZ module
        else:
            print("Cannot do stuff")
            return None

由于某种原因,我觉得这个设计很糟糕。我可以使用更好的模式吗?

1 个答案:

答案 0 :(得分:1)

导入通常放在py文件的开头:

try:
    import XYZ
except ImportError:
    XYZ = None

class ABC:
    def test_function(self):
        if XYZ is None:
            raise Exception("Cannot do stuff")

然而,当您可以选择替代方法时,通常会执行try / except ImportError技巧:

try:
    import XYZ
except ImportError:
    import ZZTop as XYZ # if ZZTop fails, all fails. And that's fine.

class ABC:
    def test_function(self):
        XYZ.something()

否则建议尽可能简单地失败:

import XYZ

class ABC:
    def test_function(self):
        XYZ.something()