[Python] What happens if an object's __hash__ changes?

Discussão em 'Python' iniciado por Stack, Março 12, 2025.

  1. Stack

    Stack Membro Participativo

    In Python, I know that the value __hash__ returns for a given object is supposed to be the same for the lifetime of that object. But, out of curiosity, what happens if it isn't? What sort of havoc would this cause?

    class BadIdea(object):
    def __hash__(self):
    return random.randint(0, 10000)


    I know __contains__ and __getitem__ would behave strangely, and dicts and sets would act odd because of that. You also might end up with "orphaned" values in the dict/set.

    What else could happen? Could it crash the interpreter, or corrupt internal structures?

    Continue reading...

Compartilhe esta Página