Skip to content

inspect.getgeneratorstate() fails on _GeneratorWrapper with AttributeError: gi_suspended #143999

@hyongtao-code

Description

@hyongtao-code

Bug report

Bug description:

When a generator function decorated with @types.coroutine returns a generator, calling inspect.getgeneratorstate() on the resulting _GeneratorWrapper object raises an AttributeError. This happens because _GeneratorWrapper does not have the gi_suspended attribute expected by inspect.getgeneratorstate().

Python script repro

import inspect
import types

def legacy_stepper():
    yield 1
    yield 2

@types.coroutine
def await_legacy():
    return legacy_stepper()

task = await_legacy()

print("awaitable type:", type(task))

print("state:", inspect.getgeneratorstate(task))

Wrong behavior

d:\MyCode\cpython\PCbuild\amd64>python_d.exe py_suspended.py
awaitable type: <class 'types._GeneratorWrapper'>
Traceback (most recent call last):
  File "d:\MyCode\cpython\PCbuild\amd64\py_suspended.py", line 16, in <module>
    print("state:", inspect.getgeneratorstate(task))
                    ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
  File "d:\MyCode\cpython\Lib\inspect.py", line 1817, in getgeneratorstate
    if generator.gi_suspended:
       ^^^^^^^^^^^^^^^^^^^^^^
AttributeError: '_GeneratorWrapper' object has no attribute 'gi_suspended'

Potential solutions

Add gi_suspended properties to _GeneratorWrapper that delegate to the wrapped generator.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Windows

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