pythoninheritance

Abstract base class function pointer python


I'd like to make an abstraction of one of my api classes to resolve the following problem. Let's say I have a base class like:

class AbstractAPI(ABC):
    @abstractmethod
    def create(self):
        pass

    @abstractmethod
    def delete(self):
        pass

And a concrete class:

class API(AbstractAPI):
    def create(self):
        print("create")

    def delete(self):
        print("delete")

When requests come in, I don't have access to my API instance. Both due multithreading and to avoid some circular imports. At that point I do know which method I would like to call later. So my plan was to put a function pointer of AbstractAPI onto a queue and wait until I do have access to the API instance.

function_pointer=AbstractAPI.create
# later on ...
function_pointer(ConcreteAPIInstance)

At that point call the function pointer onto the API instance, ba da bim, ba da boom. That does not work. Of course calling the function pointer of AbstractAPI onto an API instance calls the empty AbstractAPI method. Nothing happens. Is there a way to make this work?


Solution

  • Rather than directly referencing the abstract class method function_pointer=AbstractAPI.create, you can write a function that calls the named create() method on a given object.

    function_pointer = lambda api : api.create()
    

    or

    def function_pointer(api):
        return api.create()