Python:weakref
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
obj
가 가비지 수거될 때 호출되는 콜러블 파이널라이저 객체를 반환합니다. 일반적인 약한 참조와 달리, 파이널라이저는 참조 객체가 수집될 때까지 항상 생존하므로, 수명 주기 관리가 크게 간소화됩니다.
파이널라이저는 (명시적으로나 가비지 수거에서) 호출될 때까지 살아있다고 간주하며, 그 후 죽습니다. 살아있는 파이널라이저를 호출하면 func(*arg, **kwargs)
를 평가한 결과가 반환되고, 죽은 파이널라이저를 호출하면 None
이 반환됩니다.
대표적인 예시는 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)
# ...