How do I convert a function to str?

Let's say I have the 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 expected str(fn)

or str(fn.__code__)

would do this, but not really ... it just prints out the type, memory location, etc.

Also I tried pickle.dumps and json but I can't get what I want.

How do I convert the function to a string that shows the definition of the function?

--- I want to take a function as input and convert it to a string

+3


source to share


1 answer


Easy if you've installed dill. ( pip install dill

)



from dill.source import getsource
squared = lambda x:x**2
print(getsource(squared))

      

+7


source







All Articles