global/local variables

Helmut Jarausch jarausch at
Fri Jan 25 10:12:02 CET 2008

Tim Rau wrote:

> I'm sorry: I forgot to say what my problem was. Python seems to think
> that nextID is a local, and complains that it can't find it. THis is
> not the full text of the function, just the level that is causing
> errors. the lack of : on the if is a transcription error.
> Traceback (most recent call last):
>   File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
> \", line 248, in <module>
>     thing.step()
>   File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
> \", line 112, in step
>     allThings[len(allThings)-1].id = nextID
> UnboundLocalError: local variable 'nextID' referenced before
> assignment

But in the next line in the same function you say
   nextID+= 1

Since there is an assignment to nextID in the same function without
a global statement, you tell Python, that nextID is a local variable.

Note:  Assignment (anywhere in a function) is a local definition unless
        there is a global statement in this function

> I want to know why it says 'local variable' it never had a problem
> when just allThings was in there.
> as for the objection to global variable: If I didn't make them global,
> I'd make them part of a singleton class called gameVars that would get
> passed everywhere. It's unlikely that they'll get mixed in with
> anyhting else, as they fulfill a unique function. Also, I think it's
> more convenient, and I am, after all, my own employer when it comes to
> programming.

Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany

More information about the Python-list mailing list