Juan M Rivas
Juan M Rivas

Reputation: 137

What is the proper way to extend the Dict class?

I want to implement two different dictionaries with a predefined set of valid keys. Also, one dictionary contains the other.

class Otherdict (dict):

    _keys = ['A','B']

    def __init__(self):
        for key in self._keys:
            self[key] = None

    def populateDict(self):
        self['B'] = 10
        self['A'] = 12

class MyDict(dict):

    _keys = ['R','ED']

    def __init__(self):
        for key in self._keys:
            self[key] = None

    def __getitem__(self, key):
        if key not in self._keys:
            raise Exception("'" + key + "'" + " is not a valid key")
        dict.__getitem__(self,key)

    def __setitem__(self, key, value):
        if key not in self._keys:
            raise Exception("'" + key + "'" + " is not a valid key")
        dict.__setitem__(self,key,value)

    def populateDict(self):
        d = Otherdict()
        d.populateDict()
        self['R'] = 3
        self['ED'] = d


a = MyDict()
a.populateDict()
print a['ED'].__class__    #prints <type 'NoneType'>

The problem is that for some reason I cannot access the dictionary located under the 'ED' key. What am I doing wrong here?

I've also noticed that if I remove the __getitem__() method, the code works properly

Upvotes: 1

Views: 6651

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250931

Use return in def __getitem__(self, key) : return dict.__getitem__(self,key),

the code runs properly when you remove __getitem__ it's because it then accesses __getitem__ from parent classes(which is dict in this case).

Upvotes: 3

Janne Karila
Janne Karila

Reputation: 25197

__getitem__ must return a value:

def __getitem__(self, key):
    if key not in self._keys:
        raise Exception("'" + key + "'" + " is not a valid key")
    return dict.__getitem__(self,key)

If there is no explicit return statement, Python functions return None by default.

Upvotes: 8

Related Questions