Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading