Parsing code used in loop only once
Question: I'm writing a code in Python which can be used to solve equations. The user
must first input a code via a raw_input(), which will then be used to
calculate y for every x in a loop with eval(), like so:

    
    
    #some imports (math) and other irrelevant code
    Code = raw_input('please enter your equation')
    Low = raw_input('please enter the lowest number in the domain')
    High = raw_input('please enter the highest number in the domain')
    X = Low
    While X <= High:
        Y = eval(code)
        #complicated code to solve equation
        X += #number depending on the amount of decimals
    #simpler code to print the result
    

The problem is that parsing the input code using eval() for every loop is
extremely slow. Is there a way to parse the code only once and then use it as
a function in the rest of the program?


Answer: You can compile the expression in advance using
[`compiler.compile()`](https://docs.python.org/2/library/compiler.html#compiler.compile)
([deprecated](https://mail.python.org/pipermail/python-3000/2008-January/011693.html)
since Python v2.6).

With Python 3.x:

  * the [`compile`](https://docs.python.org/3/library/functions.html#compile) functionality is built-in
  * the [AST module](https://docs.python.org/3.3/library/ast.html) offers similar functions

Also take a look at: [Python: Way to speed up a repeatedly executed eval
statement?](http://stackoverflow.com/q/12467570/3235496)

EDIT

Some examples:

    
    
    >>> expr = 'x*x + 2*x + 1'
    >>> expr_obj = compile(expr, '', 'eval')
    >>> x = 1
    >>> y = eval(expr)
    

and now

    
    
    >>> y
    4
    >>> x = 2
    >>> y = eval(expr)
    >>> y
    9
    

`compile` is a lower level version of `eval` (and `exec`). It doesn't
evaluate/execute your expression/statement but returns a code object that can
do it.

* * *

PS as a general rule when using `eval` on user submitted strings you must be
very careful about what you accept (it's a potential security hole).

