Question about ast.literal_eval
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue May 21 03:21:58 EDT 2013
On Tue, 21 May 2013 08:30:03 +0200, Frank Millman wrote:
> On 20/05/2013 18:12, Steven D'Aprano wrote:
>> Personally, I would strongly suggest writing your own mini- evaluator
>> that walks the list and evaluates it by hand. It isn't as convenient as
>> just calling eval, but *definitely* safer.
>>
>>
> I am not sure I can wrap my mind around mixed 'and's, 'or's, and
> brackets.
Parsers are a solved problem in computer science, he says as if he had a
clue what he was talking about *wink*
Here's a sketch of a solution... suppose you have a sequence of records,
looking like this:
(bool_op, column_name, comparison_op, literal)
with appropriate validation on each field. The very first record has
bool_op set to "or". Then, you do something like this:
import operator
OPERATORS = {
'=': operator.eq,
'is': operator.is_,
'<': operator.lt,
# etc.
}
def eval_op(column_name, op, literal):
value = lookup(column_name) # whatever...
return OPERATORS[op](value, literal)
result = False
for (bool_op, column_name, comparison_op, literal) in sequence:
flag = eval_op(column_name, comparison_op, literal)
if bool_op == 'and':
result = result and flag
else:
assert bool_op == 'or'
result = result or flag
# Lazy processing?
if result:
break
and in theory it should all Just Work.
--
Steven
More information about the Python-list
mailing list