Yet another attempt at a safe eval() call

Grant Edwards invalid at invalid.invalid
Thu Jan 3 18:25:51 EST 2013


I've written a small assembler in Python 2.[67], and it needs to
evaluate integer-valued arithmetic expressions in the context of a
symbol table that defines integer values for a set of names.  The
"right" thing is probably an expression parser/evaluator using ast,
but it looked like that would take more code that the rest of the
assembler combined, and I've got other higher-priority tasks to get
back to.

How badly am I deluding myself with the code below?

def lessDangerousEval(expr):
    global symbolTable
    if 'import' in expr:
        raise ParseError("operand expressions are not allowed to contain the string 'import'")
    globals = {'__builtins__': None}
    locals  = symbolTable
    return eval(expr, globals, locals)

I can guarantee that symbolTable is a dict that maps a set of string
symbol names to integer values.

-- 
Grant Edwards               grant.b.edwards        Yow! -- I have seen the
                                  at               FUN --
                              gmail.com            



More information about the Python-list mailing list