Thursday, 4 November 2021

Python + mutable return + caching: careful

Let's say

from functools import lru_cache                                         
@lru_cache(5) def cached(n): return {}

Beware then, as:

In [3]: cached(1) == cached(1)                                                  
Out[3]: True

In [4]: cached(1) is cached(1)                                                  
Out[4]: True

In [5]: cached(1)[2] = 3                                                        

In [6]: cached(1)                                                               
Out[6]: {2: 3} 
 
So I suppose - further from the attention paid with parameter default mutability - there are times when it's a good idea to put in the effort and return immutable results whenever there's the slightest chance of caching right at the moment or later on (and being inattentive :) never happens, of course).

No comments:

Post a Comment