Skip to content

gh-133925: Make typing._UnionGenericAlias hashable #133929

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

Merged
merged 2 commits into from
May 12, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -10668,6 +10668,9 @@ def test_eq(self):
with self.assertWarns(DeprecationWarning):
self.assertNotEqual(int, typing._UnionGenericAlias)

def test_hashable(self):
self.assertIsInstance(hash(typing._UnionGenericAlias), int)


def load_tests(loader, tests, pattern):
import doctest
Expand Down
3 changes: 3 additions & 0 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1649,6 +1649,9 @@ def __eq__(self, other):
return True
return NotImplemented

def __hash__(self):
return super().__hash__()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This means that a Union instance and a _UnionGenericAlias instance might compare equal but hash differently, right? Might that do counterintuitive things if you used them as dictionary keys or put them in sets?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that this is purely about the _UnionGenericAlias class itself, not _UnionGenericAlias instances.

Btw, do we need to add __hash__ tests to instances in other PR?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that this is purely about the _UnionGenericAlias class itself, not _UnionGenericAlias instances.

ah, thanks, great point. It still seems like users are storing the classes themselves in sets, though, so I think my point still applies -- the bug report here comes from astropy/astropy#18126

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I should have made it hash() equal to Union. Fixed now.



class _UnionGenericAlias(metaclass=_UnionGenericAliasMeta):
"""Compatibility hack.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Make the private class ``typing._UnionGenericAlias`` hashable.
Loading