Question about ast.literal_eval

Carlos Nepomuceno carlosnepomuceno at outlook.com
Mon May 20 03:34:47 EDT 2013


It seems to me you can't use ast.literal_eval()[1] to evaluate that kind of expression because it's just for literals[2].

Why don't you use eval()?


[1] http://docs.python.org/2/library/ast.html#ast-helpers

[2] http://docs.python.org/2/reference/lexical_analysis.html#literals

----------------------------------------
> To: python-list at python.org
> From: frank at chagford.com
> Subject: Question about ast.literal_eval
> Date: Mon, 20 May 2013 09:05:48 +0200
>
> 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.
>
> Thanks
>
> Frank Millman
>
> --
> http://mail.python.org/mailman/listinfo/python-list 		 	   		  


More information about the Python-list mailing list