Reputation: 1830
I have a module which can be described as python
class Symbol():
def __init__(data):
self.data = data
pass
def __add__(self,other):
return Add(self,other)
class Integer(Symbol):
pass
class Add(Symbol):
def __init__(a,b):
self.data = [a,b]
I want to split it into three files, which are symbol.py, integer.py and add.py; there are of course going to be a lot more details on those classes so having them in one files is ridiculous.
For some reason the imports never seem to work, while it's not even complaining of circular dependencies, can someone give me a little example?
Upvotes: 2
Views: 340
Reputation: 104682
Your circular dependency situation isn't unsolvable, because Symbol
doesn't depend on Add
at definition time, only when the __add__
method is called. There are two good ways to resolve it.
The first is to not have the module Symbol
is in import Add
at top level, but only do that within the __add__
method itself. For instance, if your modules were named after the classes (only lowercase), you'd use this in symbol.py
:
class Symbol():
# ...
def __add__(self,other):
from add import Add
return Add(self,other)
The other approach is to import Add
globally into the symbol
module, but do so after the definintion of the Symbol
class. This way, when the add
module imports symbol
back, it will always be able to see the Symbol
class's definition, even if the rest of the module is not finished loading.
class Symbol():
# same as in your current code
from add import Add
If you go with this second approach and the Symbol
class imports other stuff at the top of the file (where import
statements normally are put), you might want to add a comment in that space about Add
being imported later (and why).
Upvotes: 1