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

Han*_*Gay 3 python import dependencies

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

这是一个例子.假设以下模块,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__()
Run Code Online (Sandbox Code Playgroud)

这是我的Python shell体验:

>>> import example
You need to install flibbertigibbet-py
Run Code Online (Sandbox Code Playgroud)

交替:

>>> from example import RedisExample
You need to install flibbertigibbet-py
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

Ian*_*and 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__()
Run Code Online (Sandbox Code Playgroud)