0

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?

  • Assigning to a slice of a list mutates the list. – Ry- Apr 02 '17 at 05:38
  • Thanks. But why `self.thelist=self.workingcopy` cannot change the contents of `self.thelist`? – Xiaoguang Niu Apr 02 '17 at 05:47
  • `self.workingcopy` points to a list. If you set `self.list = self.workingcopy`, it just makes it point to a new list instead of *changing* the list it points to. – Ry- Apr 02 '17 at 06:30

0 Answers0