Hash functions

S

Steven D'Aprano

Do people often use hash() on built-in types? What do you find it useful
for?

How about on custom classes? Can anyone give me some good tips or hints
for writing and using hash functions in Python?

Thank you,
 
M

Michael Hudson

Steven D'Aprano said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,310
Members
47,976
Latest member
SheriBolli

Latest Threads

Top