Choose adapter dynamically depending on librarie(s) installed

后端 未结 5 405
慢半拍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条回答
  •  粉色の甜心
    2020-12-16 21:00

    The importlib.import_module might do what you need:

    INSTALLED = ['syncronous', 'alternative']  
    
    for mod_name in INSTALLED:
        try: 
            module = importlib.import_module('servicelibrary.simple.' + mod_name)
            Publisher = getattr(module, 'Publisher')
    
            if Publisher:
                break  # found, what we needed
    
        except ImportError:
            continue
    

    I guess, this is not the most advance technique, but the idea should be clear. And you can take a look at the imp module as well.

提交回复
热议问题