Content-Length: 304760 | pFad | https://github.com/python/cpython/issues/138151

5E annotationlib: `ref.evaluate()` not working for generics as local variables · Issue #138151 · python/cpython · GitHub
Skip to content

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

@dr-carlos

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.

from annotationlib import Format, get_annotations

def works_global():
    class Demo:
        x: sequence_a[int]

    fwdref = get_annotations(Demo, format=Format.FORWARDREF)['x']
    print(f"Global {fwdref!r}")

    global sequence_a
    sequence_a = list
    evaluated = fwdref.evaluate()
    print(f"Evaluated {evaluated!r}")

def works_nongeneric():
    class Demo:
        nonlocal alias # Optional
        x: alias

    fwdref = get_annotations(Demo, format=Format.FORWARDREF)['x']
    print(f"Global {fwdref!r}")

    alias = int
    evaluated = fwdref.evaluate()
    print(f"Evaluated {evaluated!r}")


def fails():
    class Demo:
        nonlocal sequence_b
        x: sequence_b[int]

    fwdref = get_annotations(Demo, format=Format.FORWARDREF)['x']
    print(f"Local {fwdref!r}")

    sequence_b = list
    evaluated = fwdref.evaluate() # NameError
    print(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









      ApplySandwichStrip

      pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


      --- a PPN by Garber Painting Akron. With Image Size Reduction included!

      Fetched URL: https://github.com/python/cpython/issues/138151

      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy