Thanks Chris<br><br><div class="gmail_quote">On Tue, Apr 13, 2010 at 1:08 PM, Chris Rebert <span dir="ltr"><<a href="mailto:clp2@rebertia.com">clp2@rebertia.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<div class="im">> On Tue, Apr 13, 2010 at 12:29 PM, Chris Rebert <<a href="mailto:clp2@rebertia.com">clp2@rebertia.com</a>> wrote:<br>
>> On Tue, Apr 13, 2010 at 8:56 AM, Vishal Rana <<a href="mailto:ranavishal@gmail.com">ranavishal@gmail.com</a>> wrote:<br>
>> > Hi,<br>
>> ><br>
>> > I need to construct an if statement from the data coming from the client<br>
>> > as<br>
>> > below:<br>
>> ><br>
>> > conditions: condition1, condition2, condition3, condition4 logical<br>
>> > operators: lo1, lo2, lo3 (Possible values: "and" "or")<br>
>> ><br>
>> > Eg.<br>
>> ><br>
>> > if condition1 lo1 condition2 lo3 condition4:<br>
>> ><br>
>> > # Do something<br>
>> ><br>
>> > I can think of eval/exec but not sure how safe they are! Any better<br>
>> > approach<br>
>> > or alternative? Appreciate your responses :)<br>
>> ><br>
>> > PS: Client-side: Flex, Server-side: Python, over internet<br>
>><br>
>> Do you literally get a string, or do/could you get the expression in a<br>
>> more structured format?<br>
<br>
</div><div class="im">On Tue, Apr 13, 2010 at 12:46 PM, Vishal Rana <<a href="mailto:ranavishal@gmail.com">ranavishal@gmail.com</a>> wrote:<br>
> Its a form at the client side where you can construct a query<br>
> using different conditions and logical operators.<br>
> I can take it in any format!, currently it comes as a parameters to an RPC.<br>
<br>
</div>Well, then if possible, I'd have the form send it back in a Lisp-like<br>
format and run it through a simple evaluator:<br>
<br>
def and_(conds, context):<br>
for cond in conds:<br>
if not evaluate(cond, context):<br>
return False<br>
return True<br>
<br>
def or_(conds, context):<br>
for cond in conds:<br>
if evaluate(cond, context):<br>
return True<br>
return False<br>
<br>
def greater_than(pair, context):<br>
left, right = [context[name] for name in pair]<br>
return left > right<br>
<br>
OPNAME2FUNC = {"and" : and_, "or" : or_, ">" : greater_than}<br>
<br>
def evaluate(expr, context):<br>
op_name, operands = expr[0], expr[1:]<br>
return OPNAME2FUNC[op_name](operands, context)<br>
<br>
expression = ["and", [">", "x", "y"], ["or", [">", "y", "z"], [">", "x", "z"]]]<br>
variables = {"x" : 7, "y" : 3, "z" : 5}<br>
print evaluate(expression, variables)<br>
<br>
If it's just ands and ors of bare variables (no '>' or analogous<br>
operations), the code can be simplified a bit.<br>
<div><div></div><div class="h5"><br>
Cheers,<br>
Chris<br>
--<br>
<a href="http://blog.rebertia.com" target="_blank">http://blog.rebertia.com</a><br>
</div></div></blockquote></div><br>