classification
Title: inspect.getsourceslines() consider lambda of one line only
Type: behavior Stage:
Components: Extension Modules, Library (Lib), Windows Versions: Python 3.10, Python 3.9
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: Welgriv, paul.moore, steve.dower, tim.golden, zach.ware
Priority: normal Keywords:

Created on 2021-06-21 13:33 by Welgriv, last changed 2021-06-21 13:33 by Welgriv.

Messages (1)
msg396245 - (view) Author: Wel Griv (Welgriv) Date: 2021-06-21 13:33
When lambda expression is more than one line or contain a line break, getsourcelines() from inspect package only return the first line. Code example:

import inspect


def foo(param, lambda_ref):
    _ = param
    print(str(inspect.getsourcelines(lambda_ref)))


foo(param=0,
    lambda_ref=lambda:
    40 + 2)

output:

(['    lambda_ref=lambda:\n'], 10)

expected output:

(['foo(lambda_ref=lambda:\n', '    40 + 2)\n'], 10)

`param` is not necessary to make the bug appears but makes more sense in a real use-case scenario.
Beside, I checked the inspect.py code (see github: https://github.com/python/cpython/blob/3.9/Lib/inspect.py couldn't include link in the form for some reason), the guilty code is in the tokeneater() method in the BlockFinder class. A commentary explicitly mention "# lambdas always end at the first NEWLINE" (line 957 of inspect.py in python 3.9, line 1078 in python 3.10). EndOfBlock is raised after the first newline in case the block is a lambda.
Moreover, a similar issue was raised, and closed for strange reason in python 2 back in 2013, see here: https://bugs.python.org/issue17631
History
Date User Action Args
2021-06-21 13:33:42Welgrivcreate