I would like to dynamically load .py-Files (plugins) into my program.
After doing some research, I found usually two ways of doing this:
1)
import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
from importlib import import_module
module = import_module("plugins." + modulename)
for name, klass in inspect.getmembers(module, inspect.isclass):
if klass.__module__ == "plugins." + modulename:
instance = klass()
if isinstance(instance, IPluginTemplate):
print("Plugin Call:", instance.do_something(x))
What are the main differences regarding both solutions? Is there a prefered way of doing this?