Why keys method does not work with MutableMapping?

triccare triccare triccare at gmail.com
Sat Nov 12 23:06:49 EST 2016


Ahhh, and what is being shown is simply the __repr__. Gotcha. Thanks!

On Fri, Nov 11, 2016 at 1:03 PM, Rob Gaddi <
rgaddi at highlandtechnology.invalid> wrote:

> triccare triccare wrote:
>
> > 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>)
>
> Nope, that's exactly right.  That's the python3 behavior.
>
> >>> d = {'a': 1, 'b':2}
> >>> d.keys()
> dict_keys(['b', 'a'])
>
> Keys returns a dedicated keys object now, not just a list.  That thing
> you got back isn't a repr string; it's the actual object.  If it were a
> string it'd be quoted.
>
> Try list(md.keys()).
>
>
> --
> Rob Gaddi, Highland Technology -- www.highlandtechnology.com
> Email address domain is currently out of order.  See above to fix.
> --
> https://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list