5

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?

4

2 に答える 2

3

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.

于 2012-09-17T13:48:23.740 に答える
2

I generally use [], however it really doesn't matter ... I'm not aware of any style guide on this issue.


Note that when you're calling __getitem__ on a parent class, you need to use __getitem__ instead of [...]. e.g.

class getDict(dict):
   def __getitem__(self,key):
       if key in self:
          return dict.__getitem__(self,key)
       else:
          return None

But that's not what you're dealing with here ...

please don't use this code -- it is not meant to be an example of good code (return dict.get(self,key,None) would be better). It is only an easy to read illustration

于 2012-09-17T13:48:44.487 に答える