Python Interview Questions
Roy Smith
roy at panix.com
Mon Nov 19 22:14:39 EST 2012
In article <50aac66c$0$29983$c3e8da3$5496439d at news.astraweb.com>,
Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
> I'm asking about the case where one might want the key to remain mutable
> even after it is used as a key, but can't because Python won't let you.
Ah. Now I see what you're getting at. Thank you.
Well, I will admit that it probably doesn't make sense to mutate an
object after it's put into a dict (or at least mutate it in a way which
changes it's hash value and/or whether it compares equal to the original
object). If you did (assuming lists were allowed as keys):
l = [1, 2, 3]
d = {l: "spam"}
l.append(4)
print d[l]
I'm not sure what I would expect to print. It's not too hard to
experiment, though. All you need do is:
class HashableList(list):
def __hash__(self):
return hash(tuple(self))
and python is then happy to let you use a list as a key. I just played
around with this a bit off-line. I think I got the results I was
expecting, but since I'm not sure what I was expecting, that's hard to
say.
However, you didn't ask if it made sense to mutate an object after using
it as a key. You asked if it made sense to let the object remain
mutable after using it as a key. That's a harder question.
Let's say I had lots of of lists I wanted to use a dictionary keys. As
it stands now, I have to convert them to tuples, which means copying all
the data. For a lot of data, that's inefficient.
Wouldn't it be nice (or at least, more efficient) if I could just use
the original lists as keys directly, without the extra copy? I would
have to understand that even though they are mutable, interesting (and
perhaps, unwanted) things if I actually mutated them. But, we're all
consenting adults here. If I'm willing to accept responsibility for the
consequences of my actions in return for the efficiency gain, why
shouldn't I be allowed to?
I guess the answer is, that I am allowed to. I just need to do the
HashableList deal, shown above (no broken URL required to read the code).
More information about the Python-list
mailing list