FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

bpo-41370: Evaluate strings as forward refs in PEP 585 generics by NiklasRosenstein · Pull Request #30900 · python/cpython · GitHub

/ cpython Public
Merged
44 changes: 42 additions & 2 deletions Lib/test/test_typing.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from typing import ParamSpec, Concatenate, ParamSpecArgs, ParamSpecKwargs
from typing import TypeGuard
import abc
import textwrap
import typing
import weakref
import types
Expand Down Expand Up @@ -2006,6 +2007,45 @@ def barfoo(x: AT): ...
def barfoo2(x: CT): ...
self.assertIs(get_type_hints(barfoo2, globals(), locals())['x'], CT)

def test_generic_pep585_forward_ref(self):
# See https://bugs.python.org/issue41370

class C1:
a: list['C1']
self.assertEqual(
get_type_hints(C1, globals(), locals()),
{'a': list[C1]}
)

class C2:
a: dict['C1', list[List[list['C2']]]]
self.assertEqual(
get_type_hints(C2, globals(), locals()),
{'a': dict[C1, list[List[list[C2]]]]}
)

# Test stringified annotations
scope = {}
exec(textwrap.dedent('''
from __future__ import annotations
class C3:
a: List[list["C2"]]
'''), scope)
C3 = scope['C3']
self.assertEqual(C3.__annotations__['a'], "List[list['C2']]")
self.assertEqual(
get_type_hints(C3, globals(), locals()),
{'a': List[list[C2]]}
)

# Test recursive types
X = list["X"]
def f(x: X): ...
self.assertEqual(
get_type_hints(f, globals(), locals()),
{'x': list[list[ForwardRef('X')]]}
)

def test_extended_generic_rules_subclassing(self):
class T1(Tuple[T, KT]): ...
class T2(Tuple[T, ...]): ...
Expand Down Expand Up @@ -3270,15 +3310,15 @@ def foobar(x: list[ForwardRef('X')]): ...
BA = Tuple[Annotated[T, (1, 0)], ...]
def barfoo(x: BA): ...
self.assertEqual(get_type_hints(barfoo, globals(), locals())['x'], Tuple[T, ...])
self.assertIs(
self.assertEqual(
get_type_hints(barfoo, globals(), locals(), include_extras=True)['x'],
BA
)

BA = tuple[Annotated[T, (1, 0)], ...]
def barfoo(x: BA): ...
self.assertEqual(get_type_hints(barfoo, globals(), locals())['x'], tuple[T, ...])
self.assertIs(
self.assertEqual(
get_type_hints(barfoo, globals(), locals(), include_extras=True)['x'],
BA
)
Expand Down
6 changes: 6 additions & 0 deletions Lib/typing.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,12 @@ def _eval_type(t, globalns, localns, recursive_guard=frozenset()):
if isinstance(t, ForwardRef):
return t._evaluate(globalns, localns, recursive_guard)
if isinstance(t, (_GenericAlias, GenericAlias, types.UnionType)):
if isinstance(t, GenericAlias):
args = tuple(
ForwardRef(arg) if isinstance(arg, str) else arg

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Do we need to pass globals and locals to ForwardRef here? 🤔

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

I may not be knowledgable enough about the typing code base, but I don't see a globals/locals argument for ForwardRef. Do you mean the module? I couldn't find out how to use/what to pass to that argument exactly.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

It's too late for that anyway. The ForwardRef class has an optional module= argument which may be used to resolve references, but the best we could do at this point is passing globalns.get("__name__"), which would just end up with the same globalns as we are using anyway.

This suggests there could still be scenarios where this will fail, esp. when a type alias defined in one module is used in another. But that would only be solvable by recording the module at the time the alias is being defined, and we've already said we wouldn't go that far (since it would require a ForwardRef implementation in C).

for arg in t.__args__
)
t = t.__origin__[args]
ev_args = tuple(_eval_type(a, globalns, localns, recursive_guard) for a in t.__args__)
if ev_args == t.__args__:
return t
Expand Down
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:func:`typing.get_type_hints` now supports evaluating strings as forward references in :ref:`PEP 585 generic aliases <types-genericalias>`.

Back | FazBrowse Home | New Git URL