示例工程 12-decorators-functools

12-decorators-functools/03-lru-cache-stats/lru_cache_stats.py

python · 1.0 KB

"""演示 lru_cache 的命中统计、淘汰与不可哈希参数。"""
 
from __future__ import annotations
 
from functools import lru_cache
 
calls: list[str] = []
 
 
@lru_cache(maxsize=2)
def fetch(key: str) -> str:
    calls.append(key)
    return key.upper()
 
 
def main() -> None:
    calls.clear()
    fetch.cache_clear()
    fetch("a")
    fetch("a")
    fetch("b")
    info = fetch.cache_info()
    print(f"hits: {info.hits}, misses: {info.misses}, currsize: {info.currsize}")
    print(f"computed: {calls}")
    fetch("c")
    fetch("a")
    info = fetch.cache_info()
    print(f"after evict: hits: {info.hits}, misses: {info.misses}, currsize: {info.currsize}")
    fetch.cache_clear()
    info = fetch.cache_info()
    print(f"cleared: hits: {info.hits}, misses: {info.misses}")
    try:
        fetch(["unhashable"])  # type: ignore[arg-type]  # 演示不可哈希参数
    except TypeError as exc:
        print(f"unhashable: {exc}")
 
 
if __name__ == "__main__":
    main()