Friday, August 29, 2014

A funny thing with Python __getitem__()

So, Python has the 'in' operator which we are encouraged to use to test membership of a key in a dictionary, for example. Like

a = {'A': 22, 'B': 45}
if 'A' in a:
  print 'Yes' 

--> 'Yes'

Python has a index/slice/key notation which consists of square brackets ([]):
a['A']

--> 22

Because Python is so awesome it's slice notation is available to us for any classes we define.
class A():
  def __getitem__(self, item):
    print item
    return item

a = A()
a[23] --> 23
b['hello']  --> 'hello'

(In our real class, of course, we would be doing something interesting in the __getitem__ method, like returning a data structure indexed by the key)

What happens when we put the two together, you know, use the in idiom with a user defined class?

It's so awesome, it needs its own screencast.


So Python goes through indexes sequentially testing membership! Returning None does not help either. You have to return True or 1 to indicate membership or raise IndexError for non-mmebership. Otherwise this madness will never stop!





No comments:

Post a Comment