This bit of Python does not work:

def make_incrementer(start):
    def closure():
        # I know I could write 'x = start' and use x - that's not my point though (:
        while True:
            yield start
            start += 1
    return closure

x = make_incrementer(100)
iter = x()
print iter.next()    # Exception: UnboundLocalError: local variable 'start' referenced before assignment

I know how to fix that error, but bear with me:

This code works fine:

def test(start):
    def closure():
        return start
    return closure

x = test(999)
print x()    # prints 999

Why can I read the start variable inside a closure but not write to it? What language rule is causing this handling of the start variable?

Update: I found this SO post relevant (the answer more than the question): Read/Write Python Closures

Edit
Report