title: Own lru_cache decorator in python
body: <p>I can't understand, why my own decorator &quot;lru cache&quot; doens't work.</p>
  <pre><code>def cache(max_size: int):
    
      dictionary = OrderedDict()
  
      def trace(func):
          @functools.wraps(func)
          def wrapper(*args, **kwargs):
              cache_key = args + tuple(kwargs.items())
              if (cache_key not in dictionary) and (len(dictionary) &lt; max_size):
                  dictionary[cache_key] = func(*args, **kwargs)
              elif (cache_key not in dictionary) and (len(dictionary) == max_size):
                  dictionary.popitem(last=False)
                  dictionary[cache_key] = func(*args, **kwargs)
              else:
                  old_cache = dictionary[cache_key]
                  del dictionary[cache_key]
                  dictionary[cache_key] = old_cache
  
              return dictionary[cache_key]
  
          return wrapper
  
      return trace
  
  @cache(20)
  def binomial(n: int, k: int):
      if k &gt; n:
          return 0
      if k == 0:
          return 1
      return binomial(n - 1, k) + binomial(n - 1, k - 1)
  
  binomial(30, 1)
  </code></pre>
  <p>ERRORS:</p>
  <pre><code>Traceback (most recent call last):
    File &quot;main.py&quot;, line 33, in &lt;module&gt;
      binomial(30, 1)
    File &quot;main.py&quot;, line 13, in wrapper
      dictionary[cache_key] = func(*args, **kwargs)
    File &quot;main.py&quot;, line 31, in binomial
      return binomial(n - 1, k) + binomial(n - 1, k - 1)
    ...
    File &quot;main.py&quot;, line 13, in wrapper
      dictionary[cache_key] = func(*args, **kwargs)
    File &quot;main.py&quot;, line 31, in binomial
      return binomial(n - 1, k) + binomial(n - 1, k - 1)
    File &quot;main.py&quot;, line 13, in wrapper
      dictionary[cache_key] = func(*args, **kwargs)
    File &quot;main.py&quot;, line 31, in binomial
      return binomial(n - 1, k) + binomial(n - 1, k - 1)
    File &quot;main.py&quot;, line 18, in wrapper
      old_cache = dictionary[cache_key]
  KeyError: (10, 0)
  </code></pre>
  <p>As I understand, that is just recursive errors, but I can't understand why they appear.</p>
  <p>I tried to run this decorator on fibonachi numbers function (fib(10)) with cache capacity of 3, but it return an error. WHY?</p>