Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting 'has no attribute' error using __import__

Tags:

python

I've run across a strange issue, and I have not found any similar issues in my searches; which probably means the issue is plainly obvious and I am just not seeing it. I have a class module called modulefile.py, in a folder called modulefolder. Here is modulefile.py:

class moduleclass(object):
    def __init__(self):
        self.parameter = 5

Now, in my test1.py file I do this:

from modulefolder.modulefile import moduleclass
myobj = moduleclass()
print myobj.parameter

And this works great - it prints the value 5 as expected.

Now, my problem is that in my application I won't know modulefolder, modulefile and moduleclass until runtime. They will be provided to me in strings. So I tried this, this is test2.py:

module = __import__("modulefolder.modulefile", fromlist=["moduleclass"])
myobj = getattr(module, "moduleclass")
print myobj.parameter

And this doesn't work, I get an error AttributeError: type object 'moduleclass' has no attribute 'parameter'.

So, this is what is baffling me. In both test1.py and test2.py I changed the print statment to print dir(myobj) instead, and I get this:

For test1.py:

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'parameter']

For test2.py

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

So, clearly, the second import method is missing my 'parameter' attribute. The problem is, I don't know why.

Why does this method of dynamic import affect the way the instantiated object works? And what can I do to fix it?

I've searched high-and-low looking for answers, so it's probably something straightforward that I've overlooked, or just don't fully understand.

like image 364
Raceyman Avatar asked Apr 23 '26 20:04

Raceyman


1 Answers

You don't instantiate your class in test2.py:

myobj = getattr(module, "moduleclass")()
like image 197
Pavel Anossov Avatar answered Apr 26 '26 09:04

Pavel Anossov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!