Why is dictionary.keys() a list and not a set?
Mike Meyer
mwm at mired.org
Thu Nov 24 16:28:20 EST 2005
Christoph Zwerschke <cito at online.de> writes:
> Mike Meyer schrieb:
>> If the hash changes, you've screwed up the set. What it really should
>> say is "collection of objects with fixed hashes", or words to that
>> effect. Do you want to file a PR on this?
> I fear I have not enough understanding of Python's hashing concepts to
> make a suggestion for improvement here.
Well, I just made a suggestion. You found the problem - you want to do
the PR, or should I?
>> How so? As I demonstrated, you can subclass any class that doesn't
>> have a hash to add one, and then use the subclass, which - except for
>> having a hash - will have exactly the same behavior as your original
>> class.
> But you surely wouldn't want to do this to the list of items just to
> be able to return it as a set.
Well, I don't have a use case for this, but it's not hard. Write a
class whose __new__ either returns the original object (if it's
hashable), or creates an instance of the class, which will proxy for
that object. Something like:
# Untested code
class Hash(object):
def __new__(cls, obj):
if hasattr(obj, '__hash__'):
return obj
self.__obj = obj
return object.__new__()
def __getattr__(self, name):
return getattr(self.__obj, name)
def __setattr(self, name, value):
setattr(self.__obj, name, value)
def __hash__(self):
return id(self.__obj)
and then do:
set([Hash(i) for i in lst])
If you need to turn a list of arbitrary, possibly unhashable, objects
into a set, is there a problem with the above?
<mike
--
Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list
mailing list