Skip to content

inspect.getsource does not work for a class-defined code object #116987

Closed
@blhsing

Description

@blhsing

Bug report

Bug description:

In the following MRE, code.co_firstlineno correctly returns 4, the first line number of the class definition, but getsource(code) returns the content of the entire file:

import sys
from inspect import getsource

class A:
    code = sys._getframe(0).f_code
    print(code.co_firstlineno)
    print(getsource(code))

This is because inspect.findsource uses a regex pattern that does not match class:

pat = re.compile(r'^(\s*def\s)|(\s*async\s+def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')

CPython versions tested on:

3.12

Operating systems tested on:

Linux, Windows

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions