views:

1292

answers:

7

How can I (easily) take a string such as

'sin(x)*x^2'

which might be entered by a user at runtime and produce a python function that could be evaluated for any value of x? Does anyone know of any libraries or modules that takes care of this sort of thing?

A: 

Sage is intended as matlab replacement and in intro videos it's demonstrated how similar to yours cases are handled. They seem to be supporting a wide range of approaches. Since the code is open-source you could browse and see for yourself how the authors handle such cases.

SilentGhost
+2  A: 
 f = parser.parse('sin(x)*x^2').to_pyfunc()

Where parser could be defined using PLY, pyparsing, builtin tokenizer, parser, ast.

Don't use eval on user input.

J.F. Sebastian
+6  A: 

You might consider this interesting:

"SymPy is a Python library for symbolic mathematics" http://code.google.com/p/sympy/

vartec
+6  A: 

Python's own internal compiler can parse this, if you use Python notation.

If your change the notation slightly, you'll be happier.

import compiler
eq= "sin(x)*x**2"
ast= compiler.parse( eq )

You get an abstract syntax tree that you can work with.

S.Lott
+2  A: 

To emphasize J.F. Sebastian's advice, 'eval' and even the 'compiler' solutions can be open to subtle security holes. How trustworthy is the input? With 'compiler' you can at least filter out things like getattr lookups from the AST, but I've found it's easier to use PLY or pyparsing for this sort of thing than it is to secure the result of letting Python help out.

Also, 'compiler' is clumsy and hard to use. It's deprecated and removed in 3.0. You should use the 'ast' module (added in 2.6, available in 2.5 as '_ast').

Andrew Dalke
+1  A: 

In agreement with vartec. I would use SymPy - in particular the lambdify function should do exactly what you want.

See: http://showmedo.com/videotutorials/video?name=7200080&fromSeriesID=720

for a very nice explanation of this.

Best wishes,

Geddes
+2  A: 

pyparsing might do what you want (http://pyparsing.wikispaces.com/) especially if the strings are from an untrusted source.

See also http://pyparsing.wikispaces.com/file/view/fourFn.py for a fairly full-featured calculator built with it.

David Morrissey