Search code examples
pythonparent-childtyping

Python 3 typing annotation and parent-child design


I am writing some Python code where I have to use parent-child design like this:

from typing import List


class Parent(object):

    def add_children(self, child: List[Child]):
        """Do something here"""


class Child(object):

    def set_parent(self, parent: Parent):
        """Do something here"""

But Python raises a NameError and complains that the Child class was not defined. This is logical because it is under the Parent class.

Is there something like "Forward declaration" in C++ to handle problems like this or is there is some other way? I tried to Google it with no success.


Solution

  • This is a circular dependency problem.

    When your code is run and the Parent class is encountered, it looks for the Child class definition, but it is defined afterwards so it cannot find it and throws the error!

    If you swap the two definitions, when your code is run and the Child class is encountered, it looks for the Parent class definition, but it is defined afterwards so it cannot find it and throws the error!

    To resolve this you have to use a string in the name as identified in here and the issue will be resolved

     def add_children(self, child: "List[Child]"):