please help explain this result

TomF tomf.sessile at gmail.com
Sun Oct 17 13:51:47 EDT 2010


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.

-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