Python: Why doesn't "__all__" work for imports?
File structure;
./__init__.py
a.py
/lib
__init__.py
Foo1.py # contains `class Foo1`
Foo2.py # contains `class Foo2`
# so on ...
Tested in a.py
and worked doing it;
from lib.Foo1 import Foo1
from lib.Foo2 import Foo2
But, when I do the from lib import *
execution __all__ = ["Foo1", "Foo2"]
in __init__.py
, it doesn't work.
Mistake: <type 'exceptions.TypeError'>: 'module' object is not callable
What am I missing?
Here a.py
;
#!/usr/bin/python
import cgi, cgitb
cgitb.enable()
from lib import *
print "Content-Type: text/html"
print ""
print "Test!"
foo1 = Foo1()
foo2 = Foo2()
// used this refs:
// http://docs.python.org/2/tutorial/modules.html#importing-from-a-package
// Load all modules into a Python folder
source to share
from lib import *
Everything in lib
the current module will be imported , so ours globals()
looks like this:
{'Foo1':<module lib.Foo1>,
'Foo2':<module lib.Foo2>}
While
from lib.Foo1 import *
from lib.Foo2 import *
Makes ours globals()
become
{'Foo1':<class lib.Foo1.Foo1>,
'Foo2':<class lib.Foo2.Foo2>}
So in the first case, we just import the modules, not the classes inside them, which is what we want.
source to share
Add the following to your ... / lib / __ init__.py file:
from Foo1 import Foo1
from Foo2 import Foo1
__all__ = ['Foo1', 'Foo2']
Note that PEP-8 recommends that package and module names be lowercase to avoid confusion.
source to share
When importing *
from a package (as in your case using __all__
in init.py
) __all__
specifies all modules to be loaded and imported into the current namespace.
So, in your case it from lib import *
will import modules Foo1
and Foo2
, and you need to access classes like this:
foo1 = Foo1.Foo1()
foo2 = Foo2.Foo2()
See Import *
to Python for a quick clarification.
source to share