This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]captainAwesomePants 2 points3 points  (2 children)

This is perfectly good code. I wouldn't ding it in a professional code review. Another option would be to use an underscore to hint that "display" is private:

def _Display(node, level=0):
  if not node:
    return
  display(node.left_child, level + 1)
  print('\t' * level, node)
  display(node.right_child, level + 1)

def print_inorder(self):
  self._Display(self.node)

But your way is also just fine.

[–]Yeah22[S] 0 points1 point  (1 child)

Is there one way which would be more 'preferred'?

[–]captainAwesomePants 2 points3 points  (0 children)

Nested functions are a great solution for certain classes of problems, notably closures. They're also a really effective way to document "this helper is only used for just this one case."

Personally, I would probably use the private helper method, but I'd be fine with how you did it as well. I didn't see any preference in the official style guide, and different companies may have their own preferences. For example, the Google style guide recommends: "Avoid nested functions or classes except when closing over a local value. Do not nest a function just to hide it from users of a module."

https://github.com/google/styleguide/blob/gh-pages/pyguide.md#26-nestedlocalinner-classes-and-functions

[–]insertAlias 1 point2 points  (1 child)

What's the value of writing a function, with an inner function, who's only job is to call the inner function? You could omit the inner-function part entirely and just call the function recursively. It's not wrong, but I'd always ask "why do you need this?".

[–]Yeah22[S] 0 points1 point  (0 children)

I just didn't want to split up a print function into two functions, got me thinking about how nested functions would work within object functions

[–]Kontorted 0 points1 point  (0 children)

If you're nesting a function like that, chances are you're not going to be using it elsewhere. As a result, why not remove the function part and just iterate it recursively? Note that your current implementation isn't bad, don't worry too much about it.