Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__getitem__ or square brackets for recursive data structure

Hello fellow StackOverflowers,

I'm implementing a Binary Search Tree with pretty much the same interface as a dict in Python (before anyone asks, I'm doing it for fun, no production code).

For adding, retrieving and deleting elements from my tree, I've implemented __getitem__, __setitem__ and __delitem__, which works great.

The question is, since this is a recursive data structure, my __getitem__ method itself calls __getitem__ on either the left or right branch of the tree, if the current node does not have the key I'm looking for.

What is the most "pythonic" way of doing this recursive call, via __getitem__ or []?

Example:

def __getitem__(self, key):
    if key  == self.key:
        return self.value
    if key < self.key and self.left is not None:
        return self.left[key]
    if key > self.key and self.right is not None:
        return self.right[key]
    return None

versus

def __getitem__(self, key):
    if key  == self.key:
        return self.value
    if key < self.key and self.left is not None:
        return self.left.__getitem__(key)
    if key > self.key and self.right is not None:
        return self.right.__getitem__(key)
    return None

I know they both work exactly the same, one being a wrapper for the other, but this is a question of style.

Using [] directly provides more concise code, less verbosity, but might mislead people who don't immediately understand that the instruction is basically the recursive call of the method, so __getitem__ removes ambiguity.

Bear in mind, I'm not talking about using one or the other in external calls, clearly [] shall be used in that case, but only inside the method, as the recursive call.

What are your thoughts?

like image 367
pcalcao Avatar asked Sep 17 '12 13:09

pcalcao


1 Answers

Use the [ ] way. It is designed to be so. If your only concern is misleading other reathers of your code, you can overcome it simply by adding a comment to your code.

like image 157
jsbueno Avatar answered Sep 23 '22 13:09

jsbueno