2

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

Jean-Francois T.
  • 11,549
  • 7
  • 68
  • 107
  • Possible duplicate of [Name not defined in type annotation](https://stackoverflow.com/questions/36286894/name-not-defined-in-type-annotation) – Jean-Francois T. Jun 07 '18 at 07:50

1 Answers1

2

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)
Jean-Francois T.
  • 11,549
  • 7
  • 68
  • 107