Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are valid statements inside a python eval()?

Tags:

python

eval

I have tried

eval('print("hello world")')
eval('return 0')

which are both incorrect. Why are they invalid and what rules should I follow when using eval() (other than as little as possible)?

like image 532
user1561108 Avatar asked Feb 18 '23 04:02

user1561108


1 Answers

In Python, eval() evaluates expressions (something that results in a value). Both print and return are defined as statements (however in Python 3, print is actually a function call, which is an expression). In the case of executing statements, you need to use the exec statement instead.

like image 60
Greg Hewgill Avatar answered Feb 21 '23 02:02

Greg Hewgill