2

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?

blueFast
  • 41,341
  • 63
  • 198
  • 344
  • You are **rebinding** `x` to a new value. `x += 1` for an immutable `x` *has* to bind `x` to a new value. `x += something` for a mutable value will still rebind, but can *potentially* change the mutable object in place. `d['a'] = x` doesn't rebind the name `d` to anything else, it mutates the object *referenced* by `d`. `d` still points to the dictionary, only `d['a']` is altered to add a new key or update an existing key to reference whatever `x` is referencing. – Martijn Pieters Sep 26 '14 at 12:33

0 Answers0