I've read a few other SO (PythonScope and globals don't need global) but nothing seems to explain as explicitly as I would like and I'm having trouble mentally sifting through whether or not PyDocs tells me the answer to my question:
myList = [1]
def foo():
myList = myList + [2, 3]
def bar():
myList.extend([2, 3])
def baz():
myList += [2, 3]
Now, understandably,
>>> foo()
UnboundLocalError: local variable 'myList' referenced before assignment
and
bar() # works
myList # shows [1, 2, 3]
but then
>>> baz()
UnboundLocalError: local variable 'myList' referenced before assignment
I thought, however, that things like +=
implicitly called the method operators, in this case extend()
, but the error implies that for some reason it does not actually treat +=
as extends()
. Is this consistent with how Python parsing ought to work?
I would have thought that calling functions that are equivalent to method-operators, they would be equivalent in all cases. Instead it seems that it treats +=
as an actual assignment operator. Except, this isn't completely true, because if I do something (admittedly contrived):
myList = range(50000000) # wait a second or two on my laptop before returning
myList += [0] # returns instantly
myList = myList + [1] # wait a second or two before returning
all of which is expected, if +=
actually just calls extend()
.
Is there some finer distinction (or very obvious point...) that I'm missing that makes it clear that myList
in baz()
needs to be treated as a local variable, and that therefore the +=
cannot be implicitly converted to an extend()
such that it recognizes the global variable?