18

I'd like to read a lambda function I created as a string, after I created it.

For example,

func = lambda num1,num2: num1 + num2

I'd like to read func as:

'lambda num1,num2: num1 + num2'

Is there a way to accomplish this or even read any part of the lambda function?

Chris
  • 5,444
  • 16
  • 63
  • 119

4 Answers4

13

Edit: Changed my first answer as I misunderstood the question. This answer is borrowed from a number of other uses, however I have completed the code to only display the part of the string that you want.

import inspect

func = lambda num1,num2: num1 + num2
funcString = str(inspect.getsourcelines(func)[0])
funcString = funcString.strip("['\\n']").split(" = ")[1]
print funcString

Outputs the following string:

lambda num1,num2: num1 + num2
maccartm
  • 2,035
  • 14
  • 23
  • If I copy and paste the code above I get an error at line 3: Traceback (most recent call last): File "", line 1, in File "/usr/lib/python3.9/inspect.py", line 1006, in getsourcelines lines, lnum = findsource(object) File "/usr/lib/python3.9/inspect.py", line 835, in findsource raise OSError('could not get source code') OSError: could not get source code – Siderius Dec 03 '21 at 16:26
  • 1
    Sorry for the delayed reply. @Siderius try running the code from a file instead of an interpreter. – maccartm Dec 15 '21 at 14:47
6

You can use getsourcelines from the inspect module to do this

This function returns as a list all of the lines of the definition of any function, module, class or method as well as the line number at which it was defined.

For example:

import inspect

f = lambda x, y : x + y

print inspect.getsourcelines(f)[0][0]

Will output the definition of the function as:

f = lambda x, y: x + y
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Simon Gibbons
  • 6,969
  • 1
  • 21
  • 34
2

You can use Python's eval() function:

>>> func = eval('lambda num1,num2: num1 + num2')
>>> func
<function <lambda> at 0x7fe87b74b668>

To evaluate any expression and return the value.

Kaiting Chen
  • 1,076
  • 1
  • 7
  • 12
2

You can use Python's inspect module to get the desired code as a list of strings:

#!/usr/bin/env python3
# coding: utf-8

import inspect

func = lambda num1, num2: num1 + num2

def f():
    a = 1
    b = 2
    return a + b

def get_code_as_string(passed_func):
    return inspect.getsourcelines(passed_func)


if __name__ == '__main__':
    # feed a lambda function
    print(get_code_as_string(func))

    #feed a normal function
    print(get_code_as_string(f))

The output is as follows:

(['func = lambda num1, num2: num1 + num2\n'], 6)
(['def f():\n', '    a = 1\n', '    b = 2\n', '    return a + b\n'], 8)

As you can see inspect.getsourcelines() returns a tuple of a list and an integer. The list contains all the lines of the function passed to inspect.getsourcelines() and the integer represents the line number in which the provided functions starts.

albert
  • 8,027
  • 10
  • 48
  • 84