When I read the chapter 5 of the book Python Essential Reference, I have met some problem in the example ListTransaction. Here is the original code:
class ListTransaction(object):
def __init__(self,thelist):
self.thelist=thelist
def __enter__(self):
self.workingcopy=list(self.thelist)
return self.workingcopy
def __exit__(self,type,value,tb):
if type is None:
self.thelist[:]=self.workingcopy
return False
items=[1,2,3]
with ListTransaction(items) as working:
working.append(4)
working.append(5)
print(items) #[1,2,3,4,5]
It works as expected. But if I omit the [:]
in the definition of __exit__()
, that is, the 9th line becomes
self.thelist=self.workingcopy
then the output will be
[1,2,3].
So what's the difference between the presence and absence of [:]
after a list?