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

2024-05-18 15:46:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个相当简单的功能集,我有多个实现,例如,一个可以由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成为一个包,每个后端都有自己的模块,并使用工厂函数,但我想确保没有遗漏更好的东西。你知道吗

谢谢。你知道吗


Tags: 模块installto代码pyimportselfredis
2条回答

import只是另一个语句,如forwith。把它放在if语句中,可能放在抽象类后面。你知道吗

你不能简单地把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__()

相关问题 更多 >

    热门问题