Suppose I have a python module set out as follows:
setup.py
tpkg/
__init__.py
module1.py
module2.py
where __init__.py
is:
from .module1 import class1
from .module2 import class2
module1.py
is:
from .module2 import class2
class class1(object):
def __init__(self):
self._who = "Class 1"
def __str__(self):
return "I'm {}".format(self._who)
def otherclass(self):
print(str(class2()))
module2.py
is:
from .module1 import class1
class class2(object):
def __init__(self):
self._who = "Class 2"
def __str__(self):
return "I'm {}".format(self._who)
def otherclass(self):
print(str(class1()))
and setup.py
is:
from setuptools import setup
setup(name="tpkg",
version="0.0.1",
packages=["tpkg"])
So, here both the modules need to import the class that is contained in the other module.
If I install this module and try to import tpkg
I get the error
In [1]: import tpkg
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-834a70240c6c> in <module>()
----> 1 import tpkg
build/bdist.linux-x86_64/egg/tpkg/__init__.py in <module>()
build/bdist.linux-x86_64/egg/tpkg/module1.py in <module>()
build/bdist.linux-x86_64/egg/tpkg/module2.py in <module>()
ImportError: cannot import name class1
So, my question is, how should I actually go about importing the classes from the two modules into each other?
Update This question is slightly different to that given here, which asks why there is a problem with cyclic imports, rather than the question of how to solve the problem of cyclic imports, which is what I needed.