代码备忘录

好记性不如烂笔头

2026.3.1
全面拥抱 Pathlib,抛弃 os.path

以前拼路径老是用 os.path.join,层级一多代码写得特别长,还容易漏斜杠。现在强迫自己全换成面向对象的 pathlib,操作起来舒服多了,跨平台兼容性也更好。

from pathlib import Path

# 获取当前脚本所在目录的上级目录中的 data 文件夹
base_dir = Path(__file__).resolve().parent.parent
data_file = base_dir / 'data' / 'config.json'

# 判断文件是否存在并读取
if data_file.exists():
    text = data_file.read_text(encoding='utf-8')

2025.11.7
f-string 调试打印的语法糖

Python 3.8 以后 f-string 加了个 = 的小特权,本地断点调试或者打日志的时候太方便了,不用再像以前那样傻傻地写 print(f"user_id: {user_id}") 了。

user_id = 89757
status = "active"
retry_count = 3

# 直接打印变量名和值
print(f"{user_id=}, {status=}, {retry_count=}")
# 输出结果: user_id=89757, status='active', retry_count=3

2025.2.25
字典取值防错与 defaultdict

解析外部 API 返回的 JSON 数据时,直接 data['key'] 经常遇到 KeyError 导致服务挂掉。除了用 .get() 给默认值,遇到需要分组聚合的场景,直接上 defaultdict 最省事,省去了判断 key 在不在的恶心逻辑。

from collections import defaultdict

logs = [('error', 'timeout'), ('info', 'login'), ('error', 'db_crash')]
log_dict = defaultdict(list)

# 不用先写 if level in log_dict 判断了
for level, msg in logs:
    log_dict[level].append(msg)

print(dict(log_dict))
# {'error': ['timeout', 'db_crash'], 'info': ['login']}

2024.6.2
接手老代码:加上 Type Hints 救命

虽然 Python 是动态语言一时爽,但接手别人几千行的无注释老项目真的会抓狂。现在自己写公共函数习惯顺手把参数和返回值的类型提示(Type Hints)加上,配合 IDE 的自动推导,能提前规避很多低级类型 bug。

from typing import List, Dict, Optional

def process_user_data(users: List[Dict[str, str]], threshold: int) -> Optional[float]:
    if not users:
        return None
    # 业务逻辑省略
    return 99.9