fix(python): make union case classes hashable again#4805
Merged
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #4804
Hashing a union value that contains another union as a field raises TypeError: unhashable type at runtime, e.g.
The same code works on .NET and JS, and breaks things like
List.distinctor using unions as dictionary keys on Python.The
tagged_uniondecorator appliesdataclass()to every case class. Since that generates__eq__withoutfrozen=True, Python sets__hash__ = Noneon the class, shadowing the__hash__the Union base inherits fromHashableBase. So case classes were explicitly unhashable, andUnion.GetHashCode (hash((self.tag, *self.fields)))blows up as soon as a field is itself a union. The decorator's docstring already claims__hash__is generated. This restores it after thedataclass()call. It's consistent with the dataclass__eq__: equal values have equal(tag, *fields), hence equal hashes.Added tests for the hash protocol, hash/eq consistency, nested unions and set membership.
One note: type checkers still consider the case classes unhashable statically (
dataclass_transformmodels them as non-frozen dataclasses), even though__hash__now exists at runtime.