Evaluating Arbitrary Strings As Python Expressions
Explore how to evaluate Python expressions from strings using eval() while understanding the associated risks. Learn to manage global and local namespaces, override built-ins, and why using eval on untrusted input can be dangerous. This lesson guides you through the complexities and precautions needed to use eval safely in practical coding scenarios.
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 ...