how to convert function to str for Python?

Viewed 7851

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

2 Answers

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

Related