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

gh-114053: Fix another edge case involving get_type_hints, PEP 695 and PEP 563 #120272

Merged
merged 10 commits into from
Jun 25, 2024

Conversation

AlexWaygood
Copy link
Member

@AlexWaygood AlexWaygood commented Jun 8, 2024

This PR fixes a bug in #118009 that can be seen in the following REPL demo, where get_type_hints under from __future__ import annotations semantics won't detect if a variable defined in a type-parameter namespace has been overidden in a local namespace:

Python 3.14.0a0 (heads/getannotations-nameerror:ec4848f2c8b, Jun  8 2024, 15:28:33) [Clang 15.0.0 (clang-1500.3.9.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo[T]:
...     T = int
...     x: T
...     
>>> Foo.__annotations__
{'x': <class 'int'>}
>>> from __future__ import annotations
>>> class Foo[T]:
...     T = int
...     x: T
...     
>>> from typing import get_type_hints
>>> get_type_hints(Foo)
{'x': T}

The cause of the bug is that get_type_hints does this weird swapping of globals and locals, and the logic added in #118009 doesn't account for that -- it injects the type parameters into the dictionary called localns (which is actually the globals) when it should be injecting the type parameters into globalns (which is actually the locals).

I actually added a test for this exact edge case in #118009, which should have caught the bug. But there was a bug in the test, because the test was trying to be too clever, and I got mixed up between ^ and & when you're using sets. Had I not tried to write such a clever test, I would have caught the bug.

Copy link
Member

@JelleZijlstra JelleZijlstra left a comment

Choose a reason for hiding this comment

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

Can you add a test where T also exists in the global scope, ensuring that the type param is picked up over the global?

@AlexWaygood
Copy link
Member Author

Can you add a test where T also exists in the global scope, ensuring that the type param is picked up over the global?

Thanks, good catch -- that test failed. I added it and fixed it.

Lib/typing.py Outdated Show resolved Hide resolved
Lib/typing.py Outdated Show resolved Hide resolved
@AlexWaygood
Copy link
Member Author

AlexWaygood commented Jun 9, 2024

Okay, this still doesn't get things right in all cases :(

>>> from __future__ import annotations
>>> from typing import get_type_hints
>>> Eggs, Spam = int, str
>>> def f[Eggs, **Spam](x: Eggs, y: Spam): pass
... 
>>> get_type_hints(f)
{'x': <class 'int'>, 'y': <class 'str'>}

@AlexWaygood
Copy link
Member Author

Okay, this still doesn't get things right in all cases :(

>>> from __future__ import annotations
>>> from typing import get_type_hints
>>> Eggs, Spam = int, str
>>> def f[Eggs, **Spam](x: Eggs, y: Spam): pass
... 
>>> get_type_hints(f)
{'x': <class 'int'>, 'y': <class 'str'>}

Should have been fixed in 2fbcd7b.

globalns, localns = dict(globalns), dict(localns)
for param in type_params:
param_name = param.__name__
if not self.__forward_is_class__ or param_name not in globalns:
Copy link
Member

Choose a reason for hiding this comment

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

Why do we need the __forward_is_class__ condition? I don't understand why class-scoped forwardrefs are special here.

Copy link
Member Author

@AlexWaygood AlexWaygood Jun 13, 2024

Choose a reason for hiding this comment

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

For functions, names in type_params should always take highest priority, and this is implemented by inserting the type params into the local namespace (which is here called globalns) and popping them from the global namespace (which is here called localns). For classes, we only want to give type_params highest priority if they haven't been overridden in the local scope, however.

param_name = param.__name__
if not self.__forward_is_class__ or param_name not in globalns:
globalns[param_name] = param
localns.pop(param_name, None)
Copy link
Member

Choose a reason for hiding this comment

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

Why do we need to do this? Shouldn't the local namespace override the type params?

Test case:

class X[T]:
    T = int
    x: T

Copy link
Member Author

Choose a reason for hiding this comment

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

I already have that test case included in this PR, and it fails unless we have this block of code here. The local namespace shoudl indeed override the type param, but the locals here are found in the globalns, and the globals here are found in the localns variable. This highly confusing situation is because the globals and locals are swapped higher up in the call stack here, for backwards compatibility reasons if you believe the comment:

cpython/Lib/typing.py

Lines 2419 to 2426 in a3711af

if localns is None and globalns is None:
# This is surprising, but required. Before Python 3.10,
# get_type_hints only evaluated the globalns of
# a class. To maintain backwards compatibility, we reverse
# the globalns and localns order so that eval() looks into
# *base_globals* first rather than *base_locals*.
# This only affects ForwardRefs.
base_globals, base_locals = base_locals, base_globals

Copy link
Member

Choose a reason for hiding this comment

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

I saw that comment, maybe we should find a way to get rid of that compatibility hack.

Copy link
Member Author

Choose a reason for hiding this comment

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

I don't really see a way round it, short of deprecating get_type_hints altogether. Which... I'm not 100% against, but it would be quite disruptive.

Copy link
Member

Choose a reason for hiding this comment

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

There could be other approaches, like adding new keyword arguments. Will have to think about it more.

Copy link
Contributor

@picnixz picnixz Jun 14, 2024

Choose a reason for hiding this comment

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

If you decide to add keywords arguments or deprecate things, please tell me in advance so that I can be reactive on Sphinx' side if needed.

@AlexWaygood
Copy link
Member Author

@JelleZijlstra, are you okay with this going in? I'd love to get this into the next 3.13 beta if possible (but at the same time, the bug also exists in Python 3.12, so it wouldn't be a disaster if it waited until beta 4).

I agree that the implementation is kinda weird but I'm not sure there's a better way of doing it until we've sorted out the strange globals/locals swapping (which I think would probably be harder to backport to 3.12).

@AlexWaygood AlexWaygood merged commit 2d3187b into python:main Jun 25, 2024
35 checks passed
@AlexWaygood AlexWaygood deleted the gettypehints-bug branch June 25, 2024 15:53
@miss-islington-app
Copy link

Thanks @AlexWaygood for the PR 🌮🎉.. I'm working now to backport this PR to: 3.12, 3.13.
🐍🍒⛏🤖

miss-islington pushed a commit to miss-islington/cpython that referenced this pull request Jun 25, 2024
…P 695 and PEP 563 (pythonGH-120272)

(cherry picked from commit 2d3187b)

Co-authored-by: Alex Waygood <[email protected]>
@bedevere-app
Copy link

bedevere-app bot commented Jun 25, 2024

GH-121003 is a backport of this pull request to the 3.13 branch.

miss-islington pushed a commit to miss-islington/cpython that referenced this pull request Jun 25, 2024
…P 695 and PEP 563 (pythonGH-120272)

(cherry picked from commit 2d3187b)

Co-authored-by: Alex Waygood <[email protected]>
@bedevere-app bedevere-app bot removed the needs backport to 3.13 bugs and security fixes label Jun 25, 2024
@bedevere-app
Copy link

bedevere-app bot commented Jun 25, 2024

GH-121004 is a backport of this pull request to the 3.12 branch.

@bedevere-app bedevere-app bot removed the needs backport to 3.12 bug and security fixes label Jun 25, 2024
AlexWaygood added a commit that referenced this pull request Jun 25, 2024
AlexWaygood added a commit that referenced this pull request Jun 25, 2024
mrahtz pushed a commit to mrahtz/cpython that referenced this pull request Jun 30, 2024
noahbkim pushed a commit to hudson-trading/cpython that referenced this pull request Jul 11, 2024
estyxx pushed a commit to estyxx/cpython that referenced this pull request Jul 17, 2024
JelleZijlstra added a commit to JelleZijlstra/cpython that referenced this pull request Jul 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants