3

File structure:

./__init__.py
  a.py
    /lib
    __init__.py
    Foo1.py # contains `class Foo1`
    Foo2.py # contains `class Foo2`
    # so on ...

Tested this in a.py and worked, doing this;

from lib.Foo1 import Foo1
from lib.Foo2 import Foo2

But, when I do from lib import * the __all__ = ["Foo1", "Foo2"] in __init__.py it doesn't work.

Error: <type 'exceptions.TypeError'>: 'module' object is not callable

What I'm missing?

Here is 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 these refs:
    http://docs.python.org/2/tutorial/modules.html#importing-from-a-package
    How to load all modules in a folder?

martineau
  • 119,623
  • 25
  • 170
  • 301
Kerem
  • 11,377
  • 5
  • 59
  • 58

3 Answers3

4
from lib import *

Will import everything in lib to the current module, so our globals() looks like:

{'Foo1':<module lib.Foo1>,
 'Foo2':<module lib.Foo2>}

Whereas

from lib.Foo1 import *
from lib.Foo2 import *

Makes our globals() become

{'Foo1':<class lib.Foo1.Foo1>,
 'Foo2':<class lib.Foo2.Foo2>}

So in the first case we're just importing modules, not the classes inside them which is what we want.

randomusername
  • 7,927
  • 23
  • 50
3

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 modules names be all lowercase to avoid confusion.

martineau
  • 119,623
  • 25
  • 170
  • 301
3

When importing * from a package (as in your case, using the __all__ in init.py) __all__ specifies all modules that shall be loaded and imported into the current namespace.

So, in your case, from lib import * will import the modules Foo1 and Foo2 and you need to access the classes like so:

foo1 = Foo1.Foo1()
foo2 = Foo2.Foo2()

Have a look at Importing * in Python for a quick clarification.

s16h
  • 4,647
  • 1
  • 21
  • 33