Choose adapter dynamically depending on librarie(s) installed

后端 未结 5 412
慢半拍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 20:58

    You've got the right idea. Your case works because each subobject has the same sort of classes e.g. both APIs have a class called Publisher and you can just make sure the correct version is imported.

    If this isn't true (if possible implementation A and B are not similar) you write your own facade, which is just your own simple API that then calls the real API with the correct methods/parameters for that library.

    Obviously switching between choices may require some overhead (i don't know your case, but for instance, let's say you had two libraries to walk through an open file, and the library handles opening the file. You can't just switch to the second library in the middle of the file and expect it to start where the first library stopped). But it's just a matter of saving it:

    accessmethods = {}
    try:
        from modA.modB import classX as apiA_classX
        from modA.modB import classY as apiA_classY
        accessmethods['apiA'] = [apiA_classX, apiA_classY]
        classX = apiA_classX
        classY = apiA_classY
    except:
        pass
    
    try:
        from modC.modD import classX as apiB_classX
        from modC.modD import classY as apiB_classY
        accessmethods['apiB'] = [apiB_classX, apiB_classY]
        classX = apiB_classX
        classY = apiB_classY
    except:
        pass
    
    def switchMethod(method):
        global classX
        global classY
        try: 
            classX, classY = accessmethods[method]
        except KeyError as e:
            raise ValueError, 'Method %s not currently available'%method
    

    etc.

提交回复
热议问题