This is my code:
def outer():
x = 0
d = { 'a' : 'b' }
def inner():
for _ in xrange(10):
x += 1
d['a'] = x
yield x
for y in inner():
print y
print "%d rounds" % (x)
outer()
Which gives:
Traceback (most recent call last):
File "xxx.py", line 14, in <module>
outer()
File "xxx.py", line 11, in outer
for y in inner():
File "xxx.py", line 8, in inner
x += 1
UnboundLocalError: local variable 'x' referenced before assignment
If I define x
locally in inner
the problem disappears. In other words: inner
can not modify the externally defined integer, but it can modify the dictionary. I guess this is because assigning x
requires read/write access to it, but assigning to the dictionary does not require read/write access to the dictionary: the update is done to an element of the dictionary?
How can I implement inner
so that I can access and modify the variable x
defined outer
?