I have nested a function definition bar() inside another function foo(). Now I am trying to access a variable located in the outer function foo() from the nested function bar(). This however doesn't work because of the scoping rules (see error traceback below).
I am looking for something similar to the global keyword, which however only enables me to access global variables, whereas this is some kind of semi-global variable.
Here's example code:
def foo():
i = 0
def bar():
# how can I get access to the variable from enclosing scope?
i += 1
bar()
foo()
The output is:
$ python test.py
Traceback (most recent call last):
File "test.py", line 7, in <module>
foo()
File "test.py", line 5, in foo
bar()
File "test.py", line 4, in bar
i += 1
UnboundLocalError: local variable 'i' referenced before assignment