Trouble with nested scopes when trying to rebind a variable

Alexander Schmolck a.schmolck at gmx.net
Fri Nov 21 10:40:25 EST 2003


Fernando Rodriguez <frr at easyjob.net> writes:

> Hi,
> 
> I have a parameter defined in a module, called PREVIEW.  Many functions use
> it's value to modify their behavior.
> 
> A function called dispatch checks the user arguments in sys.argv and calls the
> appropriate function. It should also modify the value of PREVIEW depending on
> the user input.
> 
> 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?

Just as you'd modify any variable, really (provided you're actually using a
*mutatable* datatype like a list),

  PREVIEW[:] = []

However, what you actual seem to be after is globally reassigning the name
PREVIEW. so do:

def some_fun(bla):
  global preview
  preview = None

 
> In Lisp there are different operators to rebind an existing variable and to
> create a new variable.  How do you do this in python?

You don't.

'as




More information about the Python-list mailing list