简体   繁体   中英

Python `eval`: “invalid syntax” error, when trying to create class attributes programmatically?

I have a lot of class attributes that I want to create, so I decided to use a function to do so:

def make_index_variables(self):
    for index, label in enumerate(self.variable_labels):
        eval('self.' + label + '_index = ' + str(index))

If earlier, I defined:

self.variable_labels = ['x', 'y']

I get an error message like this:

eval('self.' + label + '_index = ' + str(index))

    self.x_index = 0
                     ^
    SyntaxError: invalid syntax

I am beginning to realize that using setattr is probably better than using eval (but I am not sure). In any case, why does eval raise this error?

You want to do exec instead of eval

exec('self.' + label + '_index = ' + str(index))

eval will evaluate a expression, not run it like you want.
Think of eval like the argument of a if statement.

Also, if you want to set attributes of a class, you should definitely use setattr instead.
Actually, 99% of time there are better options for what you want rather than using exec .

Try this one:

setattr(self, name + "_index", index)

Eval evaluates an expression. Different from C, in Python an assignment is a statement, not an expression (you cannot write c = (a = b) == None , for example. The variant a = b = 3 is somewhat special syntax. It does actually not pass the value assigned to b , but the value on the right side (yes, this is a subtle, but important difference).

If it just for an index, there may be better versions which do not pullute the namespace, however.

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