@zlodiak

Почему hash() возвращает разные значения?

Скажите пожалуйста почему в python3 функция hash() возвращает одинаковый хеш для определённой строки только в пределах одного сеанса REPL? В документации ничего про это не сказано.

kalinin@lenovo ~ $ python3
Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'qwerty'
>>> hash(a)
-3910147687157241976
>>> hash(a)
-3910147687157241976
>>> hash(a)
-3910147687157241976
>>> 
kalinin@lenovo ~ $ python3
Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'qwerty'
>>> hash(a)
6131909781381546730
>>> hash(a)
6131909781381546730
>>> hash(a)
6131909781381546730
>>>


Проблема в том, что эту функцию не получится использовать для хеширования строки и записи её в БД. Потому что в последующий момент времени не удастся проверить строку, повторно её хешируя.
  • Вопрос задан
  • 417 просмотров
Решения вопроса 1
deepblack
@deepblack Куратор тега Python
Потому что

Note 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 www.ocert.org/advisories/ocert-2011-003.html for details.

Changing hash values affects the iteration order of dicts, sets and other mappings. Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds).

See also PYTHONHASHSEED.


UPD:
Можно заюзать https://hashids.org/python/

Hashids is a small open-source library that generates short, unique, non-sequential ids from numbers.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы