Reputation: 9178
I am from Java background and I want to know how to implement something similar to SPI pattern in python : How to implement the API/SPI Pattern in Java?
Basically, we are building a Platform and we want to distribute the SDK/API packages to the "platform users" who will build Data Pipelines on top of the platform.
We only want to share the interfaces and actual implementation is resolved during the runtime by the Platform.
For example, following SDK class/interface is shared to the Platform user and during runtime when their code invokes IEventLog.send_event() method, Platform will send the event to the kafka using a Kafka Producer.
class IEventLog(object):
def __init__(self):
pass
def send_event(self,qn,corrId):
raise Exception("Error Runtime feature")
Upvotes: 4
Views: 2039
Reputation: 2928
If I correctly understand your needs, The first approach could use a dynamic import like so:
# set target module somehow, for example via environment variable
# or some kind of settings file.
import os
import imporlib
class EventLog(object):
def __init__(self):
impl_module = os.environ.get("IMPL_MODULE")
self.impl = importlib.import_module(imp_module)
def send_event(self,qn,corr_id):
self.impl.send_event(qn, corr_id)
The second is to use Strategy Pattern.
class EventLog(object):
def __init__(self):
self.impl = None
def set_impl(self, impl):
self.impl = impl
def send_event(self,qn,corr_id):
self.impl.send_event(qn, corr_id)
The third is to use some kind of dependency injection.
Upvotes: 1