3 ms·
Reminds me of the Python trap that I fall into every few months because I forget about it: def foo(mylist=[]): mylist.append("a") return mylist mylist
by skocznymroczny 6y ago
Reminds me of the Python trap that I fall into every few months because I forget about it:
def foo(mylist=[]):
mylist.append("a")
return mylist
mylist is only initialized once, so the function will actually return one more "a" with each function execution
- klyrs 6y agoIt's a feature! Use this memoization pattern and you'll never forget it def foo(x, cache={}): if x in cache: return cache[x] val = cache[x] = x*x+1 return val But, be warned, there's no mechanism for cache eviction; use @lru_cache if you don't know ahead of time that x will take a reasonably small number of values