Trouble with nested scopes when trying to rebind a variable

F

Fernando Rodriguez

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?

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

Duncan Booth

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

Alexander Schmolck

Fernando Rodriguez said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top