Let's say I have a following lambda function.
fn = lambda x: print(x)
If I wanted to convert it to string
"lambda x: print(x)"
What can I do?
I was expecting str(fn)
or str(fn.__code__)
would do it but not really...it just prints out type, mem location, etc.
Also I've tried pickle.dumps and json as well, but i cannot get what I want.
How could I convert function to string that shows function definition?
--- I want to take function as an input and convert that into a string
The str() function converts the specified value into a string.
Code to Convert a Function to String To convert a function to string, use the toString() method of a function object.
The str() function converts values to a string form so they can be combined with other strings.
Try it with inspect
, which is part of Python3 standard lib:
import inspect
func = lambda e: e**2
print(inspect.getsource(func))
Returns a string:
func = lambda e: e**2
It's easy if you have installed dill. (pip install dill
)
from dill.source import getsource
squared = lambda x:x**2
print(getsource(squared))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With