The idea of eval is to evaluate an expression in the form of a string and return the value. So why would you do this?
A common question i see is something like "How do you convert a string of a list to a list?"
Sometimes it gets more complicated, like a string of a list of tuples to a python list of tuples, or maybe its a dictionary.
Sometimes, you can use the json module, but sometimes not. What you can do, if you have a string version of any python code, is use eval.
Keep in mind, just like the pickle module we talked about, eval has no security against malicious attacks. Don't use eval if you cannot trust the source. For example, some people have considered using eval to evaluate strings in the browser from users on their website, as a way to create a sort of "online editor." While you can do this, you have to be incredibly careful!
list_str = "[1,5,7,8,2]" list_str = eval(list_str) print(list_str) print(list_str[1])
First, we define a string, that carries the syntax of a list. Next, we use eval to evaluate it.
Finally, we can show that it has the properties of a Python list.
x = input("see this...") check_this_out = eval(input("code:"))
The next question is whether or not we can use logic in evaluate. Evaluate will only evaluate code, it will not compile. For example, this code wont work:
eval("if True: print('yep!')")
With that shown, all hope is not lost if you want to basically do eval plus logic, because there is always exec, which we're going to cover next!