惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The GitHub Blog
The GitHub Blog
云风的 BLOG
云风的 BLOG
T
Threatpost
WordPress大学
WordPress大学
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
PCI Perspectives
PCI Perspectives
T
The Exploit Database - CXSecurity.com
Y
Y Combinator Blog
雷峰网
雷峰网
爱范儿
爱范儿
The Hacker News
The Hacker News
Last Week in AI
Last Week in AI
Simon Willison's Weblog
Simon Willison's Weblog
T
Tor Project blog
S
Securelist
宝玉的分享
宝玉的分享
L
LangChain Blog
O
OpenAI News
AI
AI
P
Privacy International News Feed
L
LINUX DO - 最新话题
D
DataBreaches.Net
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Attack and Defense Labs
Attack and Defense Labs
罗磊的独立博客
M
MIT News - Artificial intelligence
Security Archives - TechRepublic
Security Archives - TechRepublic
月光博客
月光博客
博客园 - 【当耐特】
T
Tailwind CSS Blog
C
Cybersecurity and Infrastructure Security Agency CISA
H
Help Net Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园_首页
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Hacker News - Newest:
Hacker News - Newest: "LLM"
腾讯CDC
Jina AI
Jina AI
The Last Watchdog
The Last Watchdog
K
Kaspersky official blog
Webroot Blog
Webroot Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Blog — PlanetScale
Blog — PlanetScale
MyScale Blog
MyScale Blog
MongoDB | Blog
MongoDB | Blog
P
Proofpoint News Feed
Recorded Future
Recorded Future
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 三生石上(FineUI控件)
The Cloudflare Blog

又见苍岚

COLMAP PatchMatch Stereo 算法详解 事件驱动的状态机框架:从理论到工程实践 Git 在国内网络环境下无法 Push 的排查与修复 —— 配置 Clash 代理 分段五次多项式插值原理详解 路径插值方法深度对比研究 Claude Code 使用指南 OpenClaw 记忆管理与技能创建指南 CBS(Conflict-Based Search)算法详解 A* 算法及其变种详解 OpenClaw 配置多 Agents Windows Powershell 无法加载文件,因为在此系统上禁止运行脚本问题的解决方案 MaxClaw 安装流程 大模型 AI 名词介绍 AList 网盘聚合工具简介 Protobuf 简介与测试 Claude Code 简介以及 GLM 4.7 模型接入 Github 歌词下载工具 163MusicLyrics Python TypedDict 机器人仿真平台 Gazebo 安装记录 机器人仿真平台 Gazebo 简介 多机器人路径规划问题(Multi-Agent Path Finding, MAPF)简介 Python exifread 读取修改过的 jpeg 信息错误问题修复 3D 坐标系变换的理解 3D 旋转矩阵基本概念 MongoDB Compass 介绍 Python 环境管理工具 uv Flutter 开发指南 Snipaste 安装下载与黑屏问题解决方案 全局路径规划算法记录 2025 Python 版本性能测试 Flutter Hello World Flutter 安装环境配置 Ubuntu VMware 硬盘扩容后 SMBus Host controller not enabled 报错问题解决 Python NetworkX 教程 Docker GPU 报错 - Failed to initialize NVML Unknown Error 解决方案 Python matplotlib 图表绘制 cuda-toolkit 安装替代 Cuda 与 Cudnn Jinja2 Python 利用 docxtpl 和 Jinja2 生成基于模板的 Word 文档 Docker 实现 CPU 核心隔离 LoFTR 基于 Transformer 的特征提取匹配算法 OmniGlue 特征匹配 SuperGlue 使用图神经网络学习特征匹配 Ubuntu 下将 xlsx 文件按照 sheet 转换为 图片 Python 使用 SQLAlchemy Python FastAPI 教程 openwrt 软路由配置安装 Nav2 地图文件(PGM/YAML)规范标准 3D OBJ 模型转换为 glb 瓦片格式 Python 源码 Redis 数据库介绍 Ubuntu 22.04 内核自动升级导致 MongoDB 7.0.12 错误记录 ubuntu 20.04 安装 ROS Noetic ubuntu 18.04 安装 ROS Melodic VMware Workstation Pro 个人免费版下载、安装、使用指南 Hybrid A-star 路径规划 Reeds-Shepp 曲线 Dubins 曲线 Linux kvm 虚拟机网络不通的问题解决方法 Ubuntu 自动内存清理 BiliBili 缓存视频转 mp4 Python 求解线性规划 3D Gaussian Splatting 官方源码实践记录 ImageMagick 教程 Ubuntu 22.04 安装 Colmap 对数几率 odds Ubuntu nmcli 网络管理工具使用指南 SuperPoint 自监督深度学习特征点提取 SyncTV Music Tag Web 在线音乐信息整理工具 ncm 格式转 mp3 MusicBrainz 音乐元数据百科数据库 Ubuntu 网络流量监控工具 私人云音乐平台 Navidrome 入门 手眼标定 四元数(Quaternions) OHTTPS 实现免费自动 https 证书申请、更新、部署 ubuntu 22.04 安装 CloudCompare 单机 KVM 虚拟机冷迁移 Ubuntu 22.04 使用 mdadm 实现软 raid 小鱼 一键安装 ROS-humble Fluid -46- 基于 Simpletex API 构建公式识别页面 公式识别 API 简介 -- Simpletex 使用 Python web 部署库 waitress 3D Gaussian Splatting for Real-Time Radiance Field Rendering Ubuntu Swap 简介与空间扩展 Ubuntu 24.04 安装 forticlient Clash Verge 使用 MongoDB 7.0.17 集群 Docker 构建源码 Error code - 2013. Lost connection to MySQL server during query 问题解决 Python 日志记录库 loguru 使用指北 Python 实现 Web 日志查看服务 MySQL LOAD DATA LOCAL INFILE 极速数据加载 Image size exceeds limit of 89478485 pixels 解决方案 Docker 使用 NVIDIA GPU 驱动错误解决 阿里云 docker 镜像仓库 Ubuntu中没有wired connected的解决方案 MinIO 简介 subconverter 代理订阅格式转换 修复 node –openssl-legacy-provider is not allowed in NODE_OPTIONS 错误 Ubuntu 使用 Clash For Linux 客户端
Python __getattr__ 懒加载
Yiwei Zhang · 2025-12-18 · via 又见苍岚

__getattr__ 可以实现包的懒加载,它的核心思想是:当用户在模块中访问一个尚未定义的属性时,Python 会调用 __getattr__(name) 方法。我们可以在这里拦截请求,动态导入对应的模块。

以我的 vvdutils 库为例,这个库中包含了 MongoGridFSConnection 模块,用户可以调用 from vvdutils import MongoGridFSConnection 引用该功能,如果用 __getattr__ 的视角来看这个过程是这样的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# ./__init__.py
"""
vvdutils 主模块。
数据库连接类已启用懒加载,仅在首次访问时导入。
"""

# 1. 定义公开的接口,这有助于工具进行代码分析、自动补全和生成文档。
# 这里列出所有你希望用户从包顶级直接访问的类名。
__all__ = [
'MongoGridFSConnection', # 对应 mongofs.connect.MongoGridFSConnection
'MysqlConnection', # 对应 mysql.connect.MysqlConnection
# 未来可以轻松地在这里添加新的类名,例如:
# 'RedisConnection',
# 'PostgresConnection',
]

# 2. 核心:定义懒加载映射表。
# 格式:'对外暴露的属性名': ('模块路径', '实际类名')
# 模块路径相对于当前包(vvdutils),使用点号分隔。
_LAZY_IMPORTS = {
'MongoGridFSConnection': ('mongofs.connect', 'MongoGridFSConnection'),
'MysqlConnection': ('mysql.connect', 'MysqlConnection'),
# 未来添加新模块时,只需在此增加一行映射即可。
# 'RedisConnection': ('redis.connect', 'RedisConnection'),
}

# 3. 实现 __getattr__ 函数
def __getattr__(name: str):
"""
当试图访问本模块中不存在的属性时被调用。
用于实现类(尤其是重量级数据库连接类)的懒加载。
"""
if name in _LAZY_IMPORTS:
# 根据映射表获取模块路径和类名
module_path, class_name = _LAZY_IMPORTS[name]

# 动态导入模块。__import__ 返回顶级模块,getattr 逐级深入获取子模块。
# level=0 表示绝对导入。
module = __import__(module_path, fromlist=[class_name], level=0)

# 从模块中获取我们需要的具体类
klass = getattr(module, class_name)

# 【关键】将获取到的类缓存到本模块的全局变量中。
# 这样后续再次访问该属性时,Python会直接找到它,不会再触发 __getattr__。
globals()[name] = klass

return klass

# 如果请求的属性名不在我们的懒加载映射表中,则抛出标准的 AttributeError。
raise AttributeError(f"module '{__name__}' has no attribute '{name}'")

# 4. 实现 __dir__ 函数
def __dir__():
"""
返回模块中可用的属性名列表。
这对于 IDE 的自动补全和交互式环境(如 IPython)的 tab 补全至关重要。
"""
# 合并:内置属性、已加载的属性、以及我们声明支持懒加载但尚未加载的属性。
attrs = set(globals().keys()) # 当前已存在于全局作用域中的名称
attrs.update(_LAZY_IMPORTS.keys()) # 加上所有我们声明支持懒加载的名称
attrs.update(['__all__', '__doc__', '__getattr__', '__dir__']) # 确保特殊方法也在列表中
return sorted(attrs)

# 【可选但推荐】初始化提示
# 可以在这里导入一些轻量级的工具模块,它们不影响启动速度。
# 例如,如果你的 `utils` 模块很轻量,可以正常导入:
# from . import utils

# 注意:我们在这里并没有导入 mongofs 或 mysql,它们将在被访问时按需加载。