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

bpo-41341: Recursive evaluation of ForwardRef in get_type_hints #21553

Merged
merged 2 commits into from
Jul 22, 2020
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
Next Next commit
bpo-41341: Recursive evaluation of ForwardRef in get_type_hints
The issue raised by recursive evaluation is infinite recursion with
recursive types. In that case, only the first recursive ForwardRef is
evaluated.
  • Loading branch information
wyfo committed Jul 20, 2020
commit 2389c257ea8a480c9a011cac5cda7eb947ed3bca
6 changes: 6 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2456,6 +2456,12 @@ def foo(a: tuple[ForwardRef('T')]):
self.assertEqual(get_type_hints(foo, globals(), locals()),
{'a': tuple[T]})

def test_double_forward(self):
def foo(a: 'List[\'int\']'):
Copy link
Member

Choose a reason for hiding this comment

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

I was about to approve this PR when I realized that we should make this work with list -- I tried and it doesn't currently.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

You're right concerning the fact that it doesn't work with list, but I've found that it's not related to this PR; actually, I think there is a significant defect in current PEP 585 implementation. In fact:

from dataclasses import dataclass, field
from typing import get_type_hints, List, ForwardRef

@dataclass
class Node:
    children: list["Node"] = field(default_factory=list)
    children2: List["Node"] = field(default_factory=list)

assert get_type_hints(Node) == {"children": list["Node"], "children2": List[Node]}
assert List["Node"].__args__ == (ForwardRef("Node"),)
assert list["Node"].__args__ == ("Node",)  # No ForwardRef here, so no evaluation by get_type_hints

I will open an issue on bugs.python.org to discuss about this, because I think this PR is not the best place to do it.

Copy link
Member

Choose a reason for hiding this comment

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

Heh, you're right, thanks for the analysis. We probably will not ever support this: importing ForwardRef from the built-in generic alias code would be problematic, and once from __future__ import annotations is always on there's no need to quote the argument anyway. Sorry for the hiccup. I will now approve your PR.

pass
self.assertEqual(get_type_hints(foo, globals(), locals()),
{'a': List[int]})

def test_forward_recursion_actually(self):
def namespace1():
a = typing.ForwardRef('A')
Expand Down
20 changes: 14 additions & 6 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,14 +244,16 @@ def inner(*args, **kwds):
return inner


def _eval_type(t, globalns, localns):
def _eval_type(t, globalns, localns, recursive_guard=frozenset()):
"""Evaluate all forward reverences in the given type t.
For use of globalns and localns see the docstring for get_type_hints().
recursive_guard is used to prevent prevent infinite recursion
with recursive ForwardRef.
"""
if isinstance(t, ForwardRef):
return t._evaluate(globalns, localns)
return t._evaluate(globalns, localns, recursive_guard)
if isinstance(t, (_GenericAlias, GenericAlias)):
ev_args = tuple(_eval_type(a, globalns, localns) for a in t.__args__)
ev_args = tuple(_eval_type(a, globalns, localns, recursive_guard) for a in t.__args__)
if ev_args == t.__args__:
return t
if isinstance(t, GenericAlias):
Expand Down Expand Up @@ -477,18 +479,24 @@ def __init__(self, arg, is_argument=True):
self.__forward_value__ = None
self.__forward_is_argument__ = is_argument

def _evaluate(self, globalns, localns):
def _evaluate(self, globalns, localns, recursive_guard):
if self.__forward_arg__ in recursive_guard:
return self
if not self.__forward_evaluated__ or localns is not globalns:
if globalns is None and localns is None:
globalns = localns = {}
elif globalns is None:
globalns = localns
elif localns is None:
localns = globalns
self.__forward_value__ = _type_check(
type_ =_type_check(
eval(self.__forward_code__, globalns, localns),
"Forward references must evaluate to types.",
is_argument=self.__forward_is_argument__)
is_argument=self.__forward_is_argument__,
)
self.__forward_value__ = _eval_type(
type_, globalns, localns, recursive_guard | {self.__forward_arg__}
)
self.__forward_evaluated__ = True
return self.__forward_value__

Expand Down