Import submodules all at once

Viewed 139

I'm quite new at Python, but I'm experienced with other programming languages.

I have this line of code:

import module as m

If I try to access its functions:

m.spam.foo()
m.eggs.bar()

I get the following errors:

AttributeError: module 'module' has no attribute 'spam'
AttributeError: module 'module' has no attribute 'eggs'

On the other hand, if I write:

import module.spam, module.eggs

and then:

module.spam.foo()
module.eggs.bar()

It works properly.


Same if I write:

from module import spam, eggs

and:

spam.foo()
eggs.bar()

Works with no errors.


I prefer the first method since I don't have to manually import every single submodule before using it...

So, what's wrong with that method? Is there a workaround to make it work (I do not like the from module import * approach since they can be confused with my global variables)?

I searched everywhere inside the reference but could not find anything.

1 Answers

I don't know how well this solves your problem, because this code is actually longer than the from module import spam, eggs method, but this question might solve your problem. Basically, you would use an __init__ function to load all submodules.

Related