1

Words

The structure is as follows: a module test contains two submodules test.foo and test.bar.

test.foo has a function inc() that uses test.bar.bar() so based on the python documentation from . import bar is the proper way to include that, and this works as expected.

test.bar however, also has a function inc2 that uses test.foo.foo, but when from . import foo is used, both of these modules break.

What is the correct method for achieving this? I've found little in the python docs or searching.

Code

test/_init_.py

#empty

test/foo.py

from . import bar

def foo():
    print("I do foo")

def inc():
    print(bar.bar())

test/bar.py

from . import foo

def bar():
    print("I do bar")

def inc2():
    print(foo.foo())

Error 1

>>> import test.foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test/foo.py", line 1, in <module>
    from . import bar
  File "test/bar.py", line 1, in <module>
    from . import foo
ImportError: cannot import name foo

Error 2

>>> import test.bar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test/bar.py", line 1, in <module>
    from . import foo
  File "test/foo.py", line 1, in <module>
    from . import bar
ImportError: cannot import name bar
Yuval F
  • 20,565
  • 5
  • 44
  • 69
anthonyryan1
  • 4,867
  • 2
  • 34
  • 27

1 Answers1

4

The solution is to factor out code needed by both modules into a third module which is imported by both. For instance, put the foo function into a third module.

There are many previous StackOverflow questions about this, e.g., Circular import dependency in Python . See also http://effbot.org/zone/import-confusion.htm#circular-imports .

Community
  • 1
  • 1
BrenBarn
  • 242,874
  • 37
  • 412
  • 384