Does a list_iterator garbage collect its consumed values?

给你一囗甜甜゛ 提交于 2019-12-22 10:27:46

问题


Suppose I have li = iter([1,2,3,4]).

Will the garbage collector drop the references to inaccessible element when I do next(li).

And what about deque, will elements in di = iter(deque([1,2,3,4])) be collectable once consumed.

If not, does a native data structure in Python implement such behaviour.


回答1:


https://github.com/python/cpython/blob/bb86bf4c4eaa30b1f5192dab9f389ce0bb61114d/Objects/iterobject.c

A reference to the list is held until you iterate to the end of the sequence. You can see this in the iternext function.

The deque is here and has no special iterator.

https://github.com/python/cpython/blob/master/Modules/_collectionsmodule.c

You can create your own class and define __iter__ and __next__ to do what you want. Something like this

class CList(list):
    def __init__(self, lst):
        self.lst = lst

    def __iter__(self):
        return self

    def __next__(self):
        if len(self.lst) == 0:
            raise StopIteration
        item = self.lst[0]
        del self.lst[0]
        return item

    def __len__(self):
      return len(self.lst)


l = CList([1,2,3,4])

for item in l:
  print( len(l) )


来源:https://stackoverflow.com/questions/54661382/does-a-list-iterator-garbage-collect-its-consumed-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!