python circular import error

时间:2015-06-15 14:31:48

标签: python python-2.7

There is following structure:

bin.py
package/
  __init__.py
  a.py
  b.py

Content of bin.py:

#!/usr/bin/python
import package

Content of __init__.py:

import a

Content of a.py:

print "a >> begin"
print "a >> import b"
import b
print "a << import b"

def Print():
    print b.var

print "a << end"

Content of b.py:

print "  b >> begin"
print "  b >> import a"
import a
print "  b << import a"

var = 3
a.Print()

print "  b << end"

If I run python './package/a.py' - all is ok.

./package/a.py
a >> begin
a >> import b
  b >> begin
  b >> import a
a >> begin
a >> import b
a << import b
a << end
  b << import a
3
  b << end
a << import b
a << end

If I run python './bin.py', I catch error.

./bin.py
a >> begin
a >> import b
  b >> begin
  b >> import a
  b << import a
Traceback (most recent call last):
  File "./bin.py", line 2, in <module>
    import package
  File "/home/fervid/Projects/AutoClassification-Python/package/__init__.py", line 1, in <module>
    import a
  File "/home/fervid/Projects/AutoClassification-Python/package/a.py", line 3, in <module>
    import b
  File "/home/fervid/Projects/AutoClassification-Python/package/b.py", line 7, in <module>
    a.Print()
AttributeError: 'module' object has no attribute 'Print'

What is the difference?

2 个答案:

答案 0 :(得分:1)

When you run/import a.py before b.py:

a >> begin
a >> import b
  b >> begin
  b >> import a
a >> begin
a >> import b
a << import b  # see here? 
a << end
  b << import a
3
  b << end
a << import b
a << end

The second call to import b finds that there is already a b loaded (although at that point it's only part-way through), so returns to a to finish that import. Therefore when it returns to finish loading b, a.Print has been defined.


However, when you run/import b.py before a.py:

  b >> begin
  b >> import a
a >> begin
a >> import b
  b >> begin
  b >> import a
  b << import a  # oh dear

Traceback (most recent call last):
  File "C:\Python27\so\package\b.py", line 3, in <module>
    import a
  File "C:\Python27\so\package\a.py", line 3, in <module>
    import b
  File "C:\Python27\so\package\b.py", line 7, in <module>
    a.Print()
AttributeError: 'module' object has no attribute 'Print'

a has started importing when import b starts, but a.Print hasn't been defined yet (we haven't reached a << import b, let alone a << end). However, as b hasn't previously started importing, it tries to load all of b before a has finished.

答案 1 :(得分:0)

The reason for your issue is as described by jonrsharpe.

To fix the issue, you need to make sure you import b.py before importing a.py in __init__.py .

The contents of __init__.py would become -

import b
import a