I am designing a library that has adapters that supports a wide-range of libraries. I want the library to dynamically choose which ever adapter that has the library it uses
I know two method, one is wildly used and another is my guesswork. You can choose one for your situation.
The first one, which is widely used, such as from tornado.concurrent import Future.
try:
from concurrent import futures
except ImportError:
futures = None
#define _DummyFuture balabala...
if futures is None:
Future = _DummyFuture
else:
Future = futures.Future
Then you can use from tornado.concurrent import Future in other files.
The second one, which is my guesswork, and I write simple demo, but I haven't use it in production environment because I don't need it.
import sys
try:
import servicelibrary.simple.synchronous
except ImportError:
import servicelibrary.simple.alternative
sys.modules['servicelibrary.simple.synchronous'] = servicelibrary.simple.alternative
You can run the script before other script import servicelibrary.simple.synchronous. Then you can use the script as before:
from servicelibrary.simple.synchronous import Publisher
from servicelibrary.simple.synchronous import Consumer
The only thing I wonder is that what are the consequences of my guesswork.