I want to dynamically inspect the body of a lambda that specialises another lambda at runtime. This would need to happen recursively until there are no more "parent" lambdas.
What I mean by that is the following example:
add_x_z = lambda x, z: x + z
add_x_1 = lambda x: add_x_z(x, 1)
Here add_x_1
is what I refer to as a "specialisation" of add_x_z
(the "parent" lambda). The specialisation here is hardcoded (z = 1
) but you can imagine cases where the fixed value comes from the runtime.
In this case, I am looking for the following string as an output:
"add_x_1 = lambda x: x + 1"
There are a lot of questions on Stack Overflow about inspecting the body of functions/lambdas, the most widely-accepted solution accross all those Q&As is the following:
add_x_z = lambda x, z: x + z
add_x_1 = lambda x: add_x_z(x, 1)
print(inspect.getsource(add_x_1))
# add_x_1 = lambda x: add_x_z(x, 1)
This doesn't do the trick for me because inspect
under the hood only looks at the source files and doesn't care about the runtime. There are also various solutions floating around that suggest using packages such as uncompyle6
, this also doesn't solve my issue:
import uncompyle6
add_x_z = lambda x, z: x + z
add_x_1 = lambda x: add_x_z(x, 1)
uncompyle6.deparse_code2str(add_x_1.__code__)
# return add_x_z(x, 1)
Is there any way to achieve this through Python internals and that doesn't involve writing some kind of parser?
Bonus points for an answer that doesn't make use of exec
or eval