jcrist / msgspec

A fast serialization and validation library, with builtin support for JSON, MessagePack, YAML, and TOML
https://jcristharif.com/msgspec/
BSD 3-Clause "New" or "Revised" License
2.45k stars 76 forks source link

Include the struct type in frozen hash implementation #595

Closed jcrist closed 1 year ago

jcrist commented 1 year ago

This modifies the provided hash method to also include the struct type. This improves hash quality for mappings or sets that contain multiple different struct types as keys, as structs of different types with the same data will now hash differently, better matching the __eq__ implementation.

As an implementation detail, structs should now hash as a tuple of the type and all following elements.

from msgspec import Struct

class Point(Struct, frozen=True):
    x: int
    y: int

assert hash(Point(1, 2)) == hash((Point, 1, 2))

Addresses part of #591.