global/local variables

Diez B. Roggisch deets at nospam.web.de
Thu Jan 24 18:48:53 EST 2008


Tim Rau schrieb:
> What makes python decide whether a particular variable is global or
> local? 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:
> 
> class ship(thing):
> ###snip###
>     def step(self):
> ###snip###
>         if keys[K_up]
>             for n in range(0,2):  #sparks/newton second is
> proportional to framerate
>                 divergence = 5.0
>                 p = self.body.getRelPointPos((-0.15,0,0))
>                 v = self.body.vectorToWorld((-100+ random.uniform(-
> divergence,divergence) ,random.uniform(-divergence,divergence),0))
>                 allThings.append(particle(p,v))
>                 allThings[len(allThings)-1].id = nextID
>                 nextID += 1
> 
> 
> I don't think it's important, but the function is defined before the
> two globals. What gives?

The difference is that you assign to nextID in your function. Statements 
of the form


foo = expression

will make foo a function-local variable.

If you want it to be a module-global, you need to do

global foo

foo = expression

If you do this:


bar = 10

def f():
    print bar

you don't assign to a variable, but only read. So if it's not found 
locally, it will be looked up globally.

Diez



More information about the Python-list mailing list