Python cached_property 实战:实例缓存、del 失效与五个容易误判的边界
把一个方法改成 functools.cached_property 很简单,真正容易踩坑的是结果存在多久、什么时候失效,以及它究竟是不是只读属性。本文用五个可以分别复制运行的小程序,把缓存看得见地放进实例字典,再逐项验证依赖变化、赋值、异常与槽位限制。
以下代码仅使用 Python 标准库,已在 CPython 3.12.14 与 CPython 3.13.5 上分别以普通模式和 -O 优化模式运行。每段都自带 require 检查,条件不满足会明确抛出 RuntimeError,因此验证不会像 assert 那样被 -O 删除。输出展示的是实际顺序行为,不是性能基准,也不是并发保证。
配图说明:模型生成的概念示意图,以独立容器表现各实例分别保存结果,以移出的缓存块表现失效;图中箭头仅作视觉引导,不表示两个实例共享缓存;不是 Python 调试器截图,也不表示线程只会计算一次。
一、先看缓存放在哪里:不是所有实例共用一份
如果某个对象的统计结果计算较贵,而且输入在使用期间不变,可以把计算写成 cached_property。调用方仍然用 obj.total 读取属性,不必记住额外的缓存方法。第一次访问之前,构造函数已经运行,但统计结果尚未计算;成功读取后,同名结果会写入这个实例的属性字典。下面用两个对象区分“类上定义一个描述器”和“每个对象各自保存结果”。
from functools import cached_property
def require(condition, message):
if not condition:
raise RuntimeError(message)
class Report:
def __init__(self, values):
self.values = tuple(values)
self.calls = 0
@cached_property
def total(self):
self.calls += 1
return sum(self.values)
a = Report([2, 3])
b = Report([10, 20])
require("total" not in a.__dict__, "a must start uncached")
require("total" not in b.__dict__, "b must start uncached")
print("before:", a.calls, b.calls)
first = a.total
second = a.total
require((first, second) == (5, 5), "a value mismatch")
require(a.calls == 1, "sequential reads must reuse a cache")
require(b.calls == 0, "a must not initialize b")
require(a.__dict__["total"] == 5, "cache must be on a")
other = b.total
require(other == 30 and b.calls == 1, "b cache mismatch")
print("a reads:", first, second)
print("b read:", other)
print("calls:", a.calls, b.calls)
准确输出:
before: 0 0 a reads: 5 5 b read: 30 calls: 1 1
这里的 calls 是教学用计数器,不是性能测量。对 a 连续读取两次后,b 仍未计算;只有读取 b.total 才初始化 b 的结果。tuple 只是把这个例子的整数输入固定为一个序列,并不把整个 Report 对象变成不可变对象:重新赋值 a.values 仍然可能制造过期缓存。缓存是否安全,取决于实际依赖的生命周期,而不只是容器的名字。
二、依赖列表变了,缓存不会自动知道
购物篮求和只用于展示依赖变化,不表示金额计算应该依赖这种简化模型。先读取总和,再给列表追加一项,此时缓存仍然存在,所以再次读取拿到的是旧数字。失效动作必须由程序明确执行。del basket.total 删除的是实例上的已缓存结果,不是类上的方法,也不是 prices 列表。
from functools import cached_property
def require(condition, message):
if not condition:
raise RuntimeError(message)
class Basket:
def __init__(self, prices):
self.prices = list(prices)
self.calls = 0
@cached_property
def total(self):
self.calls += 1
return sum(self.prices)
basket = Basket([10, 20])
first = basket.total
require(first == 30 and basket.calls == 1, "initial sum mismatch")
basket.prices.append(5)
stale = basket.total
require(stale == 30, "mutation must not auto-invalidate the cache")
require(sum(basket.prices) == 35, "underlying prices must have changed")
require(basket.calls == 1, "stale read must not call the getter")
del basket.total
require("total" not in basket.__dict__, "del must remove the cached entry")
require(basket.calls == 1, "del itself must not recompute")
fresh = basket.total
require(fresh == 35 and basket.calls == 2, "fresh sum mismatch")
print("initial:", first)
print("after append:", stale)
print("after del and read:", fresh)
print("getter calls:", basket.calls)
准确输出:
initial: 30 after append: 30 after del and read: 35 getter calls: 2
注意顺序:删除本身不做重新计算,下一次读取才会执行 getter。如果对象还没生成过该缓存,直接 del 对应属性通常会抛出 AttributeError;不能把删除不存在的缓存当成无条件安全的操作。对这个普通实例,可以用 basket.__dict__.pop("total", None) 做可重复失效。实际业务更适合把依赖修改和失效放到同一个更新方法里,并避免调用者从外部直接改列表;否则你很难检查每个写入入口是否都清掉了缓存。这个建议只解决单线程更新流程,不构成并发同步方案。
三、手动赋值会覆盖缓存,也能跳过首次计算
cached_property 与没有 setter 的普通 property 有一个重要区别:它允许给同名实例属性赋值。下面先写入 99,此时 getter 一次也没有执行。删除这项手工值后,下一次访问才恢复正常计算;之后写入 -1,又把已经计算出的结果覆盖掉。
from functools import cached_property
def require(condition, message):
if not condition:
raise RuntimeError(message)
class Estimate:
def __init__(self, base):
self.base = base
self.calls = 0
@cached_property
def doubled(self):
self.calls += 1
return self.base * 2
item = Estimate(10)
item.doubled = 99
require(item.doubled == 99 and item.calls == 0, "assignment must bypass getter")
print("assigned before read:", item.doubled)
del item.doubled
computed = item.doubled
require(computed == 20 and item.calls == 1, "delete must restore computation")
print("computed after delete:", computed)
item.doubled = -1
require(item.doubled == -1, "assignment must replace the cached value")
require(item.__dict__["doubled"] == -1, "replacement must live on the instance")
require(item.calls == 1, "replacement must not call the getter")
print("assigned after read:", item.doubled)
print("getter calls:", item.calls)
准确输出:
assigned before read: 99 computed after delete: 20 assigned after read: -1 getter calls: 1
因此,不要把它当成只读字段或数据校验边界。即使计算方法内部写了输入检查,同名属性被预先赋值以后,读取路径也可能完全绕过该方法。若接口必须拒绝外部赋值,应该重新选择属性设计,而不是依赖 cached_property 的名称。手动覆盖适合明确允许替换结果的测试或对象装配场景,但需要让维护者知道这是一项受支持的操作。
四、getter 抛出异常后,下次读取还会尝试
这里模拟第一次准备不足、第二次才成功的本地对象,不发网络请求,也不使用随机数。第一次 getter 抛出 ValueError,调用者接到异常;实例字典里还没有 payload 的成功结果。第二次访问因此重新执行 getter,第三次才复用已经得到的字符串。
from functools import cached_property
def require(condition, message):
if not condition:
raise RuntimeError(message)
class Loader:
def __init__(self):
self.calls = 0
@cached_property
def payload(self):
self.calls += 1
if self.calls == 1:
raise ValueError("not ready")
return "ready"
loader = Loader()
try:
loader.payload
except ValueError as exc:
require(str(exc) == "not ready", "unexpected error")
print("first read:", type(exc).__name__)
else:
raise RuntimeError("the first read must fail")
require("payload" not in loader.__dict__, "a failed getter must not cache a result")
require(loader.calls == 1, "the first attempt must be recorded")
second = loader.payload
third = loader.payload
require(second == "ready" and third == "ready", "retry result mismatch")
require(loader.calls == 2, "success must stop sequential retries")
require(loader.__dict__["payload"] == "ready", "successful result must be cached")
print("second read:", second)
print("third read:", third)
print("getter calls:", loader.calls)
准确输出:
first read: ValueError second read: ready third read: ready getter calls: 2
这并不等于装饰器自带重试策略:它不会自动循环、退避、限制次数,也不会撤销失败前发生的副作用。示例中的 calls 就保留了第一次失败产生的变化。如果 getter 在抛错前写了文件或触发了外部操作,下一次读取可能再次做这些事。按 CPython 3.12.14 实现的执行顺序,先调用被包装的方法,得到返回值以后才写入缓存;这个例子的异常不会成为缓存值。若 getter 自己修改了同名属性,那是另外的程序行为,不应混为装饰器替你缓存了异常。
五、使用 slots 时,先确认实例有没有可写字典
缓存必须有位置保存。第一个类只声明 value 槽位,没有实例字典,因此创建对象没有问题,但读取 doubled 时会抛出 TypeError。第二个类在槽位列表里明确包含 __dict__,同名缓存就能写入字典。为使输出不受异常文案细节影响,示例只打印异常类型。
from functools import cached_property
def require(condition, message):
if not condition:
raise RuntimeError(message)
class Compact:
__slots__ = ("value",)
def __init__(self, value):
self.value = value
@cached_property
def doubled(self):
return self.value * 2
class Flexible:
__slots__ = ("value", "calls", "__dict__")
def __init__(self, value):
self.value = value
self.calls = 0
@cached_property
def doubled(self):
self.calls += 1
return self.value * 2
compact = Compact(7)
require(not hasattr(compact, "__dict__"), "Compact must have no instance dictionary")
try:
compact.doubled
except TypeError:
print("slots without dict: TypeError")
else:
raise RuntimeError("a cache without an instance dictionary must fail")
flexible = Flexible(7)
require("doubled" not in flexible.__dict__, "Flexible must start uncached")
first = flexible.doubled
second = flexible.doubled
require((first, second) == (14, 14), "slot-backed value mismatch")
require(flexible.calls == 1, "Flexible must reuse its cached value")
require(flexible.__dict__["doubled"] == 14, "cache must use the instance dictionary")
print("slots with dict:", first, second)
print("getter calls:", flexible.calls)
准确输出:
slots without dict: TypeError slots with dict: 14 14 getter calls: 1
这不是“所有使用 slots 的类都不能缓存”。继承关系可能让实例已经拥有字典;真正要检查的是实例是否提供可写的 __dict__。同时,加入字典会改变原本纯槽位对象的存储取舍,不应在追求大量紧凑实例的模型里不加分析地照搬。可以选择每次计算的 property,或显式设计自己的缓存槽位与失效方法;本文不把这些不同的缓存策略当成完全等价替换。
Python 3.12 的并发边界:不要推导“恰好一次”
Python 官方文档与 3.12 迁移说明都指出:3.12 之前的 cached_property 曾有一个未文档化的锁;它按属性而不是按实例设置,不同实例访问同一属性也可能发生锁争用。从 Python 3.12 开始,这个锁被移除。同一实例发生并发首次读取时,getter 可能执行不止一次。官方迁移说明明确说明了这个改变。
不要把前面单线程计数器出现的 1 推广成并发承诺,也不要把解释器存在 GIL 当成这段业务初始化的互斥协议。如果重复计算没有副作用,且依赖保持稳定,重复求值也许可以接受;如果结果初始化会收费、写入外部状态或者必须唯一,就不能仅靠 cached_property 保障。需要围绕访问和依赖修改设计同一套同步规则。仅把 getter 里的计算包进锁,却不检查是否已经初始化,也可能只是把重复计算排队执行,仍然不能自动得到“只做一次”。本文没有运行并发性能基准,也不报告吞吐提升或线程安全结论。
选择前的三个问题
- 依赖是否足够稳定?若数据每次读取前都可能变化,普通 property 的重新计算可能更直观,缓存反而增加维护成本。
- 谁负责失效?应先确定更新入口,再决定使用 del 清除单个实例的结果,而不是寄希望于装饰器追踪列表内部变化。
- 是否接受赋值与重复执行?公开接口的只读要求、失败副作用和并发初始化,应分别设计,不能让一个缓存装饰器承担所有职责。
从属性查找规则看,cached_property 属于非数据描述器:实例字典中的同名项优先,这解释了为什么成功缓存后可以直接读取,也解释了为什么赋值能够遮蔽计算逻辑。Python 的描述器指南给出了查找优先级。理解这个机制之后,del 就不再像一个神秘的“刷新按钮”,它只是让下次查找重新到达类上的描述器。
核验范围与一手资料
五段程序都是独立示例,共完成两个解释器、两种启动模式下的二十次正常执行,逐字比较标准输出;另有二十次故意破坏预期条件的负向测试,确认检查会失败而非被优化掉。测试结论限于文中可复现的顺序行为。异常重试的解释另对照 CPython 3.12.14 源码,不把实现细节扩张为所有 Python 实现的额外保证。
- Python 官方 functools.cached_property 文档:同名属性读写、删除失效、实例字典要求与版本变化。
- Python 3.12 官方迁移说明:删除未文档化锁后的并发注意事项。
- CPython 3.12.14 的 functools.py:getter 调用与缓存写入的先后顺序。
- Python 3.12 描述器指南与数据模型的 slots 说明:查找优先级与实例字典的存储条件。


