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