please help explain this result

Paul Kölle paul at subsignal.org
Sun Oct 17 22:23:43 CEST 2010


Am 17.10.2010 19:51, schrieb TomF:
> On 2010-10-17 10:21:36 -0700, Paul Kölle said:
>> Am 17.10.2010 13:48, schrieb Steven D'Aprano:
>>> On Sun, 17 Oct 2010 03:58:21 -0700, Yingjie Lan wrote:
>>>
>>>> Hi,
>>>>
>>>> I played with an example related to namespaces/scoping. The result is a
>>>> little confusing:
>>>
>>> [snip example of UnboundLocalError]
>>>
>>> Python's scoping rules are such that if you assign to a variable
>>> inside a
>>> function, it is treated as a local. In your function, you do this:
>>>
>>> def f():
>>> a = a + 1
>>>
>>> Since a is treated as a local, when you enter the function the local
>>> a is
>>> unbound -- it does not have a value. So the right hand side fails, since
>>> local a does not exist, and you get an UnboundLocalError. You are trying
>>> to get the value of local "a" when it doesn't have a value.
>
> Steven's explanation is correct. In your example below you're altering
> portions of a global data structure, not reassigning a global variable.
> Put another way, there is a significant difference between:
> a = 7
> and:
> a['x'] = 7
>
> Only the first reassigns a global variable.

Thanks Tom and Dennis.

This will teach me (hopefully) to pay attention to details next time and 
I think I learned something too. I always thought the rules about 
changing "global" objects where inconsistent because it works for 
mutables... Turns out it's all fine since assignment doesn't work for 
mutables too and assignment just happens to be the only way to "change" 
immutables ;)

cheers
  Paul

>
> -Tom
>
>> Oh really? Can you explain the following?
>>
>> >>> a = {}
>> >>> def foo():
>> ... a['a'] = 'lowercase a'
>> ... print a.keys()
>> ...
>> >>> foo()
>> ['a']
>> >>> a
>> {'a': 'lowercase a'}
>> >>> def bar():
>> ... a['b'] = a['a'].replace('a', 'b')
>> ...
>> >>> bar()
>> >>> a
>> {'a': 'lowercase a', 'b': 'lowercbse b'}
>> >>>
>>
>> cheers
>> Paul
>
>





More information about the Python-list mailing list