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()?
Why does Python's eval(input("Enter input: ")) change input's datatype? - Stack Overflow
Demo of how input() is security probem in Python 2.7 (4min)
What does list(map(int,input().split())) do in python?
Does eval() work with Python 2 vs Python 3 differently?
What is the performance impact of eval() vs native Python code?
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.
Why does this happen?
x = eval(input("Enter a number: ")) is not the same thing as x = eval('input("Enter a number: ")')
The former first calls input(...), gets a string, e.g. '5' then evaluates it, that's why you get an int, in this manner:
>>> eval('5') # the str '5' is e.g. the value it gets after calling input(...)
5 # You get an int
While the latter (more aligned with what you were expecting), evaluates the expression 'input("Enter a number: ")'
>>> x = eval('input("Enter a number: ")')
Enter a number: 5
>>> x
'5' # Here you get a str
Because a number is a valid expression in Python, and it evaluates to itself (and its type is int). For example, if you input a rubbish string with a non-existing name (say, 'abcdefgh'), a NameError exception will be raised (the exception is raised while evaluating).