Python + = vs. .extend () inside a global variable function

I read several other SOs ( PythonScope and global global values ​​are not needed), but nothing seems to explain as clearly as I would like, and I am having problems with mental sifting, regardless of whether 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 it is clear,

>>> foo()
UnboundLocalError

and

bar()  # works
myList # shows [1, 2, 3]

but then

>>> baz()
UnboundLocalError

I thought, however, that such things as +=are implicitly called method statements, in this case extend(), but the error implies that for some reason it does not actually consider +=how extends(). Is this consistent with how Python parsing should work?

, , -, . , += . , , , - ( , ):

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

, += extend().

- ( ...), , , myList baz() , += extend(), ?

+5
2

+= extend(). -, .

assignment, :

.

():

: . : .

:

- :

. :

>>> def baz():
        myList += [2, 3]


>>> dis.dis(baz)
  2           0 LOAD_FAST                0 (myList)
              3 LOAD_CONST               1 (2)
              6 LOAD_CONST               2 (3)
              9 BUILD_LIST               2
             12 INPLACE_ADD         
             13 STORE_FAST               0 (myList)
             16 LOAD_CONST               0 (None)
             19 RETURN_VALUE  

(, , ) , , , , .

myList, LOAD_FAST, global, :

LOAD_FAST(var_num)

co_varnames[var_num] .

, . , , , oppcode INPLACE_ADD, myList.__iadd__, , , , .

global, .

+3

, myList. . , + =

myList = [1]

def foo():
    global myList
    myList = myList + [2, 3]
def bar():
    myList.extend([2, 3])
def baz():
    global myList
    myList += [2, 3]

foo()
bar()
baz()
0

All Articles