【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"""
相关推荐
MO2T15 分钟前
使用 Flask 构建基于 Dify 的企业资金投向与客户分类评估系统
后端·python·语言模型·flask
慢热型网友.18 分钟前
用 Docker 构建你的第一个 Python Flask 程序
python·docker·flask
Naiva18 分钟前
【小技巧】Python + PyCharm 小智AI配置MCP接入点使用说明(内测)( PyInstaller打包成 .exe 可执行文件)
开发语言·python·pycharm
云动雨颤22 分钟前
Python 自动化办公神器|一键转换所有文档为 PDF
运维·python
梅孔立34 分钟前
yum update 报错 Cannot find a valid baseurl for repo: centos-sclo-rh/x86_64 等解决办法
linux·python·centos
前端付豪1 小时前
13、你还在 print 调试🧾?教你写出自己的日志系统
后端·python
这里有鱼汤1 小时前
hvPlot:用你熟悉的 Pandas,画出你没见过的炫图
后端·python
源码站~1 小时前
基于Flask+Vue的豆瓣音乐分析与推荐系统
vue.js·python·flask·毕业设计·毕设·校园·豆瓣音乐
MessiGo1 小时前
Python 爬虫实战 | 国家医保
python
chanalbert1 小时前
Spring 6 源码深度掘金:66+核心原理与高频面试攻坚指南
python·spring·面试