syntax error in eval()

Duncan Booth duncan.booth at invalid.invalid
Mon Jan 10 11:50:16 EST 2005


harold fellermann wrote:

> Python 2.4 (#1, Dec 30 2004, 08:00:10)
> [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> class X : pass
> ...
> >>> attrname = "attr"
> >>> eval("X.%s = val" % attrname , {"X":X, "val":5})
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
>    File "<string>", line 1
>      X.attr = val
>             ^
> SyntaxError: invalid syntax
> 
> 
> Does anyone have a clue what might be wrong? Thanks in advance.

What you are doing wrong is attempting to use eval before exhausting all 
the simpler techniques. Why not just call 'setattr'?

>>> setattr(X, 'attr', 5)

BTW, the syntax error is because eval evaluates an expression and 
an assignment statement is a statement not an expression.



More information about the Python-list mailing list