简体   繁体   中英

Python won't eval() code

I have the following eval() thing:

c = Customer()
eval("c.name = row.value('customer', '{c}')".format(c=column_name), { 'c': c, 'row': row})

When I try to run that, I get this:

Traceback (most recent call last):
  File "./import.py", line 19, in <module>
    c = Customer.save_from_row(row)
  File "/home/jason/projects/mcifdjango/mcif/models/customer.py", line 43, in save_from_row
    eval("c.name = row.value('customer', '{c}')".format(c=column_name), { 'c': c, 'row': row})
  File "<string>", line 1
    c.name = row.value('customer', 'name')
           ^
SyntaxError: invalid syntax

What am I doing wrong?

Edit: Because it looks like I didn't explain the context of my problem well enough, here's what I ended up doing, if anyone's curious:

@classmethod
def save_from_row(cls, row):
    c = cls()
    map(lambda column_name: setattr(c, column_name, row.value('customer', column_name)), c.distinguishing_column_names())
    return c.upsert()

Before I found out about setattr() I was separately setting several different attributes on c .

eval evaluates expressions . Assignment is a statement, not an expression.

And don't even get me started on how easily misused and - in 99.99% of all cases - utterly unnecesary eval is. Just refer to the numerous other eval questions, I bet each has at least one such rant in an answer or comment - so I'll save my breath and link to one I like . (That being said, exec works like eval for statements.)

Wouldn't this do what you need?:

c = Customer()
name_cols = (('name', 'custname'), ('addr', 'cust_addr'))
for name, col in name_cols:
    setattr(c, name, row.value('customer', col))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM