1

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.

8
  • use value or func = eval(some code string), you might need value = func(params) afterwards. Commented Feb 24, 2022 at 1:11
  • ast.literal_eval is safer. Commented Feb 24, 2022 at 1:14
  • @JohnnyMopp literal eval is for literal data only (like 53.136, or (1, 2, 3), or {"x": 3}). You cannot parse function definitions with it. Commented Feb 24, 2022 at 1:23
  • eval evaluates expressions; you need exec to execute a def statement. Commented Feb 24, 2022 at 1:24
  • @JohnnyMopp I tried using a node generated by ast.parse before the ast.literal_eval, but got a ValueError: malformed node or string. That was using indentation. With no indentation I got indentation error. Commented Feb 24, 2022 at 1:25

2 Answers 2

2

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

>>> exec("""def test(): \n print('success') \n return 'success' """, globals())
>>> test()
success
'success'
Sign up to request clarification or add additional context in comments.

2 Comments

Why should one use exec instead of compile? Thanks!
in short, exec is shorter. by compile you need another invoke statement.
2

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()

2 Comments

Why compile should be picked instead of exec? Thanks!
Both are possible, but I think this way is more concise and less error-prone

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.