Yes, there is a possibility to accomplish this within one Python instance. It is possible to load individual python scripts dynamically as the following:
- Load only the module dynamically with
importlib.import_module()
- Load a module and class dynamically with
getattr()
.
Alternative 1
Use importlib.import_module()
, if you only want to load the module dynamically. Let’s assume you have the following protocols in the subfolder protocols:
protocols/protocol_1.py containing the following class:
class Protocol():
# some protocol specific code
protocols/protocol_2.py containing the following class:
class Protocol():
# some protocol specific code
First we define the dynamic variables with the protocol name that will be returned from the Web API:
module = 'protocols.protocol_1'
Then we import the importlib and load the module dynamically. The Protocol class has in both files the same class name but protocol specific code. Afterwards, we instantiate the api_protocol with the dynamically loaded Protocol:
import importlib
Protocol = importlib.import_module(module).Protocol
api_protocol = Protocol()
Alternative 2
Use getattr, if you also want to load the class dynamically. Let’s assume you have the following protocols in the subfolder protocols:
protocols/protocol_1.py containing the following class:
class Protocol_1():
# some protocol specific code
protocols/protocol_2.py containing the following class:
class Protocol_2():
# some protocol specific code
First we define the dynamically variables with the protocol name that will be returned from the Web API:
module = 'protocols.protocol_1'
class_name = 'Protocol_1'
Then we call the __import__
function in order to load dynamically the class of a dynamic module. Afterwards we can create the new class with getattr
and instantiate the api_protocol with the dynamically loaded Protocol:
mod = __import__(module, fromlist=[class_name])
Protocol = getattr(mod, class_name)
api_protocol = Protocol()