Nested packages and import order bug

Joerg Sonnenberger joerg at britannica.bec.de
Tue Oct 7 05:16:49 EDT 2003


On Mon, 06 Oct 2003 13:58:44 -0500, Ian Bicking wrote:

> On Monday, October 6, 2003, at 11:53 AM, Joerg Sonnenberger wrote:
>> Hi all,
>> I have a package a.b with the following content:
>>
>> a/b/__init__.py:
>>   import a.b
>>   dir(a.b)
>>
>> Running "import a.b" generates an AttributeError for b, obviously
>> the import didn't add b to the module "a". Even though it can be
>> argued that importing a package from within is bad style, this
>> a clearly a bug since its at least surprising.
> 
> This sort of bug is more common with circular imports, but in this case 
> the circle is very small (the module importing itself).  The module 
> isn't "imported" until all its statements have been executed.  When you 
> consider the statement execution order it's usually clear why it can't 
> work.

Right, it is a kind of circular import. But nevertheless the import not
work. This is unexpected.

> 
>> Shouldn't the import create the namespace entry in a after it
>> created the module entry in sys.modules?
>>
>> Therefore should I submit a bug report?
> 
> This is not an entirely uncommon error -- or maybe it's more that when 
> it does occur it usually confuses people.
> 
> I don't think the behavior is a bug.  Maybe it could have a better 
> error message, but I'm not entirely sure how you'd even detect this 
> particular case.

Well, you can work around it changing a/b/__init__.py:
import sys
sys.modules["a"].b = sys.modules["a.b"]
del sys

import a.b
print dir(a.b)

In a similiar way it could be handled by import itself.
ATM it seems to do:
1. create empty module in sys.modules
2. execute module code
3. setup namespace entry in case of nested packages

If Step 2 and 3 are reordered, the problem with this kind of circular
import vanishes. After trying to understand import.c this would mean
an additional cleanup steps in case the import failed.

Does this sound reasonable?

Joerg

> 
>    Ian





More information about the Python-list mailing list