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.
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


--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to