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
|