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
The documentation of
inspect.getsourcestates: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.getsourcewill return the code of both lambdas instead of just one.The returned code is not even necessarily valid Python, as the following list comprehension demonstrates:
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