-1

I have read this answer regarding the issue with using self in a defaultis parameter in a Python method, but can't seem to make it work with my use case, which is a recursive call for tree traversal as shown below:

def in_order_traversal(self, node):
    if node != None:
        print(node, end=" ")
        self.in_order_traversal(node.left)
        self.in_order_traversal(node.right)

I have to call this with tree.in_order_traversal(tree.root) but would rather just use tree.in_order_traversal(), and have node=self.root as the second argument inf the method definition.

Can someone please suggest how to use the "workaround" given in the answer linked to?

Robin Andrews
  • 3,514
  • 11
  • 43
  • 111

1 Answers1

0

It isn’t clear from your question, but I think your problem is that you’re already using None to mean “this is a leaf, nothing to print”, so you can’t also use None as a default value in the same parameter to mean “use whatever your default value is”.

The way around this is to define a “sentinel” object that isn’t None and also isn’t the same as any possible actual value. For example:

_sentinel = object()
def in_order_traversal(self, node=_sentinel):
    if node is self._sentinel:
        node = self.root
    if node != None:
        print(node, end=" ")
        self.in_order_traversal(node.left)
        self.in_order_traversal(node.right)
abarnert
  • 354,177
  • 51
  • 601
  • 671
  • That is the issue, although since `in_order_traversal` is a class method, where can I define `_sentinel` without hitting the same problem? I.e `def in_order_traversal(self, node=self._sentinel):` – Robin Andrews Aug 14 '18 at 16:01
  • @Robin If its a class method, it should be decorated with `@classmethod` and take `cls` rather than `self` as the first parameter. If it’s an instance method—as is the case with what you posted—then just do exactly what I posted in my answer. You can’t use `self._sentinel` as a default value any more than you can use ‘self.root`, but you can use `_sentinel`, which is in scope in the class-defining namespace. – abarnert Aug 14 '18 at 16:12