Skip to content

inspect.getsource returns unrelated code #143299

@99991

Description

@99991

The documentation of inspect.getsource states:

Return the text of the source code for an object. [...]

But the function returns slightly more code. It returns all lines of source code that overlap the object, even if the rest of the lines belong to different objects.

For example, the following code creates two lambdas in the same line, so inspect.getsource will return the code of both lambdas instead of just one.

import inspect

# Two function declarations in the same line
x = lambda: 1; y = lambda: 2

# prints "x = lambda: 1; y = lambda: 2\n"
print(repr(inspect.getsource(y)))

The returned code is not even necessarily valid Python, as the following list comprehension demonstrates:

import inspect

funcs = [
    lambda: 1 for
    _ in range(3)
]

# prints '    lambda: 1 for\n', including indentation and a stray "for"
print(repr(inspect.getsource(funcs[0])))

Background

I was trying to access the abstract syntax tree of a function (for JIT compilation), but that does not appear to be possible for lambdas.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dir

    Projects

    Status

    No status

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions