Given this class:
class C(object):
def set_x(self, x):
self._x = x
def get_x(self):
return self._x
x = property(get_x, set_x)
This use of compile() and eval() works as I expected it to:
c = C()
c.x = 5000
n = '\'five thousand\''
code = compile('c.x = ' + n, '<input>', 'exec')
print 'before ', c.x
eval(code)
print 'after ', c.x
But this, using eval() without compile(), does not:
c = C()
c.x = 5000
n = '\'five thousand\''
print 'before ', c.x
eval('c.x = ' + n)
print 'after ', c.x
It gives:
before 5000
Traceback (most recent call last):
File "./r.py", line 16, in ?
eval('c.x = ' + n)
File "<string>", line 1
c.x = 'five thousand'
^
SyntaxError: invalid syntax
Could someone please explain just what is going on here, and whether it
is possible to dispense with the compile step and use eval() alone
while setting a property?
Thanks.