Note that there are some explanatory texts on larger screens.

plurals
  1. POPython += versus .extend() inside a function on a global variable
    text
    copied!<p>I've read a few other SO (<a href="https://stackoverflow.com/questions/146359/python-scope">PythonScope</a> and <a href="https://stackoverflow.com/questions/14323817/global-dictionaries-dont-need-keyword-global-to-modify-them">globals don't need global</a>) but nothing seems to explain as explicitly as I would like and I'm having trouble mentally sifting through whether or not <a href="http://docs.python.org/3/reference/lexical_analysis.html#operators" rel="nofollow noreferrer">PyDocs</a> tells me the answer to my question:</p> <pre><code>myList = [1] def foo(): myList = myList + [2, 3] def bar(): myList.extend([2, 3]) def baz(): myList += [2, 3] </code></pre> <p>Now, understandably, </p> <pre><code>&gt;&gt;&gt; foo() UnboundLocalError </code></pre> <p>and</p> <pre><code>bar() # works myList # shows [1, 2, 3] </code></pre> <p>but then</p> <pre><code>&gt;&gt;&gt; baz() UnboundLocalError </code></pre> <p>I thought, however, that things like <code>+=</code> implicitly called the method operators, in this case <code>extend()</code>, but the error implies that for some reason it does not actually treat <code>+=</code> as <code>extends()</code>. Is this consistent with how Python parsing ought to work?</p> <p>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 <code>+=</code> as an actual assignment operator. Except, this isn't completely true, because if I do something (admittedly contrived):</p> <pre><code>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 </code></pre> <p>all of which is expected, if <code>+=</code> actually just calls <code>extend()</code>. </p> <p>Is there some finer distinction (or very obvious point...) that I'm missing that makes it clear that <code>myList</code> in <code>baz()</code> needs to be treated as a local variable, and that therefore the <code>+=</code> cannot be implicitly converted to an <code>extend()</code> such that it recognizes the global variable?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload