In Python 3.x this is possible:
def f1():
x = 5
def f2():
nonlocal x
x+=1
return f2
The problem and a solution to it, for Python 2.x as well, are given in this post. Additionally, please read PEP 3104 for more information on this subject.
Answer from hochl on Stack OverflowIn Python 3.x this is possible:
def f1():
x = 5
def f2():
nonlocal x
x+=1
return f2
The problem and a solution to it, for Python 2.x as well, are given in this post. Additionally, please read PEP 3104 for more information on this subject.
def f1():
x = { 'value': 5 }
def f2():
x['value'] += 1
Workaround is to use a mutable object and update members of that object. Name binding is tricky in Python, sometimes.
Take this function as an example:
def foo(self, param1):
count = 0
buffer = []
def inner(x):
buffer.append(x + param1)
count += 1
inner(5)
So, the inner function can freely access param1 and buffer. However, it will complain about count, and in order to make it work, you need to declare "nonlocal count".
I was wondering why is this the case, how is the stack organized such that param1 and buffer is accessible without the need to declare nonlocal, but for count, it needs a nonlocal declaration? I'm guessing it has something to do with it being a primitive... but then again, so is param1
python - inner function accessing outer function's variable - Stack Overflow
python - Inner function accessing variables directly from outer function scope - What are the drawbacks? - Code Review Stack Exchange
Nested function has an issue with a variable
ironpython - Is there a way to use variable from outer function in the inner function body, in Python? - Stack Overflow
You could simply reference the 'theVariable' inside the nested InnerFunction, if you don't want to pass it's value as a parameter:
def OuterFunction():
# Declare the variable
theVariable = 42
def InnerFunction():
# Just reference the 'theVariable', using it, manipulating it, etc...
print(theVariable)
# Call the InnerFunction inside the OuterFunction
InnerFunction()
# Call the OuterFunction on Main
OuterFunction()
# It will print '42' as result
You can just reference the variable directly, as follows;
def outer():
x = 1
def inner():
print(x + 2)
inner()
outer()
Prints: 3