Python:weakref
lastmod 2024-07-18created 2021-10-275 edits
Simple example
import weakref
class Apple:
color: str
a = Apple()
a.color = 'red'
r = weakref.ref(a) # 약한 참조 객체 생성
ref_a = r() # 원본 객체의 참조 생성
assert a.color == 'red'
assert ref_a.color == 'red'
assert a == ref_a # 두객체는 동일
del a, ref_a # 참조하는 변수 삭제
assert r() is None # 원본객체가 삭제되면 None을 반환함
finalize
Returns a callable finalizer object which will be called when obj is garbage collected. Unlike an ordinary weak reference, a finalizer will always survive until the reference object is collected, greatly simplifying lifecycle management.
A finalizer is considered alive until it is called (either explicitly or at garbage collection), and after that it is dead. Calling a live finalizer returns the result of evaluating func(*arg, **kwargs), whereas calling a dead finalizer returns None.
A representative example is tempfile.TemporaryDirectory.
class TemporaryDirectory(object):
def __init__(self, suffix=None, prefix=None, dir=None):
self._finalizer = _weakref.finalize(self, self._cleanup, self.name, warn_message="Implicitly cleaning up {!r}".format(self))
# ...
@classmethod
def _cleanup(cls, name, warn_message):
cls._rmtree(name)
# ...