title: is a python memoize decorator process-safe?
body: <p>Is the cache in a standard memoize decorator process-safe?</p>
  
  <p>For example, suppose I define the following decorator:</p>
  
  <pre><code>import functools
  
  def memoize(func):
      cache = {}
      @functools.wraps(func)
      def memoized(*args):
          result = None
          if args in cache:
              result = cache[args]
          else:
              result = func(*args)
              cache[args] = result
          return result
      return memoized
  </code></pre>
  
  <p>and suppose I am trying to use it to speed up computation of a recursive function, say:</p>
  
  <pre><code>@memoize
  def fib(n):
      result = 1
      if n &gt; 1:
          result = fib(n-1) + fib(n-2)
      return result
  </code></pre>
  
  <p>Now I wonder if two processes calculating fib() could ever clash? For example:</p>
  
  <pre><code>if __name__ == "__main__":
      from multiprocessing import Process
      p1 = Process(target=fib, args=(19,))
      p2 = Process(target=fib, args=(23,))
      p1.start()
      p2.start()
      p1.join()
      p2.join()
  </code></pre>
  
  <p>My first thought was that the cache is saved in the context of fib, so it is
  shared between the processes and that could lead to race conditions. But then,
  I think that the worst that could happen is that they would both think that, say,
  fib(17) has not been calculated, and will both go ahead and calculated it in
  parallel and store the same result one after the other- not ideal,
  but not horrible, I guess. But I still wonder if there is a way to do it in a process-safe way.</p>
  
  <p>EDIT: I added a print statement in each of the branches of memoized(),
  and it seems that each process re-calculates all the fib values in the cache.
  Perhaps the cache is not shared, after all? If it is not shared, I wounder
  if there is a process-safe way to share it (to save some more computations).</p>