Variables in nested functions

Z

zero.maximum

Is it possible to change the value of a variable in the outer function
if you are in a nested inner function?

For example:

def outer():
a = "outer"
def inner():
print a
a = "inner"
# I'm trying to change the outer 'a' here,
# but this statement causes Python to
# produce an UnboundLocalError.
return inner

What I'm trying to do here is to get the following output from these
lines of code?
# Code:
func = outer()
func()
func()
func()

# Output:
outer
inner
inner
 
B

Ben Cartwright

Is it possible to change the value of a variable in the outer function
if you are in a nested inner function?

The typical kludge is to wrap the variable in the outer function inside
a mutable object, then pass it into the inner using a default argument:

def outer():
a = "outer"
def inner(wrapa=[a]):
print wrapa[0]
wrapa[0] = "inner"
return inner

A cleaner solution is to use a class, and make "a" an instance
variable.

--Ben
 
B

Bruno Desthuilliers

Is it possible to change the value of a variable in the outer function
if you are in a nested inner function?

Depends on what you mean by "changing the value". If you mean mutating a
mutable object, yes, it's possible. If you mean rebinding the name to a
different object, no, it isn't possible actually.
 
B

Bryan Olson

Ben said:
The typical kludge is to wrap the variable in the outer function inside
a mutable object, then pass it into the inner using a default argument:

def outer():
a = "outer"
def inner(wrapa=[a]):
print wrapa[0]
wrapa[0] = "inner"
return inner

As of Python 2.2, scopes nest, as per PEP 227.
We still need a mutable, but not a default argument:

def outer():
a = ["outer"]
def inner():
print a[0]
a[0] = "inner"
return inner
 

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

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,610
Members
45,255
Latest member
TopCryptoTwitterChannels

Latest Threads

Top