syntax error in eval()

Steven Bethard steven.bethard at gmail.com
Mon Jan 10 11:47:22 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

You may want to use exec instead of eval:

py> class X(object):
...     pass
...
py> attrname = "attr"
py> exec "X.%s = val" % attrname in dict(X=X, val=5)
py> X.attr
5

But personally, I'd use setattr, since that's what it's for:

py> class X(object):
...     pass
...
py> attrname = "attr"
py> setattr(X, attrname, 5)
py> X.attr
5

Steve



More information about the Python-list mailing list