Let's say I have two classes in two files:
from Son import Son
class Mother:
def __init__(self):
self.sons = []
def add_son(self, son: Son):
self.sons.append(son)
and
from Mother import Mother
class Son:
def __init__(self, mother: Mother):
self.mother = mother
mother.add_son(self)
Plus a main file
from Mother import Mother
from Son import Son
if __name__ == '__main__':
mother = Mother()
son1 = Son(mother)
son2 = Son(mother)
Obviously, I have a circular dependency. How to deal with this kind of behaviour without losing the type hint stuff?
Your only circular dependency is in the type hints, and those can be specified as strings:
# Mother.py
class Mother:
def __init__(self):
self.sons = []
def add_son(self, son: 'Son.Son'):
self.sons.append(son)
# Son.py
class Son:
def __init__(self, mother: 'Mother.Mother'):
self.mother = mother
mother.add_son(self)
You may still need to import Mother
and import Son
; I'm not sure whether current analysis tools are intelligent enough to resolve the type hints otherwise. Don't use from
imports; those force resolution of the module contents at import time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With