confusion about package/module imports

Scott David Daniels Scott.Daniels at Acm.Org
Tue Jan 1 16:34:48 EST 2008


Jugdish wrote:
> Why doesn't the following work?
> ... 
   [well boiled-down code skipped]
>>>> setenv PYTHONPATH $HOME:$PYTHONPATH
>>>> python $HOME/pkg/subpkg/b.py
> Traceback (most recent call last):
>   File "pkg/subpkg/b.py", line 1, in ?
>     import pkg.subpkg.a
>   File "$HOME/pkg/subpkg/__init__.py", line 2, in ?
>     import b
>   File "$HOME/pkg/subpkg/b.py", line 2, in ?
>     class B(pkg.subpkg.a.A):
> AttributeError: 'module' object has no attribute 'subpkg'

OK, here's a trick for finding import problems:
     python -v <file to fiddle>
(shows all imports)

And for this case:
     sprinkle prints to find out what is happening.

so, add "print __name, __file__" to the top of each file where
you wonder what is going on.
I later added prints in pkg/subpkg/__init__.py to make the steps clear.

You'll see that b is executed (making module __main__),
it imports pkg.subpkg.a,
    which is accomplished by importing pkg (successfully),
                     then by importing pkg.subpkg
                           which imports pkg.subpkg.a (successfully)
                           and then imports pkg.subpkg.b
                               which then attempts to import pkg.subpkg.a
At that point, only the module pkg
and what should eventually become pkg.subpkg.a
have been successfully imported.  pkg.subpkg had not yet been imported.
If you remove the "import b" from subpkg's __init__, you will find
your problems going away.
Alternatively, you can remove the import a / import b from subpkg
and add import subpkg.a, subpkg.b to pkg's __init__.  Essentially,
you need pkg.subpkg fully imported before you import pkg.subpkg.b

Of course, in most of these cases you will have imported the code
for b twice, once as a main program, and once as a module in the
hierarchy, which is probably your actual problem (and why I use
"print __name__, __file__").


--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list