On 11/05/2014 19:40, Ned Batchelder wrote:
On 5/11/14 9:46 AM, Rotwang wrote:
On 11/05/2014 04:11, Steven D'Aprano wrote:
[...]

And try running
this function in both 2.7 and 3.3 and see if you can explain the
difference:

def test():
     if False: x = None
     exec("x = 1")
     return x

I must confess to being baffled by what happens in 3.3 with this
example. Neither locals() nor globals() has x = 1 immediately before the
return statement, so what is exec("x = 1") actually doing?


The same happens if you try to modify locals():

     >>> def test():
     ...   if 0: x = 1
     ...   locals()['x'] = 13
     ...   return x
     ...
     >>> test()
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
       File "<stdin>", line 4, in test
     UnboundLocalError: local variable 'x' referenced before assignment

The doc for exec says:

     Note: The default locals act as described for function locals()
     below: modifications to the default locals dictionary should not be
     attempted. Pass an explicit locals dictionary if you need to see
     effects of the code on locals after function exec() returns.

The doc for locals says:

     Note: The contents of this dictionary should not be modified;
     changes may not affect the values of local and free variables used
     by the interpreter.

This is a tradeoff of practicality for purity: the interpreter runs
faster if you don't make locals() a modifiable dict.

Thanks.
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to