freude
freude

Reputation: 3832

Python programming pattern for a variety of engines (backends)

What would be the best way to implement the following behaviour: I have an interface represented by a function ans = my_interface(args), I have several implementations of this function and I want to give the user permission to select one of the implementations by setting a parameter.

The obvious solution would be to make each implementation a function with identical interfaces and in my_interface process the parameter and depending on its value call one of them. If I want to extend, I need to add a new function with a new implementation of the engine and change my_interface to process a new engine's name. And I have to be aware of the proper interface here. I don't think it is the smartest way.

I would also apreciate a link on the book or discussion of this matter. I have found a similar functionality in Keras for example, where it can use either Tensorflow or PyTorch backends. Does anyone know how it is implemented?

Upvotes: 1

Views: 439

Answers (1)

Corralien
Corralien

Reputation: 120469

If you don't want to use classes and design patterns, you can try something like that:

def _my_interface_engine_A():
    print("engine A")
    return 0

def _my_interface_engine_B():
    print("engine B")
    return 1

def _my_interface_engine_C():
    print("engine C")
    return 2

def my_interface(*args, **kwargs):
    engine = kwargs.pop("engine", "A")  # A is the default engine
    return globals()[f"_my_interface_engine_{engine}"](*args, **kwargs)
>>> print(my_interface())
engine A
0

>>> print(my_interface(engine="B"))
engine B
1

If you add another interface, you just need to name your function _my_interface_engine_X and let my_interface function untouched. my_interface acts as a proxy to your other interfaces.

Upvotes: 1

Related Questions