Defining __getitem__() in a class that inherits from (dict)

Tobiah toby at rcsreg.com
Tue Mar 8 18:40:32 EST 2005


#!/usr/bin/python

# Hi,
#
# I noticed something interesting when trying to define
# the __getitem__() method in a class that inherits from
# (dict).  If within the __getitem__ method I attempt
# to get an item from self, the __getitem__ method is
# called in an infinite recursion.  I am very fond of
# inheriting from (dict) as in the class 'bar' below,
# but this problem is making me think that I will have
# to write them as in 'foo' below.  Is there a workaround
# to make the class 'bar' work as I planned?

class foo:

         data = {}

         def __getitem__(self, what):
                 if not self.data.has_key(what):
                         self.data[what] = None
                         return None
                 else:
                         return self.data[what]


class bar(dict):

         data = {}

         def __getitem__(self, what):
                 if not self.has_key(what):
                         self[what] = None
                         return None
                 else:
                         return self[what]


f = foo()
b = bar()


print f['somekey']
print f['somekey']

print b['somekey']
print b['somekey']


# OUTPUT:
# None
# None
# None
# Traceback (most recent call last):
# File "<stdin>", line 47, in ?
# File "<stdin>", line 36, in __getitem__
# File "<stdin>", line 36, in __getitem__
# File "<stdin>", line 36, in __getitem__

Thanks,

Tobiah



More information about the Python-list mailing list