Python: yield-and-delete

后端 未结 4 1799
逝去的感伤
逝去的感伤 2021-02-02 15:45

How do I yield an object from a generator and forget it immediately, so that it doesn\'t take up memory?

For example, in the following function:

def grou         


        
4条回答
  •  情话喂你
    2021-02-02 16:13

    If you really really want to get this functionality I suppose you could use a wrapper:

    class Wrap:
    
        def __init__(self, val):
            self.val = val
    
        def unlink(self):
            val = self.val
            self.val = None
            return val
    

    And could be used like

    def grouper(iterable, chunksize):
        i = iter(iterable)
        while True:
            chunk = Wrap(list(itertools.islice(i, int(chunksize))))
            if not chunk.val:
                break
            yield chunk.unlink()
    

    Which is essentially the same as what phihag does with pop() ;)

提交回复
热议问题