list vs tuple
Ken Seehof
kens at sightreader.com
Wed Mar 28 16:05:35 EST 2001
From: "Aahz Maruch" <aahz at panix.com>
Newsgroups: comp.lang.python
To: <python-list at python.org>
Sent: Wednesday, March 28, 2001 11:35 AM
Subject: Re: list vs tuple
> In article <buqw6.1999$sk3.675030 at newsb.telia.net>,
> Fredrik Lundh <fredrik at effbot.org> wrote:
> >Mark Pilgrim wrote
> >>
> >> It was my understanding that only tuples containing immutable objects
> >> could be used as dictionary keys. For instance, (1,2,3) can be, and
> >> ("a","b","c") can be, but ([1,2,3], ["a","b","c"]) can not, because
> >> the underlying objects could mutate and cause problems. (Wow, that
> >> sounds like a bad sci-fi movie.) Is this true?
> >
> >no python interpreter within reach today?
> >
> >>>> d = {}
> >>>> d[(1, 2, 3)] = 1
> >>>> d[("a", "b", "c")] = 2
> >>>> d[([1, 2, 3], ["a", "b", "c"])] = 3
> >Traceback (most recent call last):
> > File "<stdin>", line 1, in ?
> >TypeError: unhashable type
>
> Sure, but someone could create a class with __hash__ and do some weird
> stuff that way. Not Recommended.
> --
Actually it's not that bad if you follow the rules. You should make sure
that __hash__ only uses private members (starting with "__") that are only
modified in __init__. You also have to overload __cmp__ so that it also
depends on the same members as __hash__ (i.e. hashes should be equal if
instances are equal). Or you can make __hash__ return id(self) if all
instances are considered unique.
If you mess up, only the offending items will become inaccessible in your
dictionary. Nightmares of the hash table becoming completely corrupt are
exagerated. Cross-links won't happen since a compare will verify the hash
hit, so bugs won't get overly nasty. The following will safely check the
integrity of a dictionary (and raise a KeyError on damaged hash values):
for k in d.keys(): d[k]
- Ken Seehof
kseehof at neuralintegrator.com
www.neuralintegrator.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20010328/657a3639/attachment.html>
More information about the Python-list
mailing list