为什么这不会产生预期的垃圾?

时间:2019-04-08 04:05:36

标签: python multidimensional-array garbage-collection

我试图提出一个简洁的示例,说明对象的垃圾回收,没有变量名持有对该对象的引用,但是此代码似乎不起作用。我想了解为什么更好地了解Python的内部功能。似乎暴露了我误会的东西。

some_name = [['some_nested_lst_object_with_an_str_object']]
id(some_name)
'''
you don't normally need to do this.
This is done for the reference example.
Accessing garbage collector:
'''
import gc
print(gc.collect())
'''
If I assign something new to ''*some_name*'',
the reference to the previous object will be lost:
'''
some_name
print(gc.collect())
some_name = [[['something_new']]]
some_name
print(gc.collect())

1 个答案:

答案 0 :(得分:2)

Python通常使用引用计数来释放对象。 仅在循环引用的情况下,才需要垃圾回收:

some_name = [123]
print(gc.collect())
some_name = [] # previous some_name-object is freed directly
some_name.append(some_name) # cyclic reference
print(gc.collect()) # 0
some_name = None
print(gc.collect()) # 1