python import * or a list from other level
Question: 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

if I do:

    
    
    from ..previous_level.module import *
        raise: SyntaxError: import * only allowed at module level
    

the same from myapp folder:

    
    
    from myapp.previous_level.module import *
        raise: SyntaxError: import * only allowed at module level
    

So I thought:

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

and also:

    
    
    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'
    

I've tried `string format` , `getattr()` , `__getattr__` but no success.

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


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

    
    
    def func():
        from ..previous_level.module import *  # SyntaxError
    

On the other hand, importing at the beginning of a module would be valid:

    
    
    from ..previous_level.module import *      # OK
    

That said, I would still suggest using absolute imports without `*`:

    
    
    from myapp.previous_level.module import ClassA, ClassB, ClassC
    
    x = ClassA()
    
    # or:
    
    import myapp.previous_level.module
    
    x = myapp.previous_level.module.ClassA()
    

BTW, this is completely wrong:

    
    
    for i in my_classes:
        from ..previous_level.module import i
    

