Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include the struct type in frozen hash implementation #595

Merged
merged 1 commit into from
Nov 27, 2023

Conversation

jcrist
Copy link
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
8 checks passed
@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