Reason for unintuitive UnboundLocalError behaviour 2
Posted
by
Jonathan
on Stack Overflow
See other posts from Stack Overflow
or by Jonathan
Published on 2010-12-26T14:21:45Z
Indexed on
2010/12/26
14:54 UTC
Read the original article
Hit count: 165
Following up on Reason for unintuitive UnboundLocalError behaviour (I will assume you've read it). Consider the following Python script:
def f():
# a+=1 # 1
aa=a
aa+=1
# b+='b' # 2
bb=b
bb+='b'
c[0]+='c' # 3
c.append('c')
cc=c
cc.append('c') # 4
a=1
b='b'
c=['c']
f()
print a
print b
print c
The result of the script is:
1
b
['cc', 'c', 'c']
The commented out lines (marked 1,2) are lines that would through an UnboundLocalError and the SO question I referenced explains why. However, the line marked 3 works!
By default, lists are copied by reference in Python, therefore it's understandable that c changes when cc changes. But why should Python allow c to change in the first place, if it didn't allow changes to a and b directly from the method's scope?
I don't see how the fact that by default lists are copied by reference in Python should make this design decision inconsistent.
What am I missing folks?
© Stack Overflow or respective owner