[Tutor] Use python to parse the subject line of emails, listen for and react to commands

Danny Yoo dyoo at hashcollision.org
Sat Feb 28 02:26:54 CET 2015


> That's nearly always a bad idea. eval is a big security risk, especially if
> applied to external input. And as you've discovered,
> it makes debugging into a bit of a nightmare.

Yes, I concur with Alan.  eval() is definitely the wrong tool here.
It's **extraordinarily** dangerous in the context of consuming
arbitrary email input.

Did anyone teach you to use eval()?


An alternative approach to what you're considering is to define a
mapping from command name to functionality.  A quick-and-dirty
approach uses a dictionary, and may have enough power for what you're
trying to do.   Here's an example to demonstrate: let's say that we'd
like a calculator that takes a sequence of operations, like:

     zero
     inc
     inc
     double

and performs them in turn to zero out memory, increment, increment,
and double.  (getting us four).

Here's a brief sketch of what this might look like:

########################################
def zero(n):
    return 0

def double(n):
    return n * 2

def inc(n):
    return n + 1

cmd_mapping = {
    'zero': zero,
    'double': double,
    'inc': inc
}

## Run the calculator:
memory = 0
for cmd_string in 'inc inc inc double double inc'.split():
    cmd = cmd_mapping[cmd_string]
    memory = cmd(memory)
print memory
########################################


Here, we let a string dictate what's being computed, but in a
controlled fashion.  The "magic" here is the line:

    cmd = cmd_mapping[cmd_string]

which gets a function, which we can just call later on.  Since
cmd_mapping is a dictionary whose contents we control, we know that
the only command being looked up has to be in the cmd_mapping.

Compare vs. an eval-based approach.  Unlike an approach that uses
eval(), if the command string contains bad values here, nothing too
bad will happen: at worst, we'll see a reliable dictionary lookup
error.  You'll even get a good line number in the stack trace!  If we
were to use eval, we would not.  In the worst case, we might
accidentally let an adversary dictate what our computer is going to
do, against our wishes.


For more discussion why eval() is almost certainly not the tool you
want to use, see:

    http://code.activestate.com/lists/python-tutor/33338/


More information about the Tutor mailing list