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

T

Tobiah

#!/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
 
M

Michael Hoffman

Tobiah said:
If within the __getitem__ method I attempt
to get an item from self, the __getitem__ method is
called in an infinite recursion.

You need to explicitly use dict.__getitem__(self, key) instead of
using self[key] directly.
 
S

Steven Bethard

Michael said:
Tobiah said:
If within the __getitem__ method I attempt
to get an item from self, the __getitem__ method is
called in an infinite recursion.

You need to explicitly use dict.__getitem__(self, key) instead of
using self[key] directly.

or super(bar, self).__getitem__(key)

STeVe
 
T

Tobiah

My appreciation for your responses is not
easily imparted through text. Thank You.

Steven said:
Michael said:
Tobiah said:
If within the __getitem__ method I attempt
to get an item from self, the __getitem__ method is
called in an infinite recursion.


You need to explicitly use dict.__getitem__(self, key) instead of
using self[key] directly.


or super(bar, self).__getitem__(key)

STeVe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top