1

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?

1
  • 2
    Use exec for "commands" (like x = 5), and eval for expressions (like 2**5). And yes, using setattr is definitely better. Commented May 7, 2015 at 22:59

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.