Using @functools.lru_cache with dictionary arguments

前端 未结 6 2032
栀梦
栀梦 2020-12-24 12:16

I have a method that takes (among others) a dictionary as an argument. The method is parsing strings and the dictionary provides replacements for some substrings, so it does

6条回答
  •  醉酒成梦
    2020-12-24 12:49

    Here is a decorator that use @mhyfritz trick.

    def hash_dict(func):
        """Transform mutable dictionnary
        Into immutable
        Useful to be compatible with cache
        """
        class HDict(dict):
            def __hash__(self):
                return hash(frozenset(self.items()))
    
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            args = tuple([HDict(arg) if isinstance(arg, dict) else arg for arg in args])
            kwargs = {k: HDict(v) if isinstance(v, dict) else v for k, v in kwargs.items()}
            return func(*args, **kwargs)
        return wrapped
    

    Simply add it before your lru_cache.

    @hash_dict
    @functools.lru_cache()
    def your_function():
        ...
    

提交回复
热议问题