Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: Question about ast.literal_eval

Reply
Thread Tools

Re: Question about ast.literal_eval

 
 
Chris Angelico
Guest
Posts: n/a
 
      05-20-2013
On Mon, May 20, 2013 at 5:05 PM, Frank Millman <(E-Mail Removed)> wrote:
> Hi all
>
> 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: <_ast.Compare object at ...>
>
> Is there a safe way to do what I want? I am using python 3.3.


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
'=='perator.eq, # or use '=' for more SQL-like syntax
'<'perator.lt,
'>'perator.gt,
}

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

if ops[op](x,ast.literal_eval(value)):
print("Constraint passed")
else:
print("Ignore this one")

ChrisA
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
I need your advices about C prg. Dogukan Bayraktar C Programming 76 06-16-2013 08:54 AM
question about try/except blocks J Python 1 05-03-2013 03:02 AM
Re: question about try/except blocks Devin Jeanpierre Python 0 05-03-2013 02:23 AM
silly question about Running a script from the command line A.Rock Python 0 04-10-2013 11:21 AM
newbie question about confusing exception handling in urllib cabbar@gmail.com Python 6 04-09-2013 07:11 PM



Advertisments