I have been playing with the inspect
module from Python's standard library.
The following examples work just fine (assuming that inspect
has been imported):
def foo(x, y):
return x - y
print(inspect.getsource(foo))
... will print def foo(x, y):\n return x - y\n
and ...
bar = lambda x, y: x / y
print(inspect.getsource(bar))
... will print bar = lambda x, y: x / y\n
. So far so good. Things become a little odd in the following examples, however:
print(inspect.getsource(lambda x, y: x / y))
... will print print(inspect.getsource(lambda x, y: x / y))
and ...
baz = [2, 3, lambda x, y: x / y, 5]
print(inspect.getsource(baz[2]))
... will print baz = [2, 3, lambda x, y: x / y, 5]
.
The pattern seem to be that all relevant source code lines regardless of context are returned by getsource
. Everything else on those lines, in my case stuff other than the desired function source / definition, is also included. Is there another, "alternative" approach, which would allow to extract something that represents a function's source code - and only its source code - preferably in some anonymous fashion?
EDIT (1)
def foo(x, y):
return x - y
bar = [1, 2, foo, 4]
print(inspect.getsource(bar[2]))
... will print def foo(x, y):\n return x - y\n
.