On Sun, 17 Oct 2010 03:58:21 -0700, Yingjie Lan wrote:

> I played with an example related to namespaces/scoping. The result is a
> little confusing:

>>>> a=1
>>>> def f():
>       a = a + 1
>       return a
> 
>>>> f()

> UnboundLocalError: local variable 'a' referenced before assignment

If you want to modify a global variable, you have to explicitly declare it
as global. In this case, you need to add "global a" at the top of the
function.

If a function assigns to a name which isn't explicitly declared global, it
is treated as a local variable. If you reference it before the first
assignment, you get the above error.

If the function doesn't assign to it, or if it's explicitly declared
global, it is treated as global variable.

The determination of local or global is made when the "def" statement is
executed, not when the function is called.

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

Reply via email to