[Python] Why are class instances (hashable) allowed as dictionary keys in Python if they are...

Discussão em 'Python' iniciado por Stack, Abril 6, 2025.

  1. Stack

    Stack Membro Participativo

    class MyClass:
    def __init__(self, value):
    self.value = value

    obj = MyClass(10)
    my_dict = {obj: "Hello"}


    This works, even though obj is clearly mutable.

    How is this allowed?

    Doesn't this break the requirement for dictionary keys to be immutable?

    How does Python ensure hash consistency if object attributes can change?

    I understand that the default behavior uses id() for __hash__ and __eq__, but I'd like to understand the design rationale and best practices around using class instances as dict keys.

    Continue reading...

Compartilhe esta Página