Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is python's hash() persistent?

Tags:

python

hash

Is the hash() function in python guaranteed to always be the same for a given input, regardless of when/where it's entered? So far -- from trial-and-error only -- the answer seems to be yes, but it would be nice to understand the internals of how this works. For example, in a test:

$ python
>>> from ingest.tpr import *
>>> d=DailyPriceObj(date="2014-01-01") 
>>> hash(d)
5440882306090652359
>>> ^D
$ python
>>> from ingest.tpr import *
>>> d=DailyPriceObj(date="2014-01-01") 
>>> hash(d)
5440882306090652359
like image 537
David542 Avatar asked Dec 06 '25 14:12

David542


2 Answers

The contract for the __hash__ method requires that it be consistent within a given run of Python. There is no guarantee that it be consistent across different runs of Python, and in fact, for the built-in str, bytes-like types, and datetime.datetime objects (possibly others), the hash is salted with a per-run value so that it's almost never the same for the same input in different runs of Python.

like image 82
ShadowRanger Avatar answered Dec 09 '25 03:12

ShadowRanger


No, it's dependent on the process. If you need a persistent hash, see Persistent Hashing of Strings in Python.

Truncation depending on platform, from the documentation of __hash__:

hash() truncates the value returned from an object’s custom __hash__() method to the size of a Py_ssize_t. This is typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds.

Salted hashes, from the same documentation (ShadowRanger's answer):

By default, the __hash__() values of str, bytes and datetime objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python. This is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict insertion, O(n^2) complexity. See http://www.ocert.org/advisories/ocert-2011-003.html for details.

like image 37
Simon Avatar answered Dec 09 '25 03:12

Simon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!