建立函数及其参数的结果缓存

from functools import wraps
import time

class CacheManager:
    def __init__(self):
        self._cache = {}

    def get_cache_obj(self, key):
        """获取缓存对象"""
        return self._cache.get(key)

    def add_cache_obj(self, key, obj):
        """添加缓存对象"""
        self._cache[key] = obj
        return obj

    def __del__(self):
        """清除所有缓存对象"""
        # print(f"CacheManager del")
        for k, v in self._cache.items():
            # print(f"CacheManager del:{k=}")
            del v
        self._cache.clear()
        del self._cache

    @classmethod
    def cache_result(cls, func):
        """
        装饰器:缓存结果,支持参数作为缓存的唯一键。
        """

        @wraps(func)
        def wrapper(instance, *args, **kwargs):
            # 根据函数名和参数构建唯一缓存键
            key = f"{func.__name__}:{args}:{kwargs}"
            print(key)

            # 检查是否已缓存
            cache_obj = instance.cache_manager.get_cache_obj(key)
            if cache_obj is not None:
                print(cache_obj)
                return cache_obj

            # 缓存中没有对象,执行函数并缓存结果
            result = func(instance, *args, **kwargs)
            instance.cache_manager.add_cache_obj(key, result)
            print(result)
            return result

        return wrapper

class MyClass:
    def __init__(self):
        self.cache_manager = CacheManager()

    def __del__(self):
        print("MyClass.__del__")

    @property
    @CacheManager.cache_result
    def oms_user(self):
        # 该代码只在缓存不存在时执行
        # return [1, 2, 3]
        return time.time()


def test_cache():
    m = MyClass()
    print(id(m.oms_user))
    print(id(m.oms_user))

test_cache()

结果

oms_user:():{}
1732000987.240014
2584475181488
oms_user:():{}
1732000987.240014
2584475181488
MyClass.__del__

Python cache 内存泄漏问题

创建于2411191534,修改于2411191534

posted @ 2024-11-19 15:35  园糯  阅读(1)  评论(0编辑  收藏  举报