Eq () and hash () in Python: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 14: Line 14:
The <code>__hash__()</code> function computes the hash of the key. The [[Python_Language_Functions#hash|<code>hash()</code>]] built-in ends up calling <code>__hash__()</code>.
The <code>__hash__()</code> function computes the hash of the key. The [[Python_Language_Functions#hash|<code>hash()</code>]] built-in ends up calling <code>__hash__()</code>.


Because the <code>hash()</code> function is used to store objects in dictionary and keys, as explained [[#bee56|below]], if two instances are equal as returned by the [[#eq|<code>__eq()__</code>]], they '''must''' have equal hashes.
Because the <code>hash()</code> function is used to store objects in dictionary and keys, as explained [[#bee56|below]], if two instances are equal as indicated by the [[#eq|<code>__eq()__</code>]], they '''must''' have equal hashes.


===<span id='bee56'></span>Dictionaries and the <tt>__hash__()</tt> Function===
===<span id='bee56'></span>Dictionaries and the <tt>__hash__()</tt> Function===

Revision as of 16:31, 11 September 2022

Internal

Overview

__eq__()

__hash__()

The __hash__() function computes the hash of the key. The hash() built-in ends up calling __hash__().

Because the hash() function is used to store objects in dictionary and keys, as explained below, if two instances are equal as indicated by the __eq()__, they must have equal hashes.

Dictionaries and the __hash__() Function

To store a key into a dictionary, Python performs the following sequence:

1. Call __hash__() on the key and compute the hash of the key. If the key is not hashable, raise a TypeError.

2. Store (hash_value, key, value) in the bucket at the location hash_value % len(buckets)

3. If the bucket array needs resizing, re-use the previously computed hash value to re-insert all previously stored values. This is why is important that the key is immutable: if the key is mutable and it changes while the key/value pair is stored in the dictionary, lookup and resizing will not work.

To retrieve a key from the dictionary:

1. Call __hash__() on the key and compute the hash of the key. If the key is not hashable, raise a TypeError.

2. Locate the hash_value % len(buckets) bucket

3. Iterate the bucket for an entry matching the hash value. Why? Don't all keys stored in the bucket have the same hash value already?. If an entry exists, check for equality, first by identity then by calling __eq__().