Get the latest tech news

Why is hash(-1) == hash(-2) in Python?


While browsing Reddit the other day waiting for my code to compile , I ran across this question on r/Python: is hash(-1) == hash(-2) an easter egg? Wait, is that really true? $ python Python 3.9.6 (default, Jun 29 2021, 00:00:00) [GCC 11.1.1 20210531 (Red Hat 11.1.1-3)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> hash(-1) -2 >>> hash(-2) -2 >>> hash(-1) == hash(-2) True Yes, it is.

We convert Py_Ssize_t to PyLongObject(which the documentation calls out as: “This subtype of PyObject represents a Python integer object). Recalling what the documentation said about PyLongObject(“This … represents a Python integer object”), I started by looking at Objects/longobject.c: But the ending of this function matches exactly what we are expecting:-1 is reserved for an error signal, so the code converts that return value explicitly to-2!

Get the Android app

Or read this on Hacker News

Read more on:

Photo of python

python

Photo of = hash(-2

= hash(-2

Related news:

News photo

Run Python in the Browser Effortlessly

News photo

DeepFace: A lightweight deep face recognition library for Python

News photo

Should First-Year Programming Students Be Taught With Python and Java?