<jupyter_start><jupyter_text>---title: Of Hashes and Pythonsicon: code--- I posted the following code on a [tweet](https://twitter.com/Ewjoachim/status/728610568886718466) todayand subsequently had a very interesting talk answering [questions](https://twitter.com/codingrixx/status/728616489318789120) about this, which I'll sumarize here. There might also be new material, too.<jupyter_code>class A(object):
    def __hash__(self):
        return id(self)
class B(object):
    def __hash__(self):
        return 1
%%timeit
{A() for a in range(10000)}
%%timeit
{B() for a in range(10000)}<jupyter_output>1 loop, best of 3: 1.42 s per loop<jupyter_text>So what's happening here ?Here's a textual version of the code above.First I create a class `A` whose ``__hash__`` method returns the result of `id(self)` which mean more or less "the value of a pointer on `self`.Then I create a class `B` whose ``__hash__`` method returns something quite simpler : the constant 1.Putting ten thousand instances of `A` in a set takes 4 ms, putting 10 thousand instances of `B` should *logically* take less, because the hash is easier to compute and you don't have to store ten thousand different hashes, right ? Nope. It take longer. 317 times longer.**Note:** The hash of an object is just an integer with the following property : if 2 objects are equal, then their hashes are equal too. (The opposite is not always true, see the remarks at the end of the post)**Note 2:** In this post, I'm talking a lot about sets. I could say exactly the same thing about dicts. Sets are easier to manipulate in this example.  What happens when I put something in a set ? Let's play a bit. Introducing Verbose, a class that talks all the time.Instances have a name, and we do 2 things: 1. If 2 instances share the same name, we say they're equal, through `__eq__` (and talk a bit). 2. Through `__hash__`, we set the hash of instances to be solely based on their name (and talk a bit).<jupyter_code>class Verbose(object):
    
    def __init__(self, name):
        self.name = name
    
    def __eq__(self, other):
        """
        __eq__(for "equal") is used to determine
        the result of:
        Verbose() == other
        """
        equal = self.name == other.name
        print("Is {} equal to {} ? {}.".format(self, other, equal))
        return equal
    
    def __hash__(self):
        """
        Hashable objects need to implement __hash__,
        that should return integers, with this
        property: 2 equal objects should return
        the same hash.
        """
        hash_value = hash(self.name)
        print("Asking the hash for {} which is {}.".format(self, hash_value))
        return hash_value
        
    def __repr__(self):
        """
        This is just so that our prints looks clean
        """
        return self.name<jupyter_output><empty_output><jupyter_text>Play time !<jupyter_code>Verbose("a") == Verbose("b")
{Verbose("a")}
{Verbose("a"), Verbose("b")}
{Verbose("a"), Verbose("a")}<jupyter_output>Asking the hash for a which is -1212919011480583274.
Asking the hash for a which is -1212919011480583274.
Is a equal to a ? True.<jupyter_text>When I put an object in a set, these things happen : 1. We compute the hash of the object 2. We see if the hash is already in our set 3. If so, we get the objects that share the same hash, they're potential matches 4. We wheck if our object is equal to any of that list. 5. If so, it's already in our set, so no need to add it again. What would happen if 2 objects had the same hash, but were not equal ?<jupyter_code>class Verbose2(Verbose):
    def __hash__(self):
        return 1
{
    Verbose2("a"), Verbose2("b"), Verbose2("c"),
    Verbose2("d"), Verbose2("e"), Verbose2("f")
}<jupyter_output>Is f equal to e ? False.
Is f equal to d ? False.
Is e equal to d ? False.
Is f equal to c ? False.
Is e equal to c ? False.
Is d equal to c ? False.
Is f equal to b ? False.
Is e equal to b ? False.
Is d equal to b ? False.
Is c equal to b ? False.
Is f equal to a ? False.
Is e equal to a ? False.
Is d equal to a ? False.
Is c equal to a ? False.
Is b equal to a ? False.<jupyter_text>Thats 15 comparisons for 6 objects. Each object gets compared to all the others. The number of comparison is `6 * 5 / 2`<jupyter_code>n = 6
def number_of_comparisons(n):
    return n * (n - 1) // 2

number_of_comparisons(6)<jupyter_output><empty_output><jupyter_text>So this is what is happening for our initial bad example : there are 10 000 objects that all get compared to each other.<jupyter_code>number_of_comparisons(10000)<jupyter_output><empty_output><jupyter_text>That's ~50 millions.  At this point, you might ask :*"But you said elusively in your earliest list that 'We see if the hash is already in our set'. Isn't it the same problem ? We have to check all the values !*"And yes, if a hash could be anything, that would be true. Fortunately, we know something about hashes : they're integers. A comparison between any objects can give 2 results : equal or not equal. A comparison between integers can give 3 results : less, equal, greater.What happens behind the scene may depend on the python implemention. Better than telling you things that Python does that we cannot **test** here, let's give an example of what a Python implementation **might** do.Python could place all our values in a [Binary Tree](https://en.wikipedia.org/wiki/Binary_tree) (`btree`). A binary tree is a way to organize sortable elements that look a lot like the game where you have to guess someone's number when they only tell you plus or minus. This allows for very efficient fetching of your data (`log2(n)`)  So that's it, thenNow we know why the `A` class is fast and the `B` class is so very very slow.Thank you very much. The show's finished. What ? You want more ? Ok, let's get you more !  What happens when the hash is not really reliable ?<jupyter_code>import random
class C(object):
    def __hash__(self):
        return random.randint(0, 10)
c = C()
s = {c}
print(
    "Is c in the set of s that contains only c ?",
    c in s
)
print(
    "And what if I ask you 20 times the question ?",
    any(c in s for i in range(20))
)<jupyter_output>Is c in the set of s that contains only c ? False
And what if I ask you 20 times the question ? True<jupyter_text>Why do they say mutable objects should not be hashable ? (Mutable objects mean objects that you can modify after they've been created). Hashes are computed only when the object is first put in a set.<jupyter_code>a = Verbose("a")
s = {a}
a.name = "b"
s.add(Verbose("b"))
s<jupyter_output><empty_output><jupyter_text>We've mutated our object `a` to a `b` after we put it in a set, and now the set contains 2 equal `b` objects. We've broken our set ! So that's why `list`s and `dict`s (which are mutables) cannot be put in sets, but `tuple`s and `frozenset`s (which are immutable) can.   Do we really need hash AND eq to compare objects ? isn't hash alone enough ? Given that there's a lower and upper limit to the hashes integer values, there are not lots of possible hashes compared to the number of different objects that might exist, so there are not enough integers to give a unique one to all the possible objects in universe. Here are a few examples :<jupyter_code>hash(1.000000000000001) == hash(2561)
hash(object) == hash(hash(object))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08762188515709643, 'fraction_numerical': 0.023429035752979416, 'mean_word_length': 3.715836526181354, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 33, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '527786', 'license': 'MIT', 'n_tokens_mistral': 2345, 'n_tokens_neox': 2183, 'n_words': 1092, 'path': '_posts/2016-05-08-of-hashes-and-pythons.ipynb', 'repo_name': 'ewjoachim/ewjoachim.github.io', 'size': '7384'}