issue on internal import in a package

Frank Millman frank at chagford.com
Sun Feb 27 08:22:29 EST 2011


"Ben Finney" <ben+python at benfinney.id.au> wrote in message 
news:87ei6t646h.fsf at benfinney.id.au...
> 人言落日是天涯,望极天涯不见家 <kelvin.you at gmail.com> writes:
>
>> Here is a simple example:
>> [app]
>>       [module]
>>             __init__.py   --> empty
>>             a.py   --> import b
>>             b.py  --> defined a function foo()
>>       test.py
>>
>> In the test.py, contains the below statement:
>> from module import a
>> Execute the test.py will get error:
>
> This works fine for me::
>
>    $ mkdir --parents app/module/
>    $ touch app/module/__init__.py
>    $ printf "import b\n" > app/module/a.py
>    $ printf "def foo(): pass\n" > app/module/b.py
>    $ printf "from module import a\n" > app/test.py
>    $ find .
>    .
>    ./app
>    ./app/module
>    ./app/module/__init__.py
>    ./app/module/a.py
>    ./app/module/b.py
>    ./app/test.py
>
>    $ python app/test.py
>
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in <module>
>>   File "module\a.py", line 1, in <module>
>>     import b
>> ImportError: No module named b
>>
>> Why the b.py can not be found by a.py?
>
> I get no errors; the code appears to run fine. Perhaps the scenario is
> not exactly as you describe?
>

I get exactly the same result as the OP, using python 3.2 on both windows 
and linux. It works using python 2.6.

I can fix it by changing a.py from 'import b' to 'from . import b'.

As I understand it, the reason is that python 3.x will no longer look for an 
absolute import in the current package - it will only look in sys.path.

Frank Millman





More information about the Python-list mailing list