I have a fairly simple set of functions for which I have several implementations, for example, a data warehouse that can be supported by Redis, MongoDB or PostgreSQL. How can I structure / write my code so that the code that wants to use one of these implementations needs only dependencies for this implementation, for example, they do not need to install psycopg2if they use the Redis backend.
Here is an example. Assume that the next module 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__()
Here is my Python shell:
>>> import example
You need to install flibbertigibbet-py
As an alternative:
>>> from example import RedisExample
You need to install flibbertigibbet-py
, , UnsatisfiedExample. - ? , example , factory, , - .
.