0

I just learned about the hash method in Python, and I'm wondering: what is the relationship between an object and its hash value? For example:

>>>hash('a') 
1567799509

What operations did python perform on the string 'a' to arrive at 1567799509? I know it's something related to hexadecimals, but what exactly is the formula used to get a hash value?

Also, I ran the following code:

a='a'
b="b"
c='c'
print (hash(a))
print(hash (b))
print(hash(c))

And I got this the first time I ran the code:

226468662

-199440459

-37886412

I got this the second time:

-121857168

-774818061

-915254158

I got this the third time:

1567799509

1439930198

1846375895

My questions is this: do hash values change? If so, why?

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
  • I believe it hashes the id of the object by default except for certain types. – Mateen Ulhaq Oct 01 '21 at 09:34
  • Since you are asking about the ``hash`` function, are you generally aware what a [hash function](https://en.wikipedia.org/wiki/Hash_function) is? – MisterMiyagi Oct 01 '21 at 09:44
  • 1
    They change to avoid denial of service attacks by forcing a (mainly web) application to store many data with the same hash and searching it later (which would be an inefficient linear search). – Michael Butscher Oct 01 '21 at 09:46
  • See also: https://stackoverflow.com/questions/40298023/python-hash-function-on-strings – Mateen Ulhaq Oct 01 '21 at 09:50

1 Answers1

1

hash function is used to just compare if two objects in the session are the same.

Return the hash value for the given object.
    
    Two objects that compare equal must also have the same hash value, but the
    reverse is not necessarily true.

It will only return same value in the same python running session.

To get same hash across multiple runs you need to use cryptographic hash from hashlib library provided in this link: https://docs.python.org/3/library/hashlib.html?highlight=hashlib

codefire
  • 393
  • 1
  • 3
  • 13