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?

0

4 Answers 4

15

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
2
  • If I copy and paste the code above I get an error at line 3: Traceback (most recent call last): File "<stdin>", line 1, in <module> 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
    Commented Dec 3, 2021 at 16:26
  • 1
    Sorry for the delayed reply. @Siderius try running the code from a file instead of an interpreter.
    – maccartm
    Commented Dec 15, 2021 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
3

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.

0

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.

3
  • 3
    eval is evil and considered bad practice... advise against it.
    – TMOTTM
    Commented Jun 7, 2019 at 13:45
  • 2
    Also this is the opposite of the desired solution, OP is looking to get the string from the lambda, not create the lambda from the string. Commented Aug 23, 2023 at 20:09
  • @mirrorcoloured Yet the reverse ways could be used for testing that the functions are inverse of each other. Commented Jul 11, 2024 at 9:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.