Note that there are some explanatory texts on larger screens.

plurals
  1. POGetting 'has no attribute' error using __import__
    primarykey
    data
    text
    <p>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:</p> <pre><code>class moduleclass(object): def __init__(self): self.parameter = 5 </code></pre> <p>Now, in my test1.py file I do this:</p> <pre><code>from modulefolder.modulefile import moduleclass myobj = moduleclass() print myobj.parameter </code></pre> <p>And this works great - it prints the value 5 as expected.</p> <p>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:</p> <pre><code>module = __import__("modulefolder.modulefile", fromlist=["moduleclass"]) myobj = getattr(module, "moduleclass") print myobj.parameter </code></pre> <p>And this doesn't work, I get an error <code>AttributeError: type object 'moduleclass' has no attribute 'parameter'</code>.</p> <p>So, this is what is baffling me. In both test1.py and test2.py I changed the print statment to <code>print dir(myobj)</code> instead, and I get this:</p> <p>For test1.py:</p> <pre><code>['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'parameter'] </code></pre> <p>For test2.py</p> <pre><code>['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] </code></pre> <p>So, clearly, the second import method is missing my 'parameter' attribute. The problem is, I don't know why. </p> <p>Why does this method of dynamic import affect the way the instantiated object works? And what can I do to fix it?</p> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload