Circular import 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 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 addiction. How to deal with this behavior without losing the type of hint?

+4
source share
1 answer

Your only cyclic dependency is for types of prompts, and they 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 need import Motherand import Son; I am not sure that the tools of the current analysis are smart enough to otherwise allow type hints. Do not use fromimport; this is the force resolution of the module contents during import.

+4
source

Source: https://habr.com/ru/post/1684245/


All Articles