【python基础】weakref的初次遇见

我们先来看一段代码

python 复制代码
class DatabaseConnection:
    """模拟数据库连接"""

    def __init__(self, db_name):
        self.db_name = db_name
        print(f"连接到数据库 {db_name}")

    def __del__(self):
        print(f"关闭数据库连接 {self.db_name}")


cache = {}

cache["db1"] = DatabaseConnection("my_database")
print("删除 cache 中的 db1 前,cache 内容:", cache)
del cache["db1"]
print("删除 cache 中的 db1 后,cache 内容:", cache)
import gc
gc.collect()  # 手动触发垃圾回收
print("手动触发垃圾回收后,cache 内容:", cache)

print("-" * 50)

输出结果:

python 复制代码
连接到数据库 my_database

删除 cache 中的 db1 前,cache 内容: {'db1': <__main__.DatabaseConnection object at 0x7fb3cc333430>}

关闭数据库连接 my_database

删除 cache 中的 db1 后,cache 内容: {}

手动触发垃圾回收后,cache 内容: {}

​ 这是一个简易的数据库连接管理器。DatabaseConnection类,模拟了一个数据库的连接,字典cache存储数据库的连接对象,我们通过 del删除字典中的 db1条目,但python的回收机制是引用回收,cache字典仍然持有数据库连接对象的引用,因此对象的内存不会立即被释放,如果我们这次连接结束,如果后续不断创建新的数据库连接对象并添加到字典中,那这个字典会越来越大。这时候,我们需要手动的去触发回收垃圾,每次这样子清理非常的麻烦。 ​ 这时候我们就可以使用weakref(弱引用)来缓存数据库的连接,这样子数据库连接对象在没有其他强引用时被自动回收。

python 复制代码
import weakref

class DatabaseConnection:
    """模拟数据库连接"""

    def __init__(self, db_name):
        self.db_name = db_name
        print(f"连接到数据库 {db_name}")

    def __del__(self):
        print(f"关闭数据库连接 {self.db_name}")


cache = weakref.WeakValueDictionary()

db_connection = DatabaseConnection("my_database")
cache["db1"] = db_connection
print("删除 db_connection 前,cache 内容:", dict(cache))
del db_connection
print("删除 db_connection 后,cache 内容:", dict(cache))

输出结果:

python 复制代码
连接到数据库 my_database

删除 db_connection 前,cache 内容: {'db1': <__main__.DatabaseConnection object at 0x7fb3cdb8d2e0>}

关闭数据库连接 my_database

删除 db_connection 后,cache 内容: {}
python"""
相关推荐
疯狂踩坑人6 小时前
【Python版 2026 从零学Langchain 1.x】(二)结构化输出和工具调用
后端·python·langchain
HDO清风7 小时前
CASIA-HWDB2.x 数据集DGRL文件解析(python)
开发语言·人工智能·pytorch·python·目标检测·计算机视觉·restful
weixin_499771557 小时前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
weixin_452159557 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
多米Domi0117 小时前
0x3f 第48天 面向实习的八股背诵第五天 + 堆一题 背了JUC的题,java.util.Concurrency
开发语言·数据结构·python·算法·leetcode·面试
深蓝海拓7 小时前
PySide6从0开始学习的笔记(二十六) 重写Qt窗口对象的事件(QEvent)处理方法
笔记·python·qt·学习·pyqt
纠结哥_Shrek7 小时前
外贸选品工程师的工作流程和方法论
python·机器学习
小汤圆不甜不要钱7 小时前
「Datawhale」RAG技术全栈指南 Task 5
python·llm·rag
A懿轩A8 小时前
【Java 基础编程】Java 变量与八大基本数据类型详解:从声明到类型转换,零基础也能看懂
java·开发语言·python