Skip to content
loading...

Is there a way to pass an object to ast.literal_eval to give it variables?

twitter logo github logo ・1 min read  

I am working on a small parser, and I want to evaluate values, but I was wondering if I could give it an object with variables (through key and values)?
I already tried, and to my knowledge, no. If I run:

from ast import literal_eval as l
l("x",{"x": 13})

it throws:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: literal_eval() takes 1 positional argument but 2 were given

Is there any way to get around this? !important
Also, is there a way to use keywords like: "or" etc... like:

l("{} or {'x': 13}")

to prevent falsy values? !important

Thanks!
Cheers!

twitter logo DISCUSS (4)
markdown guide
 

Have you looked at the eval function? It evaluates any python expression, so it for sure does the second thing you asked for. I did not really understand your first example, so if eval doesn't work I would need some more explanation of what you are trying to do. Hope it helps :)

 

What I mean, is ast.literal_eval is meant to be a safe version of eval right? Well, take eval, and be able to pass it to it, similar to this:


Python AST Literal Eval

literal_eval("#safe expression e.g. 1*5#")



My Idea:

new_eval("x*y",{
    "x": 4,
    "y": 3
}) # Should return 12
 

So the problem with literal_eval is that it only supports literals. Literals are things like writing a number, string, lists or tuples using their respective syntax. However, you are correct in eval being very unsafe.

I found this project which might be useful or work as inspiration, as it is MIT licensed: github.com/danthedeckie/simpleeval

Classic DEV Post from Feb 24

How Do You Automate Your Boilerplate?

My team is reviewing how we start-up our projects, a large time sink for us is the initial set-up for...

PDS OWNER CALIN (Calin Baenen) profile image
I am a 13 (as of Oct 30 of 2019) yr/o developer (I have been developing mini-projects for 4, years now, since I was 9), who makes projects in languages like: Java, HTML, Python 3, JS, CSS, and C#.