Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Why keys method does not work with MutableMapping?

84 views
Skip to first unread message

triccare triccare

unread,
Nov 11, 2016, 11:53:50 AM11/11/16
to
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>)

triccare triccare

unread,
Nov 11, 2016, 12:27:24 PM11/11/16
to
Greetings,

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

Rob Gaddi

unread,
Nov 11, 2016, 1:04:21 PM11/11/16
to
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.

triccare triccare

unread,
Nov 12, 2016, 11:07:03 PM11/12/16
to
Ahhh, and what is being shown is simply the __repr__. Gotcha. Thanks!
> --
> https://mail.python.org/mailman/listinfo/python-list
>
0 new messages