python import * or a list from other level
<p>I'm trying to import a few classes from a module in another level. I can type all the classes, but I' trying to do it dynamically</p>

<p>if I do:</p>

<pre><code>from ..previous_level.module import *
    raise: SyntaxError: import * only allowed at module level
</code></pre>

<p>the same from myapp folder:</p>

<pre><code>from myapp.previous_level.module import *
    raise: SyntaxError: import * only allowed at module level
</code></pre>

<p>So I thought:</p>

<pre><code>my_classes = ['Class_Foo', 'Class_Bar']
for i in my_classes:
    from ..previous_level.module import i
        raise: ImportError: cannot import name 'i'
</code></pre>

<p>and also:</p>

<pre><code>my_classes = ['Class_Foo', 'Class_Bar']
for i in my_classes:
    __import__('myapp').previous_level.module.y
    raise: AttributeError: module 'myapp.previous_level.module' has no attribute 'y'
</code></pre>

<p>I've tried <code>string format</code> , <code>getattr()</code> , <code>__getattr__</code> but no success.</p>

<p>It's impossible to do import this way, or I'm doing something wrong?</p>

<p>The error <code>SyntaxError: import * only allowed at module level</code> happens if you try to import <code>*</code> from within a function. This is not visible from the question, but it seems that the original code was simething like:</p>

<pre><code>def func():
    from ..previous_level.module import *  # SyntaxError
</code></pre>

<p>On the other hand, importing at the beginning of a module would be valid:</p>

<pre><code>from ..previous_level.module import *      # OK
</code></pre>

<p>That said, I would still suggest using absolute imports without <code>*</code>:</p>

<pre><code>from myapp.previous_level.module import ClassA, ClassB, ClassC

x = ClassA()

# or:

import myapp.previous_level.module

x = myapp.previous_level.module.ClassA()
</code></pre>

<p>BTW, this is completely wrong:</p>

<pre><code>for i in my_classes:
    from ..previous_level.module import i
</code></pre>

python python-3.x