python通过weakref 观测实例的生命周期

属于一个简单的业务玩法,系统使用了动态模块加载,同时还有reload 需要观测类实例的gc 情况,解决方法就是使用weakref 添加callback

参考玩法

module = importlib.import_module("my_runner_module")
RunnerClass = module.Runner

# 创建旧实例
old_runner = RunnerClass("old", "req", "v1", ctx)
wref = weakref.ref(old_runner, lambda o: print("旧实例被回收")

说明

以上就是一个记录,利用好weakref 可以方便进行问题拍错

参考资料

https://docs.python.org/3/library/weakref.html

posted on 2026-08-31 08:00  荣锋亮  阅读(2)  评论(0)    收藏  举报

导航