Values and objects

Ned Batchelder ned at nedbatchelder.com
Sun May 11 14:40:24 EDT 2014


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.

-- 
Ned Batchelder, http://nedbatchelder.com




More information about the Python-list mailing list