Skip to content

annotationlib: ref.evaluate() not working for generics as local variables #138151

Description

@dr-carlos

Bug report

Bug description:

Usually, when a local variable is introduced after getting a ForwardRef, evaluate() picks this up and correctly evaluates it using the self.__cell__ short-circuit. However, this does not work when that local variable is a generic. It does still work for globals.

fromannotationlibimportFormat, get_annotationsdefworks_global():
classDemo:
x: sequence_a[int]
fwdref=get_annotations(Demo, format=Format.FORWARDREF)['x']
print(f"Global {fwdref!r}")
globalsequence_asequence_a=listevaluated=fwdref.evaluate()
print(f"Evaluated {evaluated!r}")
defworks_nongeneric():
classDemo:
nonlocalalias# Optionalx: aliasfwdref=get_annotations(Demo, format=Format.FORWARDREF)['x']
print(f"Global {fwdref!r}")
alias=intevaluated=fwdref.evaluate()
print(f"Evaluated {evaluated!r}")
deffails():
classDemo:
nonlocalsequence_bx: sequence_b[int]
fwdref=get_annotations(Demo, format=Format.FORWARDREF)['x']
print(f"Local {fwdref!r}")
sequence_b=listevaluated=fwdref.evaluate() # NameErrorprint(f"Evaluated {evaluated!r}")
works_global()
works_nongeneric()
fails()

CPython versions tested on:

CPython main branch, 3.14

Operating systems tested on:

Linux

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions