top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

use of ast.literal_eval in python

0 votes
1,293 views

I am trying to emulate a SQL check constraint in Python. Quoting from the PostgreSQL docs, "A check constraint is the most generic constraint type. It allows you to specify that the value in a certain column must satisfy a Boolean (truth-value) expression."

The problem is that I want to store the constraint as a string, and I was hoping to use ast.literal_eval to evaluate it, but it does not work.

x = 'abc'
x in ('abc', xyz')
True
b = "x in ('abc', 'xyz')"
eval(b)
True
from ast import literal_eval
literal_eval(b)
ValueError: malformed node or string: 

Is there a safe way to do what I want? I am using python 3.3.

posted May 20, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes

It seems to me you can't use ast.literal_eval() [ http://docs.python.org/2/library/ast.html#ast-helpers ] to evaluate that kind of expression because it's just for literals [ http://docs.python.org/2/reference/lexical_analysis.html#literals ].
Why don't you use eval()?

answer May 20, 2013 by anonymous
0 votes

An SQL constraint has a whole lot that Python can't do conveniently, and vice versa, so I think you do yourself a disservice by trying to tie yourself to that.

The problem here is that 'in' is an operator, so this is not a literal. One possible solution would be to separate out your operator (and have just a handful permitted), and then use ast.literal_eval for
just the second operand - something like this:

import ast
import operator
ops = {
 'in':lambda x,y: x in y, # operator.contains has the args backwards
 '==':operator.eq, # or use '=' for more SQL-like syntax
 '':operator.gt,
}

op, value = 'in', "('abc', 'xyz')"
x = 'abc'

if ops[op](x,ast.literal_eval(value)):
 print("Constraint passed")
else:
 print("Ignore this one")
answer May 20, 2013 by anonymous
Similar Questions
+2 votes

I'm trying out Tkinter with the (non object oriented) code fragment below: It works partially as I expected, but I thought that pressing "1" would cause the program to quit, however I get this message:

TypeError: quit() takes no arguments (1 given),

I tried changing quit to quit() but that makes things even worse. So my question: can anyone here help me
debug this?

#!/usr/bin/env python
import Tkinter as tk
def quit():
 sys.exit()
root = tk.Tk()
label = tk.Label(root, text="Hello, world")
label.pack()
label.bind("", quit)
root.mainloop()
...