Paddy wrote: > Hi, > I am trying to work out why I get UnboundLocalError when accessing an > int from a function where the int is at the global scope, without > explicitly declaring it as global but not when accessing a list in > similar circumstances. >
There has just been a long thread about this. I think I understand it now. Here is my explanation. Ignoring nested scopes for this exercise, references to objects (i.e. variable names) can exist in the local namespace or the global namespace. Python looks in the local namespace first, and if not found looks in the global namespace. Any name assigned to within the function is automatically deemed to exist in the local namespace, unless overridden with the global statement. With the statement 'm = m + 1', as m is assigned to on the LHS, it is deemed to be local, but as m does not yet have a value on the RHS, you get Unbound Local Error. With the statement 'n[0] = n[0] + 1', n is not being assigned to, as it is mutable. Therefore Python looks in the global namespace, finds n there, and uses it successfully. My 2c Frank Millman -- http://mail.python.org/mailman/listinfo/python-list