5

I have a boolean expression in a string. eg. 20 < 30. Is there a simple way to parse and evaluate this string so it will return True (in this case).

ast.literal_eval("20 < 30") does not work.

0

3 Answers 3

2

Is this a user-defined string, or one you're defining?

If it's a string you're creating, you could use eval (eval("20 < 30")), but if the string is given by the user, you might want to sanitize it first...

Sign up to request clarification or add additional context in comments.

1 Comment

I create it. No worries :) Eval is indeed a very nice and very BIG security hole.
1
>>> eval("20<30")
True

Comments

0

ast.literal_eval shouldn't work since (from the docs) "The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.". The expression 20<30 requires some kind of evaluation, before it returns a bool.

A safer suggestion would be to split the string on the operator and literal_eval each side before passing to eval, ie.

import ast

expr = "20 < 30"
operator = "<"
lhs,rhs = map(ast.literal_eval, map(str.strip, expr.split(operator)))
eval("%s %s %s"%(lhs,operator,rhs))

Wrapping the thing in a try, except clause will catch some input errors when evaluating lhs,rhs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.