If I define a function
def foo(function):
import inspect
return inspect.getsource(function)
and then call it, I get:
In [11]: foo(lambda x: x[0] + x[1]*2)
Out[11]: 'foo(lambda x: x[0] + x[1]*2)\n'
Note how it printed the entire line, rather than just the lambda function.
Is there a way to get it to output just the lambda?
Desired output:
In [11]: foo(lambda x: x[0] + x[1]*2)
lambda x: x[0] + x[1]*2'
Is there a way to do this that doesn't involve using a regular expression?
EDIT:
Example of how ast.parse(inspect.getsource(function)) may fail:
ast.parse(foo(
lambda x: x+1))
inspect.getsourcewill return a string that not only includes the source code of the object that is being inspected, but also the full call trace of the function that the object is being passed to. For example:Will result in the string
'val = foo(lambda x: x[0] + x[1]*2)\n'stored underval.To more accurately pull the source of
functionin the string returned frominspect.getsource(function), you can use theastmodule, returning for the function source code by anchoring a search on thefooobject name:Output: