简体   繁体   English

Python不会eval()代码

[英]Python won't eval() code

I have the following eval() thing: 我有以下eval()东西:

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 . 在我发现setattr()之前,我分别在c上设置了几个不同的属性。

eval evaluates expressions . eval计算表达式 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. 而且甚至不让我开始了解如何容易被误用,并且在所有情况下(99.99%)完全不需要eval 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 . 只需参考众多其他eval问题,我敢打赌,每个人在回答或评论中至少要有一个这样的咆哮-因此,我将屏住呼吸并链接到一个喜欢的问题 (That being said, exec works like eval for statements.) (也就是说, exec作用类似于eval的语句。)

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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