Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is hash(None) calculated?

Tags:

python

hash

On my machine, hash(None) returns a value:

>>> hash(None)
-2138947203

Just out of curiosity, how is this hash value calculated? It doesn't seem as though this value is based on None's id as it is the same if I restart the Python interpreter.

like image 426
Jason Baker Avatar asked Oct 06 '11 23:10

Jason Baker


2 Answers

It is based on None's id, but None is one of a few Python objects that are defined as C global variables, so its address (typically) doesn't change between Python runs. Other such objects are True and False (but these are hashed as ints), or built-in classes like object and tuple.

The address (and hash) is different between different CPython builds, however. On my system, hash(None) gives 539708.

like image 117
Petr Viktorin Avatar answered Oct 02 '22 16:10

Petr Viktorin


It's based on the address of None in memory, as the type definition says.

like image 29
Ignacio Vazquez-Abrams Avatar answered Oct 02 '22 17:10

Ignacio Vazquez-Abrams