syntax error in eval()

H

harold fellermann

Hi all,

I am trying to dynamically add class attributes at runtime using the
function eval(),
i.e. I want to do something like

but without knowing either the attributes name nor its value.
However, I encounter a syntax error I cannot understand:

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

- harold -
 
S

Steven Bethard

harold said:
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.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
 
D

Duncan Booth

harold said:
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.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'?

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

harold fellermann

Thank you, Duncan and Steven.
I completely forgot about setattr.
Of course that's the way ... as its name might suggest *g*
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top