Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular imports in classes

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?

like image 523
VanesBee Avatar asked Aug 22 '17 16:08

VanesBee


1 Answers

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.

like image 150
user2357112 supports Monica Avatar answered Sep 20 '22 13:09

user2357112 supports Monica