Hash functions

Cyril Bazin cyril.bazin at gmail.com
Thu Jul 21 23:24:26 CEST 2005


Maybe in certain case you could use hash to compare objects (hashable of 
course) quicker by comparing there hash values, if the hash values are the 
same you test the equality between the objects. 

But the sets and dicts cover the greatest part of the use of hash.
(Personally, I never used that explicitly in my programs)

Cyril



On 7/21/05, Michael Hudson <mwh at python.net> wrote:
> 
> Steven D'Aprano <steve at REMOVETHIScyber.com.au> writes:
> 
> > Do people often use hash() on built-in types?
> 
> Only implicitly.
> 
> > What do you find it useful for?
> 
> Dictionaries :)
> 
> > How about on custom classes?
> 
> Same here.
> 
> > Can anyone give me some good tips or hints for writing and using
> > hash functions in Python?
> 
> Well, the usual tip for writing them is, don't, unless you need to.
> 
> If implement __eq__, then you need to, so it's fairly common to just
> hash a tuple containing the things that are considered by the __eq__
> method. Something like:
> 
> class C(object):
> def __init__(self, a, b, c):
> self.a = a
> self.b = b
> self.c = c
> def __eq__(self, other):
> return self.a == other.a and self.b == other.b
> def __hash__(self):
> return hash((self.a, self.b))
> 
> Cheers,
> mwh
> 
> --
> I'm a keen cyclist and I stop at red lights. Those who don't need
> hitting with a great big slapping machine.
> -- Colin Davidson, cam.misc
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20050721/1771ad9e/attachment.html>


More information about the Python-list mailing list