Julio S.
Julio S.

Reputation: 970

Convert a string to a callable function in Python

I want to take written function (string) from a user input and convert it to a callable function in Python. How to achieve it despite any security concerns?

Example (string):

""" def test(): \n print('success') \n return 'success' """

I want to call / evaluate the said string by calling test() and make it print to the console.

Upvotes: 1

Views: 1394

Answers (2)

maya
maya

Reputation: 1080

Try this, using the compile method combined with eval or exec:

a = compile("""def test(): \n print('success') \n return 'success' """, "", "exec")
eval(a)

test()

Upvotes: 2

chepner
chepner

Reputation: 531075

When appropriate, this is a job for the exec function.

>>> exec("""def test(): \n print('success') \n return 'success' """, globals())
>>> test()
success
'success'

Upvotes: 2

Related Questions