Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
159 changes: 159 additions & 0 deletions Lib/annotationlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import sys
import types

lazy import typing

__all__ = [
"Format",
"ForwardRef",
Expand Down Expand Up @@ -410,6 +412,93 @@ def __convert_to_ast(self, other):
elts.append(new_elt)
ast_class = {list: ast.List, tuple: ast.Tuple, set: ast.Set}[type(other)]
return ast_class(elts), extra_names
elif type(other) is types.GenericAlias:
# Builtin generic aliases like list[Unknown]
origin = other.__origin__
args = other.__args__

if not (
isinstance(origin, _Stringifier)
or any(isinstance(arg, _Stringifier) for arg in args)
):
# The alias does not contain any forward references, use as-is
name = self.__stringifier_dict__.create_unique_name()
return ast.Name(id=name), {name: other}

origin_ast, elts, extra_names = self.__get_ast_origin_elts(origin, args)

# Generic Alias is not guaranteed to be from subscript
alias_ast, alias_names = self.__convert_to_ast(types.GenericAlias)
extra_names |= alias_names
new_ast = ast.Call(
func=alias_ast,
args=[origin_ast, elts],
)
return new_ast, extra_names
elif type(other) is types.UnionType:
origin = other.__origin__
args = other.__args__

if not any(isinstance(arg, _Stringifier) for arg in args):
# The union does not contain any forward references, use as-is
name = self.__stringifier_dict__.create_unique_name()
return ast.Name(id=name), {name: other}

origin_ast, elts, extra_names = self.__get_ast_origin_elts(origin, args)

new_ast = ast.Subscript(
value=origin_ast,
slice=elts,
)
return new_ast, extra_names
elif _is_typing_generic_alias(type(other)):
# User generic aliases
origin = typing.get_origin(other)
args = typing.get_args(other)

if not (
isinstance(origin, _Stringifier)
or any(isinstance(arg, _Stringifier) for arg in args)
):
# The alias does not contain any forward references, use as-is
name = self.__stringifier_dict__.create_unique_name()
return ast.Name(id=name), {name: other}

alias_inst = other._inst
alias_name = other._name
origin_ast, elts, extra_names = self.__get_ast_origin_elts(origin, args)

alias_ast, alias_names = self.__convert_to_ast(typing._GenericAlias)
extra_names |= alias_names

# alias_inst is a bool and alias_name a string or None so they have no extra_names
alias_inst_ast, _ = self.__convert_to_ast(alias_inst)
alias_name_ast, _ = self.__convert_to_ast(alias_name)

new_ast = ast.Call(
func=alias_ast,
args=[origin_ast, elts],
keywords=[
ast.keyword(arg="inst", value=alias_inst_ast),
ast.keyword(arg="name", value=alias_name_ast),
],
)
return new_ast, extra_names
elif _is_annotated_alias(other):
origin = typing.get_origin(other)
args = typing.get_args(other)

if not any(isinstance(arg, _Stringifier) for arg in args):
# The alias does not contain any forward references, use as-is
name = self.__stringifier_dict__.create_unique_name()
return ast.Name(id=name), {name: other}

origin_ast, elts, extra_names = self.__get_ast_origin_elts(origin, args)
new_ast = ast.Subscript(
value=origin_ast,
slice=elts,
)
return new_ast, extra_names
else:
name = self.__stringifier_dict__.create_unique_name()
return ast.Name(id=name), {name: other}
Expand Down Expand Up @@ -440,6 +529,28 @@ def __get_ast(self):
return ast.Name(id=node)
return node

def __get_ast_origin_elts(self, origin, args):
# Handle origin and args for generic syntax
extra_names = {}
elts = []

origin_ast, origin_names = self.__convert_to_ast(origin)
if origin_names is not None:
extra_names |= origin_names

for elt in args:
new_elt, new_extra_names = self.__convert_to_ast(elt)
if new_extra_names is not None:
extra_names |= new_extra_names
elts.append(new_elt)

if len(elts) == 1:
elts = elts[0]
else:
elts = ast.Tuple(elts=elts)

return origin_ast, elts, extra_names

def __make_new(self, node, extra_names=None):
new_extra_names = {}
if self.__extra_names__ is not None:
Expand Down Expand Up @@ -1191,7 +1302,55 @@ class _ExtraNameFixer(ast.NodeTransformer):
def __init__(self, extra_names):
self.extra_names = extra_names

def visit_Call(self, node: ast.Call):
# Convert calls to `GenericAlias` to their string representation
if isinstance((func := node.func), ast.Name) and (t := self.extra_names.get(func.id)):
if t is types.GenericAlias:
new_node = ast.Subscript(
value=node.args[0],
slice=node.args[1],
)
self.generic_visit(new_node)
return new_node

elif _is_typing_generic_alias(t):
# typing generics like typing.List have origin as the thing they are aliasing
# The correct name will be in the 'name' keyword arg in this case
name = None
for k in node.keywords:
if k.arg == "name":
if isinstance((const := k.value), ast.Constant) and const.value:
name = ast.Name(id=f"typing.{const.value}")
break

if name is None:
name = node.args[0]

new_node = ast.Subscript(
value=name,
slice=node.args[1],
)
self.generic_visit(new_node)
return new_node

self.generic_visit(node)
return node

def visit_Name(self, node: ast.Name):
if (new_name := self.extra_names.get(node.id, _sentinel)) is not _sentinel:
node = ast.Name(id=type_repr(new_name))
return node


def _is_annotated_alias(obj):
return (
(typing := sys.modules.get("typing"))
and typing.get_origin(obj) is typing.Annotated
)

def _is_typing_generic_alias(obj):
# Handle the private `typing._GenericAlias`
return (
(typing := sys.modules.get("typing"))
and obj is typing._GenericAlias
)
104 changes: 104 additions & 0 deletions Lib/test/test_annotationlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,110 @@ class UnionForwardrefs:
arg2, support.EqualToForwardRef("undefined", is_class=True, owner=UnionForwardrefs)
)

def test_nested_genericalias_deferred(self):
# Test that ForwardReferences inside generic aliases and
# typing.Annotated are correctly caught and resolved.

# Create a user generic class and simplify its string repr
class UserGeneric[T]: ...
UserGeneric.__qualname__ = "UserGeneric"
UserGeneric.__module__ = "usermodule"

# Old style typing.List is included to test typing._GenericAlias
# with ._inst = False and a value for ._name
class NestedForwardRefs:
genericalias: Unknown1[str, list[Unknown2]]
usergeneric: Unknown1[str, UserGeneric[Unknown2]]
typing_list: Unknown1[str, typing.List[Unknown2]]
typing_union: Unknown1[str, typing.Union[Unknown2, int]]
annotated: Unknown1[str, typing.Annotated[Unknown2, '']]
extra_nested: Unknown3[tuple[Unknown4[list[Unknown5]]]]

# Generics with no internal forward references are stored as one value
# and are not reconstructed directly.
known_internal_generic: Unknown1[str, list[int]]
known_internal_typing_generic: Unknown1[str, UserGeneric[int]]
known_internal_typing_union: Unknown1[str, typing.Union[str, int]]
known_internal_annotated: Unknown1[str, typing.Annotated[str, '']]

annos = get_annotations(NestedForwardRefs, format=Format.FORWARDREF)

# Tuples of annotation name, expected string, expected value, needs_unknown2
subtests = (
# These annotations fail to resolve if Unknown2 is not defined
("genericalias", "Unknown1[str, list[Unknown2]]", tuple[str, list[str]], True),
("usergeneric", "Unknown1[str, usermodule.UserGeneric[Unknown2]]", tuple[str, UserGeneric[str]], True),
("typing_list", "Unknown1[str, typing.List[Unknown2]]", tuple[str, typing.List[str]], True),
("typing_union", "Unknown1[str, typing.Union[Unknown2, int]]", tuple[str, typing.Union[str, int]], True),
("annotated", "Unknown1[str, typing.Annotated[Unknown2, '']]", tuple[str, typing.Annotated[str, '']], True),
("extra_nested", "Unknown3[tuple[Unknown4[list[Unknown5]]]]", list[tuple[set[list[int]]]], True),

# These annotations do not require Unknown2 to be defined to resolve
("known_internal_generic", "Unknown1[str, list[int]]", tuple[str, list[int]], False),
("known_internal_typing_generic", "Unknown1[str, usermodule.UserGeneric[int]]", tuple[str, UserGeneric[int]], False),
("known_internal_typing_union", "Unknown1[str, str | int]", tuple[str, typing.Union[str, int]], False),
("known_internal_annotated", "Unknown1[str, typing.Annotated[str, '']]", tuple[str, typing.Annotated[str, '']], False)
)

for name, str_result, _, _ in subtests:
with self.subTest(type="Format.STRING Evaluation", annotation=name):
self.assertEqual(annos[name].evaluate(format=Format.STRING), str_result)

Unknown1 = tuple

# Unknown2 is still undefined, these should raise
for name, _, _, should_fail in subtests:
if should_fail:
with self.subTest(type="Undefined raise NameError", annotation=name):
with self.assertRaises(NameError):
annos[name].evaluate()

# Once all names are defined, they fully evaluate correctly
Unknown2 = str
Unknown3 = list
Unknown4 = set
Unknown5 = int

for name, _, resolved, _ in subtests:
with self.subTest(type="format.VALUE evaluation", annotation=name):
self.assertEqual(annos[name].evaluate(), resolved)

def test_nested_genericalias_nonsubscript(self):
# Test that ForwardRef works correctly for generic aliases that aren't
# created through subscripting
class NonSubscriptableGeneric:
@classmethod
def get_generic(cls, *args):
return types.GenericAlias(cls, args)

nsrepr = type_repr(NonSubscriptableGeneric)

with self.assertRaises(TypeError):
_ = NonSubscriptableGeneric[str]

class C:
x: Unknown1[NonSubscriptableGeneric.get_generic(str, Unknown2)]

ann = get_annotations(C, format=Format.FORWARDREF)['x']

Unknown1 = list

with self.assertRaises(NameError):
ann.evaluate()

Unknown2 = int

self.assertEqual(
ann.evaluate(),
list[NonSubscriptableGeneric.get_generic(str, int)],
)

# The string representation should look like the __repr__ for GenericAlias
self.assertEqual(
ann.evaluate(format=Format.STRING),
f"Unknown1[{nsrepr}[str, Unknown2]]",
)


class TestStringFormat(unittest.TestCase):
def test_closure(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix :mod:`annotationlib` forward references inside a :class:`types.GenericAlias` or :class:`typing.Annotated` inside an outer :class:`annotationlib.ForwardRef` no longer evade evaluation.
Loading