Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eval giving syntax error even when correct code given

Tags:

python

eval

I have the following code, which uses the eval function:

lines = self.fulltext.splitlines()

CURRENT = 0

extractors = { "solar zenith angle" : (CURRENT, 1, "self.solar_z"),
                       "ground pressure" : (CURRENT, 2, "self.ground_pressure")                     

             }

print locals()

for line in lines:
    for label, details in extractors.iteritems():
        if label in line:
            if details[0] == CURRENT:
                values = line.split()
                eval("%s = values[%d]" % (details[2], details[1]))

However, when I run it I get the following error:

eval("%s = values[%d]" % (details[2], details[1]))
  File "<string>", line 1
    self.solar_z = values[1]
                 ^
SyntaxError: invalid syntax

Why is this? self.solar_z is defined, and the statement that is eval'd looks correct.

like image 601
robintw Avatar asked Jun 20 '11 17:06

robintw


2 Answers

Use exec instead, it does evaluate statements, to.

exec "self.solar_z = values[1]" in locals(), locals()

like image 79
Niklas R Avatar answered Sep 28 '22 02:09

Niklas R


eval() evaluates expressions. Assignment in Python is a statement. This will not work.

like image 40
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 02:09

Ignacio Vazquez-Abrams