properties vs. eval()

Peter Otten __peter__ at web.de
Wed May 4 15:40:50 EDT 2005


Bob  Rogers wrote:

> 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

I believe it is an implementation accident that this works.

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

Use 

eval(s) 

to evaluate an expression and 

exec s

to execute a statement.

Peter




More information about the Python-list mailing list