0

I am trying to dynamically import a module using the following:

def import_plugin(plugin_name):
    src = f'plugins.{plugin_name}.plugin'
    module = __import__(src)
    return getattr(module, 'Plugin')

import_plugin('core')

This is the project structure:

  • main.py
  • plugins
    • core
      • plugin.py - This file contains a class named Plugin

I'm getting the error: module 'plugins' has no attribute 'Plugin'

chrispytoes
  • 1,714
  • 1
  • 20
  • 53
  • Try adding two empty files`plugins/__init__.py` and `plugins/core/__init__.py` – chc Dec 28 '22 at 18:06
  • 2
    @chc That won't help. `module` in this case is the top level folder `plugins` as indicated by the error message. OP needs to do something like `module = __import__(src, fromlist=[None])`, or better yet, use `importlib.import_module`. – Axe319 Dec 28 '22 at 18:08
  • 2
    @chc https://stackoverflow.com/questions/37139786/is-init-py-not-required-for-packages-in-python-3-3 – Peter Wood Dec 28 '22 at 18:10
  • 1
    @Axe319 Yes thank you that was it, I changed it to `__import__(src, fromlist=['Plugin'])`. – chrispytoes Dec 28 '22 at 18:55

0 Answers0