【发布时间】:2011-01-25 12:26:06
【问题描述】:
我有一组相当简单的功能,我有多个实现,例如,可以由 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 制作成一个包,每个后端都有自己的模块并使用工厂函数,但我想确保我没有错过更好的东西。
谢谢。
【问题讨论】:
-
在拥有如此出色的代表之后,您的整个问题都在标题中......?
-
这可能有助于集中标题并在正文中提供详细信息。细节帮助,一些几乎可以工作的代码来显示你希望发生的事情通常很有帮助。
-
对不起,我有一个新生儿,所以专注的能力前一分钟在这里,下一分钟就消失了。我会尝试修改。
标签: python import dependencies