Skip to content

Include the struct type in frozen hash implementation#595

Merged
jcrist merged 1 commit intomainfrom
include-struct-type-in-hash
Nov 27, 2023
Merged

Include the struct type in frozen hash implementation#595
jcrist merged 1 commit intomainfrom
include-struct-type-in-hash

Conversation

@jcrist
Copy link
Copy Markdown
Owner

@jcrist jcrist commented Nov 27, 2023

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.

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.

```python
from msgspec import Struct

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

assert hash(Point(1, 2)) == hash((Point, 1, 2))
```
@jcrist jcrist mentioned this pull request Nov 27, 2023
@jcrist jcrist merged commit a3927c7 into main Nov 27, 2023
@jcrist jcrist deleted the include-struct-type-in-hash branch November 27, 2023 04:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant