简体   繁体   中英

Python strange import behavior: import x.y works, from x import y doesn't

I am having a simple directory structure, like that:

MyProject
--main.py
--lib #that's a directory/package
----__init__.py
----view.py
----common_lib.py
----other irrelevant modules...

In main.py:

from lib import view

causes the following error:

ImportError: cannot import name view

If instead, I write it like:

from lib.view import *

This import passes successfully, but next failure happens in view.py, in that:

from common_lib import Comments, Locations, ScreenData, ProgressSignal

causes:

ImportError: No module named 'common_lib'

And as it appears from the directory structure, common_lib.py resides in the same directory as view.py, how can it happen that it cannot be found? How does it come that 'from x import y' doesn't work, and 'from xy import *' works? ' __init__.py ' is completely empty BTW. And I am using Python 3.3 32-bit.

What is more annoying, this same program worked 2 days ago.I was testing some code in IDLE and when I thought the code was ready to include in the project, pasted it into PyDev, I was shocked by this error. I changed nothing about my directories or modules.

Also, still more strangeness, running view.py and common_lib.py as standalone (without being imported) runs just fine. It should produce the error if any issues really existed.

Thanks. Any advice is highly appreciated.

Since main.py is still at the top level, you need to use lib.common_lib :

from lib.common_lib import Comments, Locations, ScreenData, ProgressSignal

because the previous line from lib import view does not start looking for modules from inside lib .

Given:

+--main.py     # from lib import view
+--lib
   +--__init__.py
   +--common_lib.py # Comments, etc.
   +--view.py       # from .common_lib import Comments, etc.

This works:

from lib import view

And this works from view.py with a relative import to indicate common_lib is in the same package.

from .common_lib import Comments, Locations, ScreenData, ProgressSignal

Works for me:

danielallan@MacBook:~$mkdir myproject
danielallan@MacBook:~$cd myproject/
danielallan@MacBook:myproject$mkdir lib
danielallan@MacBook:myproject$cd lib
danielallan@MacBook:lib$touch __init__.py
danielallan@MacBook:lib$touch view.py
danielallan@MacBook:lib$touch common_lib.py
danielallan@MacBook:lib$cd ..

In [1]: from lib import view

In [2]: view
Out[2]: <module 'lib.view' from 'lib/view.pyc'>

What happens when you try that on your machine? Are you sitting in the wrong directory, or is your path not configured to find these files?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM