0

I am writing an implementation of a graph where I have a Node class that can have one parent and many children. I wanted to include a method to get the set of ancestors of a certain Node and have written this as follow:

     def ancestors(self) -> Set["Node"]:
         """Return all ancestors of this node.
 
         Returns
         -------
         Set
             The set of all ancestors to this node or, if this node has no
             parent, returns the empty list
         """
         if not self.parent:
             return set()
         return {self.parent}.update(self.parent.ancestors())

The following example shows the idea:

a = Node()
b = Node()
c = Node()

a.parent = b
b.parent = c

a.ancestors()

This however throws the following error and I cannot figure out why

>       return {self.parent}.update(self.parent.ancestors())
E       TypeError: 'NoneType' object is not iterable

This method should never return None seeing as the default case returns an empty set. What is returning None in this scenario?

1
  • 1
    Can you provide the full implementation of the class? It would be easy to reproduce. Commented Jun 18, 2021 at 9:01

1 Answer 1

4

The problem in your code is not in the default case (return set()) but actually in the recursive case. The method Set.update() updates the set in-place, but it returns None. You can see that here:

>>> x = set()
>>> y = x.update([5])
>>> print(x)
{5}
>>> print(y)
None

One way you could fix your code is, instead of using .update, use the union operator | as follows:

def ancestors(self) -> Set['Node']:
    if not self.parent:
        return set()
    return {self.parent} | self.parent.ancestors()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.