classification
Title: Wrong UnboundLocalError with += operator
Type: behavior Stage:
Components: Interpreter Core Versions: Python 2.5.3
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: benjamin.peterson, eric
Priority: normal Keywords:

Created on 2008-10-12 13:56 by eric, last changed 2008-10-12 14:08 by benjamin.peterson. This issue is now closed.

Messages (3)
msg74666 - (view) Author: Eric (eric) Date: 2008-10-12 13:56
the following code :

def test():
    code=''
    def sub(n):
        for i in range(n):
            code+=str(i)
    sub(5)
    sub(10)
    return code

>>> test()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "<console>", line 6, in test
  File "<console>", line 5, in sub
UnboundLocalError: local variable 'code' referenced before assignment

error came from the += operator.
Tested for code initialized to '', to 0
I guess it's the same for all inline operators.

I agree that global variables CANNOT be assigned, it's ok.

But += (and I guess *= etc) operators are not assignements, and are not 
different from .append(), or .extend() methods.

I was expecting += to work the same as append() method
msg74667 - (view) Author: Benjamin Peterson (benjamin.peterson) * (Python committer) Date: 2008-10-12 14:05
Is code a global variable?
msg74668 - (view) Author: Benjamin Peterson (benjamin.peterson) * (Python committer) Date: 2008-10-12 14:08
Inplace operators ("+=", "-=" etc) are assignments since in the case of
immutable types like str

code += "some string"

is equivalent to

code = code + "some string"
History
Date User Action Args
2008-10-12 14:08:36benjamin.petersonsetstatus: open -> closed
resolution: not a bug
messages: + msg74668
2008-10-12 14:05:18benjamin.petersonsetnosy: + benjamin.peterson
messages: + msg74667
2008-10-12 13:56:41ericcreate