The eval function lets a Python program run Python code within itself.
eval example (interactive shell):
>>> x = 1
>>> eval('x + 1')
2
>>> eval('x')
1
Answer from BYS2 on Stack OverflowThe eval function lets a Python program run Python code within itself.
eval example (interactive shell):
>>> x = 1
>>> eval('x + 1')
2
>>> eval('x')
1
eval() interprets a string as code. The reason why so many people have warned you about using this is because a user can use this as an option to run code on the computer. If you have eval(input()) and os imported, a person could type into input() os.system('rm -R *') which would delete all your files in your home directory. (Assuming you have a unix system). Using eval() is a security hole. If you need to convert strings to other formats, try to use things that do that, like int().
Valid uses of eval()?
How to use the eval() function
Demo of how input() is security probem in Python 2.7 (4min)
eval python - beginner
Videos
I’m wondering if anyone has ever seen a case of code using eval() and thought to themselves “yeah actually that’s probably the right way to do it”?
My understanding has always been that it’s a huge security risk and generally a recipe for disaster.
But I was just working on a task where I couldn’t really figure out any other way to achieve the dynamic functionality I was looking for, so I wrote code that assembles a string to do what I need, and then runs eval() on that string. Pretty sure this is the first time I’ve ever used eval() at all.
It’s a low-stakes proof of concept for a totally internal tool, so I’m not hugely worried about security at the moment, but it just feels so icky to do something like that. I’m curious if in others’ experience there’s always a better way than using eval(), or if sometimes it’s legit.