Question about name scope

Ethan Furman ethan at stoneleaf.us
Wed Feb 1 18:59:37 EST 2012


Ian Kelly wrote:
> On Wed, Feb 1, 2012 at 4:41 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
>> I'm not sure what you mean by temporary:
>>
>> --> def f(x, y):
>>
>> ...     frob = None
>> ...     loc = locals()
>> ...     loc[x] = y
>> ...     print(loc)
>> ...     print(locals())
>> ...     print(loc)
>> ...     print(locals())
>> ...
>> -->
>> --> f('frob', 19)
>> {'y': 19, 'x': 'frob', 'frob': 19}
>> {'y': 19, 'x': 'frob', 'frob': None, 'loc': {...}}
>> {'y': 19, 'x': 'frob', 'frob': None, 'loc': {...}}
>> {'y': 19, 'x': 'frob', 'frob': None, 'loc': {...}}
>>
>> Seems to be stuck that way.
> 
> The first print is the one that is incorrect.  It suggests that the
> local 'frob' has been changed to 19 as it has in the dict, but the
> actual value of the local is still None.  The second print on
> accurately reflect that.

Ah.  Thanks for the explanations.

~Ethan~



More information about the Python-list mailing list