classification
Title: Recursive evaluation of ForwardRef (and PEP 563)
Type: behavior Stage: resolved
Components: Versions:
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: Nosy List: BTaskaya, eric.smith, gvanrossum, joperez, levkivskyi, lukasz.langa, miss-islington, vstinner
Priority: normal Keywords: patch

Created on 2020-07-19 11:28 by joperez, last changed 2020-07-26 15:35 by gvanrossum. This issue is now closed.

Pull Requests
URL Status Linked Edit
PR 21553 merged joperez, 2020-07-20 01:37
PR 21629 merged miss-islington, 2020-07-26 15:08
Messages (7)
msg373960 - (view) Author: Joseph Perez (joperez) * Date: 2020-07-19 11:28
(This issue is already broached in https://bugs.python.org/issue38605, and a in some way in https://bugs.python.org/issue35834, but only as a secondary subject, that's why I've opened a ticket on this particular issue)

ForwardRef of ForwardRef are not currently evaluated by get_type_hints, only the first level is, as illustrated in these examples:
```python
from typing import ForwardRef, Optional, get_type_hints
def func(a: "Optional[\"int\"]"):
    pass
assert get_type_hints(func)["a"] == Optional[ForwardRef("int")] 
# one would expect get_type_hints(func)["a"] == Optional[int] 
```
```python
from __future__ import annotations
from typing import ForwardRef, Optional, get_type_hints
def func(a: Optional["int"]):
    pass
assert get_type_hints(func)["a"] == Optional[ForwardRef("int")]
# one would expect get_type_hints(func)["a"] == Optional[int] (which is the case without the import of __future__.annotations!)
```
On the one hand I find this behavior quite counter-intuitive; I rather think ForwardRef as kind of internal (and wonder why there is no leading underscore, like _GenericAlias where it's used) and I don't understand the purpose of exposing it as the result of the public API get_type_hints. By the way, if ForwardRef can be obtained by retrieving annotations without get_type_hints, stringified annotations (especially since PEP 563) make get_type_hints kind of mandatory, and thus make ForwardRef disappeared (only at the first level so …)

On the other hand, the second example show that adoptions of postponed annotations can change the result of get_type_hints; several libraries relying of get_type_hints could be broken.

An other issue raised here is that if these ForwardRef are not evaluated by get_type_hints, how will be done their evaluatation by the user? It would require to retrieve some globalns/localns — too bad, it's exactly what is doing get_type_hints. And if the ForwardRef is in a class field, the class globalns/localns will have to be kept somewhere while waiting to encounter these random ForwardRef; that's feasible, but really tedious.

Agreeing with Guido Von Rossum (https://bugs.python.org/msg370232), this behavior could be easily "fixed" in get_type_hints.
Actually, there would be only one line to change in ForwardRef._evaluate:
```python
# from
self.__forward_value__ = _type_check(
    eval(self.__forward_code__, globalns, localns),
    "Forward references must evaluate to types.",
    is_argument=self.__forward_is_argument__)
# to
self.__forward_value__ = _eval_type(
    _type_check(
        eval(
            self.__forward_code__, globalns, localns),
            "Forward references must evaluate to types.",
            is_argument=self.__forward_is_argument__,
        ),
    globalns,
    localns,
)

And if this fix could solve the "double ForwardRef" issue mentionned in https://bugs.python.org/issue38605, it would also resolve https://bugs.python.org/issue35834 in the same time, raising NameError in case of unknown ForwardRef with postponed annotation.
msg373978 - (view) Author: Joseph Perez (joperez) * Date: 2020-07-20 01:47
Ok, I admit that I did not think about recursive type when proposing this "fix".
I've tried an implementation that just stop when recursion is encountered in a PR.
msg374102 - (view) Author: Guido van Rossum (gvanrossum) * (Python committer) Date: 2020-07-22 19:47
New changeset 653f420b53a3aa87316cef59de8d3f5d9e11deb4 by wyfo in branch 'master':
bpo-41341: Recursive evaluation of ForwardRef in get_type_hints (#21553)
https://github.com/python/cpython/commit/653f420b53a3aa87316cef59de8d3f5d9e11deb4
msg374104 - (view) Author: Guido van Rossum (gvanrossum) * (Python committer) Date: 2020-07-22 20:02
Łukasz, can I please have a decision on whether to backport this bugfix to 3.9?

See my comment about that:
https://github.com/python/cpython/pull/21553#pullrequestreview-452895735
msg374318 - (view) Author: Łukasz Langa (lukasz.langa) * (Python committer) Date: 2020-07-26 15:06
Given the previous behavior was clearly a bug and after looking at the PR, I think it should go into 3.9.0rc1.
msg374324 - (view) Author: miss-islington (miss-islington) Date: 2020-07-26 15:31
New changeset 41d1c04f73185c1238680142aa1a81f54f2bf4a4 by Miss Islington (bot) in branch '3.9':
bpo-41341: Recursive evaluation of ForwardRef in get_type_hints (GH-21553)
https://github.com/python/cpython/commit/41d1c04f73185c1238680142aa1a81f54f2bf4a4
msg374327 - (view) Author: Guido van Rossum (gvanrossum) * (Python committer) Date: 2020-07-26 15:35
Thank you Joseph Perez! Looking forward to more of your contributions.
History
Date User Action Args
2020-07-26 15:35:12gvanrossumsetstatus: open -> closed
resolution: fixed
messages: + msg374327

stage: patch review -> resolved
2020-07-26 15:31:27miss-islingtonsetmessages: + msg374324
2020-07-26 15:08:43miss-islingtonsetnosy: + miss-islington
pull_requests: + pull_request20770
2020-07-26 15:06:46lukasz.langasetmessages: + msg374318
2020-07-22 20:02:01gvanrossumsetmessages: + msg374104
2020-07-22 19:47:35gvanrossumsetmessages: + msg374102
2020-07-20 01:47:38joperezsetmessages: + msg373978
2020-07-20 01:37:50joperezsetkeywords: + patch
stage: patch review
pull_requests: + pull_request20699
2020-07-19 11:28:27joperezcreate