How to pay only the dependency penalty for the implementation you use in Python?

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, , - .

.

+3
2

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__()
+5

import - , for with. if, , .

+4

Source: https://habr.com/ru/post/1736152/


All Articles