Skip to content

gh-160766: Handle nested annotated and generic aliases that contain forward references in annotations - #160769

Open
DavidCEllis wants to merge 6 commits into
python:mainfrom
DavidCEllis:fix-nested-forwardref-annos
Open

DavidCEllis wants to merge 6 commits into
python:mainfrom
DavidCEllis:fix-nested-forwardref-annos

Conversation

@DavidCEllis

@DavidCEllis DavidCEllis commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

This adds another special case to _Stringifier.__convert_to_ast to handle types.GenericAlias and typing.Annotated similar to the handling of list, set, tuple, dict that constructs the ast to rebuild the GenericAlias or Annotated object.

This is to prevent the ForwardRef objects from becoming "hidden" inside the GenericAlias or Annotated objects.

For GenericAlias an ast.Call node is created to reconstruct the GenericAlias as there's no guarantee it was created through subscripting. The call is converted back to subscript format when evaluating the ForwardRef in STRING format in order to match the repr of GenericAlias objects.

For Annotated, subscripting is used. Are there any other types that need to be handled?

from annotationlib import get_annotations, Format

class X:
    a: Y[list[Z]]

# Get annotations here to get the ForwardRef
anno = get_annotations(X, format=Format.FORWARDREF)['a']

class Y[T]:
    pass

class Z:
    pass

print(anno.evaluate(format=Format.STRING))
print(anno.evaluate(format=Format.VALUE))

Main:

Y[list[ForwardRef('Z', is_class=True, owner=<class '__main__.X'>)]]
__main__.Y[list[ForwardRef('Z', is_class=True, owner=<class '__main__.X'>)]]

PR:

Y[list[Z]]
__main__.Y[list[__main__.Z]]

Comment thread Lib/annotationlib.py Outdated
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 or _is_annotated_alias(other):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should this be

Suggested change
elif type(other) is types.GenericAlias or _is_annotated_alias(other):
elif isinstance(other, types.GenericAlias) or _is_annotated_alias(other):

?

GenericAlias can be subclassed.

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.

As can list/dict/tuple/set. Subclassing could change the constructor and we wouldn't necessarily be able to reconstruct the object correctly.

However I did discover that there's a typing._GenericAlias that is used when you make your own generic classes using the class A[T]: ... syntax which isn't the same as types.GenericAlias that will also need to be handled. It's also not a subclass of types.GenericAlias so checking for subclasses wouldn't catch it either.

This will also need to be handled:

from annotationlib import get_annotations, Format

class Q[T]: ...

class X:
    a: Y[Q[Z]]

# Get annotations here to get the ForwardRef
anno = get_annotations(X, format=Format.FORWARDREF)['a']

class Y[T]:
    pass

class Z:
    pass

print(anno.evaluate(format=Format.STRING))
print(anno.evaluate(format=Format.VALUE))
Y[__main__.Q[ForwardRef('Z', is_class=True, owner=<class '__main__.X'>)]]
__main__.Y[__main__.Q[ForwardRef('Z', is_class=True, owner=<class '__main__.X'>)]]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

So I'm not to familiar with the stringifier API from annotationlib, but I believe we usually assume subclasses respect the LSP for the constructor. For reference, typing._eval_type() has this logic to rebuild aliases:

cpython/Lib/typing.py

Lines 476 to 503 in 3b30937

if isinstance(t, (_GenericAlias, GenericAlias, Union)):
if isinstance(t, _LiteralGenericAlias):
# Unlike other generic aliases, Literal arguments aren't type expressions
return t
if isinstance(t, GenericAlias):
args = tuple(
_make_forward_ref(arg, parent_fwdref=parent_fwdref) if isinstance(arg, str) else arg
for arg in t.__args__
)
else:
args = t.__args__
ev_args = tuple(
_eval_type(
a, globalns, localns, type_params, recursive_guard=recursive_guard,
format=format, owner=owner, prefer_fwd_module=prefer_fwd_module,
)
for a in args
)
if ev_args == t.__args__:
return t
if isinstance(t, GenericAlias):
return _rebuild_generic_alias(t, ev_args)
if isinstance(t, Union):
return Union[ev_args]
else:
return t.copy_with(ev_args)
return t

With _rebuild_generic_alias() defined as:

cpython/Lib/typing.py

Lines 437 to 445 in 3b30937

def _rebuild_generic_alias(alias: GenericAlias, args: tuple[object, ...]) -> GenericAlias:
is_unpacked = alias.__unpacked__
if _should_unflatten_callable_args(alias, args):
t = alias.__origin__[(args[:-1], args[-1])]
else:
t = alias.__origin__[args]
if is_unpacked:
t = Unpack[t]
return t

For typing._GenericAlias instances, the copy_with() method is used.

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.

So I'm not to familiar with the stringifier API from annotationlib, but I believe we usually assume subclasses respect the LSP for the constructor.

I don't think we do this in annotationlib. typing may make the assumption that a value is a valid type hint or obeys LSP, but annotationlib doesn't. To a reasonable extent if an expression is valid in an annotation we currently try to reproduce it correctly even if it's a nonsensical type hint.

As such I'm wary of trying to handle a general case we can't guarantee we can reconstruct without losing information. There may be other specific cases we can and should handle though.

Additional name correction logic for deprecated typing aliases.

Logic to skip reconstruction if all values resolve.
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.

2 participants