Choose adapter dynamically depending on librarie(s) installed

后端 未结 5 409
慢半拍i
慢半拍i 2020-12-16 20:10

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

5条回答
  •  萌比男神i
    2020-12-16 20:49

    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.

提交回复
热议问题