Inspecting the body of a lambda function

Viewed 126

I am building a compiler. I'd like to inspect a lambda function that is passed in for compilation so that I can generate optimized code, like so:

f(fn):
  print(fn.body)   # how can I write this?
  if fn.body == 2*x:  # is this possible?
    return lambda x: x << 1 

f(lambda x : 2 * x)

I am aware of the inspect module but I didn't find a way to look into a lambda function. For instance I tried doing this:

def foo(p):
  print("code: %a" % getsource(p))

foo(lambda x: x + 1)

But it would print foo(lambda x: x + 1)\n rather than just lambda x: x + 1

1 Answers

Try uncompyle6 package.

import uncompyle6
f = lambda x: x*2
uncompyle6.deparse_code2str(f.__code__)

it returns str code:

return x * 2
Related