mercredi 14 juin 2023

How to implement a many-to-many adapter in Python?

I have many functions that solve the same problem in different ways (different algorithms with different properties). The functions were programmed by different people, and each function accepts its input in a different format. As a simplified example, let's say that the input to all functions is a set of items.

  • Function A accepts a dict, where each key is an item name and the value is the number of copies of that item.
  • Function B accepts a list, where each element is simply the item name, and there is only one copy of each item.

I would like to build an adapter function, that allows the user to use both A and B with both a dict and a list. A pseudocode of the adapter could be:

def adapter(func:callable, input:any):
    if (input is a dict and func expects a dict):
       return func(input)
    elif (input is a list and func expects a list):
       return func(input)
    elif (input is a list and func expects a dict):
       return func({key:1 for key in list})  # convert list to dict
    elif (input is a dict and func expects a list):
       return func(list(input.keys()))  # convert dict to list
    else:
       raise TypeError

The problem with this pseudocode is that, for n input formats, n^2 conditions are required.

Is there a more efficient way to implement such an adapter function?

Aucun commentaire:

Enregistrer un commentaire