Search code examples
pythonpython-typing

Interdependence of 2 classes with type hint in Python


I want to defined 2 classes and use type hints in Python 3.4+, but with some dependence between them.

This is the code I have

class Child():
    def __init__(self, name:str, parent:Parent) -> None:
        """Create a child

        Args:
            name (str): Name of the child
            parent (Parent): Parent (object)
        """
        self.name = name
        self.parent = parent
        parent.give_life(self)


class Parent():
    def __init__(self, name:str) -> None:
        self.name = name
        self.Children = []  # type: List[Child]

    def give_life(self, child:Child) -> None:
        self.Children.append(child)

and the error returned by pylint:

E0601:Using variable 'Parent' before assignment

How can I hint the type of parent argument of initialization function of Child class?

Thanks


Solution

  • It is a case of forward declaration.

    To make it work, you can us string 'Parent' instead of class Name Parent for the function Child.__init__ (and optionally Parent.give_life to make it symmetric).

    The resulting code is the following:

    class Child():
        def __init__(self, name:str, parent:'Parent') -> None:
            """Create a child
    
            Args:
                name (str): Name of the child
                parent (Parent): Parent (object)
            """
            self.name = name
            self.parent = parent
            parent.give_life(self)
    
    
    class Parent():
        def __init__(self, name:str) -> None:
            self.name = name
            self.Children = []  # type: List[Child]
    
        def give_life(self, child:'Child') -> None:
            self.Children.append(child)