Skip to content

inspect.getsourcelines() mishandles multi-line generator expressions #137477

Closed

Description

@George-Ogden

Bug report

Bug description:

import inspect

def source_error(*args):
    frame = inspect.currentframe()
    if frame is None:
        return
    frame = frame.f_back
    if frame is None:
        return
    print(inspect.getsource(frame))

def demo():
    loops = (
        None for _ in [0] if source_error(True)
    )
    list(loops)

demo()

Expected output:

def demo():
    loops = (
        None for _ in [0] if source_error(True)
    )
    list(loops)

Actual output:

    loops = (

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs

Activity

  1. George-Ogden commented on Aug 6, 2025

    @George-Ogden
    ContributorAuthor

    Possibly related to #122981
    Introduced in #117025

  2. changed the title [-]`inspect.getsourcelines` bug introduced in #117025[/-] [+]`inspect.getsourcelines()` Bug[/+] on Aug 6, 2025
  3. added
    stdlibStandard Library Python modules in the Lib/ directory
    3.13only security fixes
    3.14bugs and security fixes
    3.15bugs and security fixes
    on Aug 6, 2025
  4. AA-Turner commented on Aug 6, 2025

    @AA-Turner
    Member
  5. added a commit that references this issue on Aug 6, 2025
  6. serhiy-storchaka commented on Aug 6, 2025

    @serhiy-storchaka
    Member

    I do not think that restoring that regexp is a correct solution. This method has proven unreliable. And even if it works, it will show the source of the first function or class above the generator expression. It may even not include the source of the generator expression.

    I think that the right method is to fix getblock(), so it will process generator expressions similarly to lambda expressions.

  7. George-Ogden commented on Aug 7, 2025

    @George-Ogden
    ContributorAuthor

    @serhiy-storchaka I think #137488 is a better solution than #137479

  8. changed the title [-]`inspect.getsourcelines()` Bug[/-] [+]`inspect.getsourcelines()` mishandles multi-line generator expressions[/+] on Aug 8, 2025
  9. added a commit that references this issue on Aug 20, 2025
  10. added a commit that references this issue on Aug 20, 2025
  11. added 2 commits that reference this issue on Aug 20, 2025
  12. added a commit that references this issue on Oct 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

3.13only security fixes3.14bugs and security fixes3.15bugs and security fixesstdlibStandard 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