Given a string such as
"2*(i+j) <= 100"
I want to generate the corresponding lambda function,
fn = lambda i,j: 2*(i+j) <= 100
I can do this with
eval
, but I am seeking a less evil method.I have found
import ast f = ast.Lambda('i,j', '2*(i+j) <= 100')
but I haven't figure out how to execute the result!
Ideally, I would like to automatically pull out the parameter list ('i','j') as well - right now, I am just using re.findall('\w+'), but I would love to be able to properly use existing functions like
cos
instead of shadowing them as 'keywords'.
I was looking at Is there a Python library for handling complicated mathematical sets (constructed using mathematical set-builder notation)? and trying to figure out how best to parse the set-builder notation into the lambdas to feed to the constraint-solver.
I'm basically wishing for ast.literal_eval which would also recognize variables.
Ideally, given i >= 20
I would like to get back ((lambda x: x >= 20), ['i'])
which I could then feed directly to constraint
.