global/local variables

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Jan 25 05:31:39 EST 2008


On Thu, 24 Jan 2008 23:04:42 -0800, Tim Rau wrote:

> UnboundLocalError: local variable 'nextID' referenced before assignment

When you assign to a name in Python, the compiler treats it as a local 
variable. So when you have a line like this:

nextID += 1  # equivalent to nextID = nextID + 1

you are getting the value of the _local_ nextID before you have assigned 
a value to it.

> I want to know why it says 'local variable' it never had a problem when
> just allThings was in there.

Because you don't assign to allThings, and therefore it is treated as 
global.


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

*shrug* Or you could consider a different program structure completely. 

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

Hey, it's your time and effort. If you want to, you can download the 
Python "goto" module, and use goto and comefrom in your code.

No, that's unfair. Globals aren't as harmful as goto. I'm not saying that 
globals are verboten or that they have no place in 21st century 
programming at all. Since I know nothing about your program, I can't 
judge whether globals are the right way to go or not. But I am saying 
that as a general rule, reliance on global variables often leads to 
fragile code with hard-to-diagnose bugs. Your mileage may vary.



-- 
Steven



More information about the Python-list mailing list