5

I do the following

class dumb(object):
    def __init__(self):
        self.g = {}
    def __getitem__(self,key): return self.g[key] if key in self.g else None
    def __setitem__(self,key,val):
        self.g[key] = val


te = dumb()

te[1]=2

te[1]
Out[4]: 2

1 in te

and it hangs..

So if I want to search something like this, how do i do that? Please don't tell me to subclass class dictionary.

Thanks in advance!

Possible relevant question asked here: What does __contains__ do, what can call __contains__ function

Community
  • 1
  • 1
user2290820
  • 2,709
  • 5
  • 34
  • 62
  • 2
    Incidentally, the reason it is hanging is that when there is no `__contains__` method available but there is a `__getitem__`, it tries all possible indices starting at 0. Since your `__getitem__` method never raises an exception (it just returns None) it keeps trying infinitely. (You can put `print key` in the `__getitem__` method to confirm this) – David Robinson Oct 16 '13 at 14:44
  • Any particular reason why you don't want to subclass dict? – mbatchkarov Oct 16 '13 at 14:44
  • @mbatchkarov because it uses other functions not specific to dictionary and I dont want to limit it to class Something(Type1,Type2) and all that mro suit follows which is anyway not the case here. ive many methods defined over there. – user2290820 Oct 16 '13 at 14:47
  • @DavidRobinson Insightful! thanks – user2290820 Oct 16 '13 at 14:47

2 Answers2

8

For in to work correctly, you need to override __contains__():

class dumb(object):
    ...
    def __contains__(self, key):
        return key in self.g

By the way,

self.g[key] if key in self.g else None

can be more succinctly written as

self.g.get(key)
NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

In order to be able to do something like:

    1 in te

you have to define __contains__ method

    class dumb(object):
        def __init__(self):
            self.g = {}
        def __getitem__(self,key): return self.g[key] if key in self.g else None

        def __setitem__(self,key,val):
            self.g[key] = val

        def __contains__(self, item):
            return item in self.g
mbatchkarov
  • 15,487
  • 9
  • 60
  • 79
Alexander Zhukov
  • 4,357
  • 1
  • 20
  • 31