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?