First of all: I do know that there are already many questions and answers to the topic of the circular imports.
The answer is more or less: \"Design your Module/Class s
You can program against interface
(ABC - abstract base class in python), and not specific type Bar
. This is classical way to resolve package/module inter-dependencies in many languages. Conceptually it should also result in better object model design.
In your case you would define interface IBar
in some other module (or even in module that contains Foo class - depends on the usage of that abc
). You code then looks like this:
foo.py:
from bar import Bar, IFoo
class Foo(IFoo):
def __init__(self):
self.__bar = Bar(self)
# todo: remove this, just sample code
f = Foo()
b = Bar(f)
print f
print b
x = Bar('do not fail me please') # this fails
bar.py:
from abc import ABCMeta
class IFoo:
__metaclass__ = ABCMeta
class Bar(object):
def __init__(self, arg_instance_of_foo):
if not isinstance(arg_instance_of_foo, IFoo):
raise TypeError()