[Python-Dev] intra-package mutual imports fail: "from <pkg> import <mod>"

David Goodger goodger@users.sourceforge.net
Fri, 31 May 2002 23:30:43 -0400

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::

            # empty

            import module2   # relative import

            import module1

Executing "from package import module1" works fine.  Changing the
import statements to absolute dotted forms also works for "from
package import module3"::

            import package.module4   # absolute import

            import package.module3

However, if I change both imports to be absolute using the
"from/import" form, it doesn't work::

            from package import module6   # absolute import

            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

David Goodger  <goodger@users.sourceforge.net>  Open-source projects:
  - Python Docutils: http://docutils.sourceforge.net/
    (includes reStructuredText: http://docutils.sf.net/rst.html)
  - The Go Tools Project: http://gotools.sourceforge.net/