I am developing a library with adapters that support a wide range of libraries. I want the library to dynamically select which adapter always has the library that it uses, installed on the computer when importing certain classes.
The goal is to be able to modify the library on which the program depends, without making changes to the code. This feature consists in handling RabbitMQ connections, since we had a lot of problems with pika , we want to be able to switch to another library, for example pyAMPQ or rabbitpy without changing the base code,
I was thinking of implementing something like this in the __init__.py servicelibrary.simple file.
try: #import pika # Is pika installed? from servicelibrary.simple.synchronous import Publisher from servicelibrary.simple.synchronous import Consumer except ImportError: #import ampq # Is ampq installed? from servicelibrary.simple.alternative import Publisher from servicelibrary.simple.alternative import Consumer
Then when the user imports the library
from servicelibrary.simple import Publisher
The underlying layer looks something like this:
alternative.py
import amqp class Publisher(object): ...... class Consumer(object): ......
synchronous.py
import pika class Publisher(object): ...... class Consumer(object): ......
This will automatically select the second when the first is not installed.
Is there a better way to implement something like this? If anyone could link the library / adapter with a similar implementation, which would also be useful.
[Change]
What would be the cleanest way to implement something like this? In the future, I would also like to change the default preference. Ultimately, I can simply agree to use the installed library, as I can control this, but that would be a nice feature.
Alexanders suggestion is interesting, but I would like to know if there is a cleaner way.
[Edit2]
The original example has been simplified. Each module can contain several types of imports, for example. Consumer and publisher.