global/local variables

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Jan 24 19:09:05 EST 2008


On Thu, 24 Jan 2008 15:37:09 -0800, Tim Rau wrote:

> What makes python decide whether a particular variable
> is global or local? 

For starters, if the line of code is not inside a class or function, that 
is, it's at the top level of a module, it is global.

More interesting is if it is inside a function or class. If you assign to 
the name in the function, Python assumes it is local *unless* you have 
defined it as global with the global statement.

Otherwise, Python will treat it as global.


> I've got a list and a integer, both defined at top level, no
> indentation, right next to each other:
> 
> allThings = []
> nextID = 0
>
> and yet, in the middle of a function, python sees one and doesn't see
> the other:

I've tried to run your code -- and it isn't easy, involving much 
backwards-and-forwards copying and pasting, thanks to word-wrap in you 
post -- and the error I get is:

SyntaxError: invalid syntax

because you left off the colon from the first if statement.

I'm not especially inclined to start hunting through your code fixing any 
other errors in order to find the error you think you're getting. How 
about if you quote the exception traceback you actually get? 


> I don't think it's important, but the function is defined before 
> the two globals.

Nope, not important. What's important is whether the function is *called* 
before or after the globals are created.

If you're using global variables in your code, you probably should stop. 
As a general rule, global variables are poor programming practice for a 
number of reasons. Google on "Global variables considered harmful" for 
some examples.



-- 
Steven



More information about the Python-list mailing list