0

I'm writing two classes, Parent and Child, so that the parent contains several children and each child contains a reference to the parent to eventually invoke its method(). Since I use type hinting (PIP 484, mainly for clarity and readability of the code), I come up with the error:

ValueError: Circular reference detected

due to the fact that example/child.py imports Parent already defined in example/parent.py. Does anyone know how to get rid of this error?

My Parent (in example/parent.py) is as follows:

from typing import List
from example.child import Child

class Parent(object):
    def __init__(self, children: List[Child] = None) -> None:
        self._children = \
            {child.name: child for child in children} if children else {}

    @property
    def children(self) -> List[Child]:
        return list(self._children.values())

    @children.setter
    def children(self, value: List[Child] = None) -> None:
        self._children = {child.name: child for child in value} if value else {}

    def new_child(self, name: str) -> Child:
        child = Child(self, name)
        self._children[name] = child
        return child

    def method(self) -> bool:
        return len(self._children) % 2 == 0

My Child (in example/child.py), instead, is as follows:

from typing import TYPE_CHECKING, List

if TYPE_CHECKING:
    from example.parent import Parent

class Child(object):
    def __init__(self, parent: 'Parent', name: str) -> None:
        if parent is None:
            raise ValueError("'parent' is invalid: <%s>" % parent)
        if name is None or not str(name).strip():
            raise ValueError("'name' is invalid: <%s>" % name)
        self._parent = parent
        self._name = str(name).strip()

    @property
    def parent(self) -> 'Parent':
        return self._parent

    @property
    def name(self) -> str:
        return self._name

    def method(self) -> None:
        print('we are even' if self._parent.method() else 'we are odd')

Notice that I already introduced the trick which consists in using the TYPE_CHECKING variable, but in this case it doesn't help. Thanks in advance!

Stefano Bragaglia
  • 622
  • 1
  • 8
  • 25

0 Answers0