circular imports

Martin von Loewis loewis at informatik.hu-berlin.de
Thu May 24 11:17:58 EDT 2001


etoffi at bigfoot.com (e toffi) writes:

> i have two modules which are interdependent, and another one which
> depends on both of them.  what can be recommended to eliminate
> circular references?

Depending on the exact setup, you may be able to live with the
circular dependency. Suppose you have two functions a.foo and b.bar,
which call each other, then you'd normally write

# a.py
from b import bar

def foo():
  if do_recursion:
    bar()

 
# b.py
from a import foo

def bar():
  if do_recursion:
    foo()

In Python, this simple scenario works well. There are also cases where
circular import don't work that well; then you could write

# a.py
def foo():
  from b import bar
  if do_recursion:
    bar()
 
# b.py

def bar():
  from a import foo
  if do_recursion:
    foo()


Here, you delay importing the other module until the function is
called. That way, importing a alone will not cause b being imported,
and vice versa - this is not a circular import anymore.

Hope this helps,
Martin




More information about the Python-list mailing list