why "gc.get_objects“ in function will make circular reference or memory leak?

Viewed 35

this code will make circular reference!, if object disable automatic garbage collection,"gc.disable()", running it will make memory leaking!

import gc, sys


def test_func():
    objs = gc.get_objects()
    priint("-----End: test_func %s" % sys.getrefcount(test_func))

test_func()

l know this is right, but why???

import gc, sys


def test_func():
    objs = gc.get_objects()
    del objs
    priint("-----End: test_func %s" % sys.getrefcount(test_func))

test_func()

version: 2.7 thank bro!

1 Answers

I knew it

case frame in gc.get_objects()


def TestFunc3():
    lst = gc.get_objects()
    print("sys._getframe() in lst: %s" % (sys._getframe() in lst))
    print lst in sys._getframe().f_locals.values()
    
print("--TestFunc3 ref: %s" % sys.getrefcount(TestFunc3))
TestFunc3()
print("--TestFunc3 ref: %s" % sys.getrefcount(TestFunc3))
TestFunc3()
print("--TestFunc3 ref: %s" % sys.getrefcount(TestFunc3))


"""
--TestFunc3 ref: 2
sys._getframe() in lst: True
True
--TestFunc3 ref: 3
sys._getframe() in lst: True
True
--TestFunc3 ref: 4
"""
Related