Why keys method does not work with MutableMapping?

triccare triccare triccare at gmail.com
Fri Nov 11 12:27:08 EST 2016


Greetings,

Apologies if this has shown up twice; I jumped the gun sending before
confirming registration.

I have a class that completely implements MutableMapping, meaning that all
the abstract methods are implemented. However, the keys method no longer
returns the keys, but simply a repr of the instance.  Example is below.
Same is true for the items method.

It would seem that, if all the abstract methods have been implemented, the
keys and items methods should be able to perform exactly like the native
dict versions. There does not seem to be a need to override these methods.

Thank you for your time.
triccare

Code:

from collections import MutableMapping

class MyDict(MutableMapping):

    def __init__(self, *args, **kwargs):
        self.data = dict(*args, **kwargs)

    def __getitem__(self, key):
        return self.data[self.__keytransform__(key)]

    def __setitem__(self, key, value):
        self.data[self.__keytransform__(key)] = value

    def __delitem__(self, key):
        del self.data[self.__keytransform__(key)]

    def __iter__(self):
        return iter(self.data)

    def __len__(self):
        return len(self.data)

    def __keytransform__(self, key):
        return key

md = MyDict({'a': 1, 'b':2})
md.keys()
==> KeysView(<keys.MyDict object at 0x105f7f7b8>)



More information about the Python-list mailing list