如何只为Python中使用的实现支付依赖惩罚?

时间:2010-03-09 16:22:29

标签: python import dependencies

我有一套相当简单的功能,我有多个实现,例如,可以由Redis,MongoDB或PostgreSQL支持的数据存储。我应该如何构造/编写我的代码,以便想要使用其中一个实现的代码只需要该实现的依赖项,例如,如果他们使用Redis后端,则不需要安装psycopg2

这是一个例子。假设以下模块example.py

class RedisExample(object):
    try:
        import redis
    except ImportError:
        print("You need to install redis-py.")

    def __init__(self):
        super(RedisExample, self).__init__()

class UnsatisfiedExample(object):
    try:
        import flibbertigibbet
    except ImportError:
        print("You need to install flibbertigibbet-py")

    def __init__(self):
        super(UnsatisfiedExample, self).__init__()

这是我的Python shell体验:

>>> import example
You need to install flibbertigibbet-py

可替换地:

>>> from example import RedisExample
You need to install flibbertigibbet-py

我真的宁愿在尝试实例化UnsatisfiedExample之前没有得到错误。是否有任何一种常见的方法来解决这个问题?我已经考虑过让example包装每个后端获得自己的模块并使用工厂函数,但我想确保我没有错过更好的东西。

感谢。

2 个答案:

答案 0 :(得分:5)

您不能简单地将import语句放在每个类的__init__方法中吗?然后,在您尝试创建实例之前,它将不会运行:

class UnsatisfiedExample(object):
    def __init__(self):
        try:
            import flibbertigibbet
        except ImportError:
            raise RuntimeError("You need to install flibbertigibbet-py")
        super(UnsatisfiedExample, self).__init__()

答案 1 :(得分:4)

import只是另一种陈述,例如forwith。将它放在if语句中,可能在抽象类之后。