Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert function to str for Python?

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

like image 661
Kevin JJ Avatar asked May 26 '17 17:05

Kevin JJ


People also ask

Can you convert a function into a string in Python?

The str() function converts the specified value into a string.

How do I convert a function to a string?

Code to Convert a Function to String To convert a function to string, use the toString() method of a function object.

What does the STR () function do in Python?

The str() function converts values to a string form so they can be combined with other strings.


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

like image 162
DSH Avatar answered Sep 28 '22 08:09

DSH


It's easy if you have installed dill. (pip install dill)

from dill.source import getsource
squared = lambda x:x**2
print(getsource(squared))
like image 30
knurzl Avatar answered Sep 28 '22 09:09

knurzl