Question

With this code:

    class MyDict(dict):
        def __setitem__(self, k, v):
            print 'assignment', k, v
            self.__dict__[k] = v

    nsg = MyDict()
    nsg["b"] = 123
    print "G is: ", nsg

It prints

assignment b 123
G is: {}

If I add

def __str__(self):
    return self.__dict__.__str__()

it works:

assignment b 123
G is:  {'b': 123}

Similarly if I print G["b"] I get a KeyError except if __getitem__(self) returns self.__dict__[k].

Why are the parent class, dict, like __str__ and __getitem__, not automatically found?

Was it helpful?

Solution

A dict object does not store keys and values in a __dict__ attribute; how could it, as the __dict__ attribute is itself a dict object!

Use the overridden __setitem__ method to add to the dictionary; best practice is to use super() to look up the original method:

class MyDict(dict):
    def __setitem__(self, k, v):
        print 'assignment', k, v
        super(MyDict, self).__setitem__(k, v)

You could also use the unbound dict.__setitem__ method:

class MyDict(dict):
    def __setitem__(self, k, v):
        print 'assignment', k, v
        dict.__setitem__(self, k, v)

except that would hardcode the method and not len subclasses of your custom myDict class inject another intermediary __setitem__ method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top