LRU cache

Albert-Jan Roskam sjeik_appie at hotmail.com
Sat Feb 18 05:38:56 EST 2023


   I sometimes use this trick, which I learnt from a book by Martelli.
   Instead of try/except, membership testing with "in" (__contains__) might
   be faster. Probably "depends". Matter of measuring.
   def somefunc(arg, _cache={}):
       if len(_cache) > 10 ** 5:
           _cache.pop()
       try:
           return _cache[arg]
       except KeyError:
           result = expensivefunc(arg)
           _cache[arg] = result
           return result
   Albert-Jan


More information about the Python-list mailing list