Trouble with nested scopes when trying to rebind a variable

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Nov 21 09:42:29 EST 2003


Fernando Rodriguez <frr at easyjob.net> wrote in
news:187srv08b4hbsckjje6s79dmipug8lcqlh at 4ax.com: 

> And here's where I get into trouble:  if I write something like
> PREVIEW = None inside the body of a function, it doesn't modify the
> value of the existing PREVIEW variable, it creates a new variable in
> the function scope. 
> 
> How can I modify the external PREVIEW variable?
> 
> In Lisp there are different operators to rebind an existing variable
> and to create a new variable.  How do you do this in python?

Use the global statement in the function to declare that you want to 
modify the global variable rather than creating a local variable, see 
section 6.13 of the reference manual.  e.g.

PREVIEW = 0

def aFunction():
    global PREVIEW
    PREVIEW = 1

Better still, use classes and get rid of the global variable altogether.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list