Scope, type and UnboundLocalError

Paddy paddy3118 at netscape.net
Sun Jul 9 04:32:06 EDT 2006


Frank Millman wrote:
> 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.
> >
>
> 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
So, to paraphrase to test my understanding:

in the statement: ' n[0] = n[0] + 1' it is the object referenced by the
name n that is being assigned to rather than n itself, so n is not
'tagged' as a local variable by the LHS of the assignment.

Thanks Frank. all is is now clear :-)




More information about the Python-list mailing list