Python Delegate Pattern - How to avoid circular reference?

情到浓时终转凉″ 提交于 2019-12-05 15:15:58

Python already does garbage collection. You only need to do something special if you write your own container types in C, as extensions.

Demo: Run this program and watch the memory usage not climb.

class C(object):
    pass

def circular():
    for x in range(10**4):
        for y in range(10**4):
            a = C()
            b = C()
            a.x = b
            b.x = a

circular()

Footnote: The following function doesn't do anything, delete it.

def setDelegate(self, delegate):
    self.delegate = delegate

Instead of calling x.setDelegate(y), you can use x.delegate = y. You can overload member access in Python, so there's no benefit to writing a method.

Why wouldn't it be garbage collected at the end? When the script is over and python completes execution, the entire section of memory will be marked for garbage collection and (eventually) OS recovery.

If you're running this in a long-running program, once A and B are both dereferenced, then the memory will be reclaimed.

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