Does python garbage-collect at the end of an iteration in a loop?

前端 未结 2 475
青春惊慌失措
青春惊慌失措 2021-01-18 11:25

Please observe this simple code:

    import random
    while True:
        L = list( str(random.random()))

Question: if I let this

2条回答
  •  我在风中等你
    2021-01-18 12:05

    We can easily test this by adding a custom __del__ command to a class as watch what happens:

    class WithDestructor(object):
       def __del__(self):
           print(f"Exploding {self}")
    
    Q=None
    for i in range(5):
        Q = WithDestructor()
        print(f"In loop {i}")
    

    If cleanup only happened at the end of the loop, we'd get the loop output followed by the destructor output. Instead I get it interlaced, so the object in Q is getting immediately cleaned up when Q is reassigned.

    In loop 0
    Exploding <__main__.WithDestructor object at 0x7f93141176d8>
    In loop 1
    Exploding <__main__.WithDestructor object at 0x7f93141172b0>
    In loop 2
    Exploding <__main__.WithDestructor object at 0x7f93141176d8>
    In loop 3
    Exploding <__main__.WithDestructor object at 0x7f93141172b0>
    In loop 4
    

提交回复
热议问题