0

I'm trying to instantiate a class in a submodule using a string name. I've been trying to follow this SO question unsuccessfully:

Python dynamic instantiation from string name of a class in dynamically imported module

I've created the following directory structure:

__init__.py
mymodule/
├── __init__.py
└── MyClass.py 

MyClass.py contains:

class MyClass():
    def __init__(self, someparam):
        print(someparam)

From python I try the following which produces an error.

getattr(importlib.import_module('mymodule'), 'MyClass')

AttributeError: 'module' object has no attribute 'MyClass'

I've tried most of the other solutions put forth in the referenced question and not gotten any of them to work with this setup.

Here other failed attempts based on answers I've tried to follow to illustrate what I've tried and failed at:

import importlib
module = importlib.import_module('mymodule')
class_ = getattr(module, 'MyClass')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'MyClass'
David Parks
  • 30,789
  • 47
  • 185
  • 328
  • 2
    Importing a package doesn't automatically load all its submodules. – user2357112 Apr 10 '18 at 17:24
  • 2
    That's the same error you get if you try `import mymodule; mymodule.MyClass`. The problem here isn't the dynamic import. – Aran-Fey Apr 10 '18 at 17:26
  • So the question is how you do the dynamic import correctly, that's just one of a dozen examples I've tried. I don't care what the code looks like I just want an instance of the class given that I have a string representing the class. I can control what the string should be, but it needs to be a command line parameter. – David Parks Apr 10 '18 at 17:28
  • Also please note that the first example I have there is a directly derived from the second answer (86 upvotes) in the question I referenced. – David Parks Apr 10 '18 at 17:33

1 Answers1

2

Your code is equivalent to:

from mymodule import MyClass

mymodule doesn't contain MyClass, so you will get an error. You want the equivalent of:

from mymodule.myclass import MyClass

That would be:

getattr(importlib.import_module('mymodule.MyClass'), 'MyClass')
David Parks
  • 30,789
  • 47
  • 185
  • 328
Blender
  • 289,723
  • 53
  • 439
  • 496
  • Ahh, I swear I tried that, I must have done something else wrong along the way. Thanks for that, it does work. I adjusted capitalization in the answer to match the question context. – David Parks Apr 10 '18 at 17:43