Skip to content

gh-130870: Preserve GenericAlias subclasses in typing.get_type_hints() - #131583

Merged
JelleZijlstra merged 3 commits into
python:mainfrom
Viicos:gh-130870
Jul 5, 2025
Merged

JelleZijlstra merged 3 commits into
python:mainfrom
Viicos:gh-130870

Conversation

@Viicos

@Viicos Viicos commented Mar 22, 2025 •

Copy link
Copy Markdown
Contributor

This is an alternative approach to #130897, that avoids recreating GenericAlias instances two times (no noticeable performance improvement but cleans up the implementation).

It also fixes the GenericAlias reconstruction in _strip_annotations(), and as such I moved the logic into a separate function.

This approach has the benefit of not losing the __unpacked__ property of the GenericAlias if no forward annotation is present in the type hint. That is:

def func(*args: *tuple[int]): ...

get_type_hints(func)
# On main:
# {'args': typing.Unpack[tuple[int]]}
# On this branch:
# {'args': *tuple[int]} (that is, gth(func)['args'] is the same `GenericAlias` instance, with `__unpacked__ = True`)

A couple tests are failing due to this, I'm not sure how we can test this? Maybe like:

def func2(*args: *tuple[int, str]): pass
self.assertEqual(gth(func2), func2.__annotations__)
self.assertTrue(gth(func2)['args'].__unpacked__)
@JelleZijlstra

Copy link
Copy Markdown
Member

This generally makes sense to me, though there's a series of issues in CI. I think this can only go into 3.15 at this point.

@ZeroIntensity

Copy link
Copy Markdown
Member

Yeah, this feels like a feature to me.

@Viicos

Viicos commented Jun 9, 2025

Copy link
Copy Markdown
Contributor Author

I would rather consider this as a bug fix but the risk of regressions is relatively high so it also makes sense to me to include this in 3.15 only as well.

@JelleZijlstra
JelleZijlstra merged commit 5b56daa into python:main Jul 5, 2025
AndPuQing pushed a commit to AndPuQing/cpython that referenced this pull request Jul 11, 2025
Pranjal095 pushed a commit to Pranjal095/cpython that referenced this pull request Jul 12, 2025
picnixz pushed a commit to picnixz/cpython that referenced this pull request Jul 13, 2025
taegyunkim pushed a commit to taegyunkim/cpython that referenced this pull request Aug 4, 2025
Agent-Hellboy pushed a commit to Agent-Hellboy/cpython that referenced this pull request Aug 19, 2025
@Viicos
Viicos deleted the gh-130870 branch October 20, 2025 12:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants