intra-package mutual imports fail: "from <pkg> import <mod>"

I ran across this wrinkle and hope that someone can shed some light. First posted to comp.lang.python, but no help there. Can anyone here enlighten me?
I have a package on sys.path containing pairs of modules, each importing the other::
package/ __init__.py: # empty
module1.py: import module2 # relative import
module2.py: import module1
Executing "from package import module1" works fine. Changing the import statements to absolute dotted forms also works for "from package import module3"::
module3.py: import package.module4 # absolute import
module4.py: import package.module3
However, if I change both imports to be absolute using the "from/import" form, it doesn't work::
module5.py: from package import module6 # absolute import
module6.py: from package import module5
Now I get an exception::
>>> from package import module5 Traceback (most recent call last): File "<stdin>", line 1, in ? File "package/module5.py", line 1, in ? from package import module6 File "package/module6.py", line 1, in ? from package import module5 ImportError: cannot import name module5
Is this behavior expected? Or is it a bug? I note that FAQ entry 4.37 [*]_ says we shouldn't do "from <module> import *"; I'm not. Are all "from import" statements forbidden in this context? Why? (It seems to me that "import package.module" and "from package import module" are equivalent imports, except for their effect on the local namespace.) Is there an authoritative reference (docs, past c.l.p post, bug report, etc.)?
.. [*] http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.037.htp

However, if I change both imports to be absolute using the "from/import" form, it doesn't work::
module5.py: from package import module6 # absolute import module6.py: from package import module5
Now I get an exception::
>>> from package import module5 Traceback (most recent call last): File "<stdin>", line 1, in ? File "package/module5.py", line 1, in ? from package import module6 File "package/module6.py", line 1, in ? from package import module5 ImportError: cannot import name module5
Is this behavior expected? Or is it a bug?
It's probably due to the extremely subtle (lame?) way that "from package import module" is (has to be?) implemented.
It's too late at night for me to dig further to come up with an explanation, but maybe reading the file knee.py is helpful -- it gives the *algorithm* used for package and module import. In 2.2 and before, it's Lib/knee.py; in 2.3, it's been moved to Demo/imputils/knee.py.
I think that you'll have to live with it.
--Guido van Rossum (home page: http://www.python.org/~guido/)
participants (2)
-
David Goodger
-
Guido van Rossum