Evaluating Arbitrary Strings As Python Expressions
We'll cover the following...
This is the final piece of the puzzle (or rather, the final piece of the puzzle solver). After all that fancy string manipulation, we’re left with a string like '9567 + 1085 == 10652'. But that’s a string, and what good is a string? Enter eval(), the universal Python evaluation tool.
But wait, there’s more! The eval() function isn’t limited to boolean expressions. It can handle any Python expression and returns any datatype.
But wait, that’s not all!
① The expression that eval() takes can reference global variables defined outside the eval(). If called within a function, it can reference local variables too.
② And functions.
③ And modules.
Hey, wait a minute…
① The subprocess module allows you to run arbitrary shell commands and get the result as a Python string.
② Arbitrary shell commands can have permanent consequences.
It’s even worse than that, because there’s a global __import__() function that takes a module name ...